486b7bcb4decb7ccc24bd82b19224e4fc5739564
[platform/upstream/libzypp.git] / zypp / media / MediaCurl.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/media/MediaCurl.cc
10  *
11 */
12
13 #include <iostream>
14 #include <list>
15
16 #include "zypp/base/Logger.h"
17 #include "zypp/ExternalProgram.h"
18 #include "zypp/base/String.h"
19 #include "zypp/base/Gettext.h"
20 #include "zypp/base/Sysconfig.h"
21 #include "zypp/base/Gettext.h"
22
23 #include "zypp/media/MediaCurl.h"
24 #include "zypp/media/ProxyInfo.h"
25 #include "zypp/media/MediaUserAuth.h"
26 #include "zypp/media/CredentialManager.h"
27 #include "zypp/media/CurlConfig.h"
28 #include "zypp/thread/Once.h"
29 #include "zypp/Target.h"
30 #include "zypp/ZYppFactory.h"
31 #include "zypp/ZConfig.h"
32
33 #include <cstdlib>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/mount.h>
37 #include <errno.h>
38 #include <dirent.h>
39 #include <unistd.h>
40 #include <boost/format.hpp>
41
42 #define  DETECT_DIR_INDEX       0
43 #define  CONNECT_TIMEOUT        60
44 #define  TRANSFER_TIMEOUT_MAX   60 * 60
45
46 #define EXPLICITLY_NO_PROXY "_none_"
47
48 #undef CURLVERSION_AT_LEAST
49 #define CURLVERSION_AT_LEAST(M,N,O) LIBCURL_VERSION_NUM >= ((((M)<<8)+(N))<<8)+(O)
50
51 using namespace std;
52 using namespace zypp::base;
53
54 namespace
55 {
56   zypp::thread::OnceFlag g_InitOnceFlag = PTHREAD_ONCE_INIT;
57   zypp::thread::OnceFlag g_FreeOnceFlag = PTHREAD_ONCE_INIT;
58
59   extern "C" void _do_free_once()
60   {
61     curl_global_cleanup();
62   }
63
64   extern "C" void globalFreeOnce()
65   {
66     zypp::thread::callOnce(g_FreeOnceFlag, _do_free_once);
67   }
68
69   extern "C" void _do_init_once()
70   {
71     CURLcode ret = curl_global_init( CURL_GLOBAL_ALL );
72     if ( ret != 0 )
73     {
74       WAR << "curl global init failed" << endl;
75     }
76
77     //
78     // register at exit handler ?
79     // this may cause trouble, because we can protect it
80     // against ourself only.
81     // if the app sets an atexit handler as well, it will
82     // cause a double free while the second of them runs.
83     //
84     //std::atexit( globalFreeOnce);
85   }
86
87   inline void globalInitOnce()
88   {
89     zypp::thread::callOnce(g_InitOnceFlag, _do_init_once);
90   }
91
92   int log_curl(CURL *curl, curl_infotype info,
93                char *ptr, size_t len, void *max_lvl)
94   {
95     std::string pfx(" ");
96     long        lvl = 0;
97     switch( info)
98     {
99       case CURLINFO_TEXT:       lvl = 1; pfx = "*"; break;
100       case CURLINFO_HEADER_IN:  lvl = 2; pfx = "<"; break;
101       case CURLINFO_HEADER_OUT: lvl = 2; pfx = ">"; break;
102       default:                                      break;
103     }
104     if( lvl > 0 && max_lvl != NULL && lvl <= *((long *)max_lvl))
105     {
106       std::string                            msg(ptr, len);
107       std::list<std::string>                 lines;
108       std::list<std::string>::const_iterator line;
109       zypp::str::split(msg, std::back_inserter(lines), "\r\n");
110       for(line = lines.begin(); line != lines.end(); ++line)
111       {
112         DBG << pfx << " " << *line << endl;
113       }
114     }
115     return 0;
116   }
117
118   static size_t
119   log_redirects_curl(
120       void *ptr, size_t size, size_t nmemb, void *stream)
121   {
122     // INT << "got header: " << string((char *)ptr, ((char*)ptr) + size*nmemb) << endl;
123
124     char * lstart = (char *)ptr, * lend = (char *)ptr;
125     size_t pos = 0;
126     size_t max = size * nmemb;
127     while (pos + 1 < max)
128     {
129       // get line
130       for (lstart = lend; *lend != '\n' && pos < max; ++lend, ++pos);
131
132       // look for "Location"
133       string line(lstart, lend);
134       if (line.find("Location") != string::npos)
135       {
136         DBG << "redirecting to " << line << endl;
137         return max;
138       }
139
140       // continue with the next line
141       if (pos + 1 < max)
142       {
143         ++lend;
144         ++pos;
145       }
146       else
147         break;
148     }
149
150     return max;
151   }
152 }
153
154 namespace zypp {
155   namespace media {
156
157   namespace {
158     struct ProgressData
159     {
160       ProgressData(CURL *_curl, const long _timeout, const zypp::Url &_url = zypp::Url(),
161                    callback::SendReport<DownloadProgressReport> *_report=NULL)
162         : curl(_curl)
163         , timeout(_timeout)
164         , reached(false)
165         , report(_report)
166         , drate_period(-1)
167         , dload_period(0)
168         , secs(0)
169         , drate_avg(-1)
170         , ltime( time(NULL))
171         , dload( 0)
172         , uload( 0)
173         , url(_url)
174       {}
175       CURL                                         *curl;
176       long                                          timeout;
177       bool                                          reached;
178       callback::SendReport<DownloadProgressReport> *report;
179       // download rate of the last period (cca 1 sec)
180       double                                        drate_period;
181       // bytes downloaded at the start of the last period
182       double                                        dload_period;
183       // seconds from the start of the download
184       long                                          secs;
185       // average download rate
186       double                                        drate_avg;
187       // last time the progress was reported
188       time_t                                        ltime;
189       // bytes downloaded at the moment the progress was last reported
190       double                                        dload;
191       // bytes uploaded at the moment the progress was last reported
192       double                                        uload;
193       zypp::Url                                     url;
194     };
195
196     ///////////////////////////////////////////////////////////////////
197
198     inline void escape( string & str_r,
199                         const char char_r, const string & escaped_r ) {
200       for ( string::size_type pos = str_r.find( char_r );
201             pos != string::npos; pos = str_r.find( char_r, pos ) ) {
202               str_r.replace( pos, 1, escaped_r );
203             }
204     }
205
206     inline string escapedPath( string path_r ) {
207       escape( path_r, ' ', "%20" );
208       return path_r;
209     }
210
211     inline string unEscape( string text_r ) {
212       char * tmp = curl_unescape( text_r.c_str(), 0 );
213       string ret( tmp );
214       curl_free( tmp );
215       return ret;
216     }
217
218   }
219
220 /**
221  * Fills the settings structure using options passed on the url
222  * for example ?timeout=x&proxy=foo
223  */
224 void fillSettingsFromUrl( const Url &url, TransferSettings &s )
225 {
226     std::string param(url.getQueryParam("timeout"));
227     if( !param.empty())
228     {
229       long num = str::strtonum<long>(param);
230       if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
231           s.setTimeout(num);
232     }
233
234     if ( ! url.getUsername().empty() )
235     {
236         s.setUsername(url.getUsername());
237         if ( url.getPassword().size() )
238             s.setPassword(url.getPassword());
239     }
240     else
241     {
242         // if there is no username, set anonymous auth
243         if ( ( url.getScheme() == "ftp" || url.getScheme() == "tftp" ) && s.username().empty() )
244             s.setAnonymousAuth();
245     }
246
247     if ( url.getScheme() == "https" )
248     {
249         s.setVerifyPeerEnabled(false);
250         s.setVerifyHostEnabled(false);
251
252         std::string verify( url.getQueryParam("ssl_verify"));
253         if( verify.empty() ||
254             verify == "yes")
255         {
256             s.setVerifyPeerEnabled(true);
257             s.setVerifyHostEnabled(true);
258         }
259         else if( verify == "no")
260         {
261             s.setVerifyPeerEnabled(false);
262             s.setVerifyHostEnabled(false);
263         }
264         else
265         {
266             std::vector<std::string>                 flags;
267             std::vector<std::string>::const_iterator flag;
268             str::split( verify, std::back_inserter(flags), ",");
269             for(flag = flags.begin(); flag != flags.end(); ++flag)
270             {
271                 if( *flag == "host")
272                     s.setVerifyHostEnabled(true);
273                 else if( *flag == "peer")
274                     s.setVerifyPeerEnabled(true);
275                 else
276                     ZYPP_THROW(MediaBadUrlException(url, "Unknown ssl_verify flag"));
277             }
278         }
279     }
280
281     Pathname ca_path( url.getQueryParam("ssl_capath") );
282     if( ! ca_path.empty())
283     {
284         if( !PathInfo(ca_path).isDir() || ! ca_path.absolute())
285             ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_capath path"));
286         else
287             s.setCertificateAuthoritiesPath(ca_path);
288     }
289
290     Pathname client_cert( url.getQueryParam("ssl_clientcert") );
291     if( ! client_cert.empty())
292     {
293         if( !PathInfo(client_cert).isFile() || !client_cert.absolute())
294             ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientcert file"));
295         else
296             s.setClientCertificatePath(client_cert);
297     }
298     Pathname client_key( url.getQueryParam("ssl_clientkey") );
299     if( ! client_key.empty())
300     {
301         if( !PathInfo(client_key).isFile() || !client_key.absolute())
302             ZYPP_THROW(MediaBadUrlException(url, "Invalid ssl_clientkey file"));
303         else
304             s.setClientKeyPath(client_key);
305     }
306
307     param = url.getQueryParam( "proxy" );
308     if ( ! param.empty() )
309     {
310         if ( param == EXPLICITLY_NO_PROXY ) {
311             // Workaround TransferSettings shortcoming: With an
312             // empty proxy string, code will continue to look for
313             // valid proxy settings. So set proxy to some non-empty
314             // string, to indicate it has been explicitly disabled.
315             s.setProxy(EXPLICITLY_NO_PROXY);
316             s.setProxyEnabled(false);
317         }
318         else {
319             string proxyport( url.getQueryParam( "proxyport" ) );
320             if ( ! proxyport.empty() ) {
321                 param += ":" + proxyport;
322             }
323             s.setProxy(param);
324             s.setProxyEnabled(true);
325         }
326     }
327
328     param = url.getQueryParam( "proxyuser" );
329     if ( ! param.empty() )
330     {
331       s.setProxyUsername(param);
332       s.setProxyPassword(url.getQueryParam( "proxypass" ));
333     }
334
335     // HTTP authentication type
336     param = url.getQueryParam("auth");
337     if (!param.empty() && (url.getScheme() == "http" || url.getScheme() == "https"))
338     {
339         try
340         {
341             CurlAuthData::auth_type_str2long(param);    // check if we know it
342         }
343         catch (MediaException & ex_r)
344         {
345             DBG << "Rethrowing as MediaUnauthorizedException.";
346             ZYPP_THROW(MediaUnauthorizedException(url, ex_r.msg(), "", ""));
347         }
348         s.setAuthType(param);
349     }
350
351     // workarounds
352     param = url.getQueryParam("head_requests");
353     if( !param.empty() && param == "no" )
354         s.setHeadRequestsAllowed(false);
355 }
356
357 /**
358  * Reads the system proxy configuration and fills the settings
359  * structure proxy information
360  */
361 void fillSettingsSystemProxy( const Url&url, TransferSettings &s )
362 {
363     ProxyInfo proxy_info;
364     if ( proxy_info.useProxyFor( url ) )
365     {
366       // We must extract any 'user:pass' from the proxy url
367       // otherwise they won't make it into curl (.curlrc wins).
368       try {
369         Url u( proxy_info.proxy( url ) );
370         s.setProxy( u.asString( url::ViewOption::WITH_SCHEME + url::ViewOption::WITH_HOST + url::ViewOption::WITH_PORT ) );
371         // don't overwrite explicit auth settings
372         if ( s.proxyUsername().empty() )
373         {
374           s.setProxyUsername( u.getUsername( url::E_ENCODED ) );
375           s.setProxyPassword( u.getPassword( url::E_ENCODED ) );
376         }
377         s.setProxyEnabled( true );
378       }
379       catch (...) {}    // no proxy if URL is malformed
380     }
381 }
382
383 Pathname MediaCurl::_cookieFile = "/var/lib/YaST2/cookies";
384
385 /**
386  * initialized only once, this gets the anonymous id
387  * from the target, which we pass in the http header
388  */
389 static const char *const anonymousIdHeader()
390 {
391   // we need to add the release and identifier to the
392   // agent string.
393   // The target could be not initialized, and then this information
394   // is guessed.
395   static const std::string _value(
396       str::trim( str::form(
397           "X-ZYpp-AnonymousId: %s",
398           Target::anonymousUniqueId( Pathname()/*guess root*/ ).c_str() ) )
399   );
400   return _value.c_str();
401 }
402
403 /**
404  * initialized only once, this gets the distribution flavor
405  * from the target, which we pass in the http header
406  */
407 static const char *const distributionFlavorHeader()
408 {
409   // we need to add the release and identifier to the
410   // agent string.
411   // The target could be not initialized, and then this information
412   // is guessed.
413   static const std::string _value(
414       str::trim( str::form(
415           "X-ZYpp-DistributionFlavor: %s",
416           Target::distributionFlavor( Pathname()/*guess root*/ ).c_str() ) )
417   );
418   return _value.c_str();
419 }
420
421 /**
422  * initialized only once, this gets the agent string
423  * which also includes the curl version
424  */
425 static const char *const agentString()
426 {
427   // we need to add the release and identifier to the
428   // agent string.
429   // The target could be not initialized, and then this information
430   // is guessed.
431   static const std::string _value(
432     str::form(
433        "ZYpp %s (curl %s) %s"
434        , VERSION
435        , curl_version_info(CURLVERSION_NOW)->version
436        , Target::targetDistribution( Pathname()/*guess root*/ ).c_str()
437     )
438   );
439   return _value.c_str();
440 }
441
442 // we use this define to unbloat code as this C setting option
443 // and catching exception is done frequently.
444 /** \todo deprecate SET_OPTION and use the typed versions below. */
445 #define SET_OPTION(opt,val) do { \
446     ret = curl_easy_setopt ( _curl, opt, val ); \
447     if ( ret != 0) { \
448       ZYPP_THROW(MediaCurlSetOptException(_url, _curlError)); \
449     } \
450   } while ( false )
451
452 #define SET_OPTION_OFFT(opt,val) SET_OPTION(opt,(curl_off_t)val)
453 #define SET_OPTION_LONG(opt,val) SET_OPTION(opt,(long)val)
454 #define SET_OPTION_VOID(opt,val) SET_OPTION(opt,(void*)val)
455
456 MediaCurl::MediaCurl( const Url &      url_r,
457                       const Pathname & attach_point_hint_r )
458     : MediaHandler( url_r, attach_point_hint_r,
459                     "/", // urlpath at attachpoint
460                     true ), // does_download
461       _curl( NULL ),
462       _customHeaders(0L)
463 {
464   _curlError[0] = '\0';
465   _curlDebug = 0L;
466
467   MIL << "MediaCurl::MediaCurl(" << url_r << ", " << attach_point_hint_r << ")" << endl;
468
469   globalInitOnce();
470
471   if( !attachPoint().empty())
472   {
473     PathInfo ainfo(attachPoint());
474     Pathname apath(attachPoint() + "XXXXXX");
475     char    *atemp = ::strdup( apath.asString().c_str());
476     char    *atest = NULL;
477     if( !ainfo.isDir() || !ainfo.userMayRWX() ||
478          atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
479     {
480       WAR << "attach point " << ainfo.path()
481           << " is not useable for " << url_r.getScheme() << endl;
482       setAttachPoint("", true);
483     }
484     else if( atest != NULL)
485       ::rmdir(atest);
486
487     if( atemp != NULL)
488       ::free(atemp);
489   }
490 }
491
492 Url MediaCurl::clearQueryString(const Url &url) const
493 {
494   Url curlUrl (url);
495   curlUrl.setUsername( "" );
496   curlUrl.setPassword( "" );
497   curlUrl.setPathParams( "" );
498   curlUrl.setFragment( "" );
499   curlUrl.delQueryParam("cookies");
500   curlUrl.delQueryParam("proxy");
501   curlUrl.delQueryParam("proxyport");
502   curlUrl.delQueryParam("proxyuser");
503   curlUrl.delQueryParam("proxypass");
504   curlUrl.delQueryParam("ssl_capath");
505   curlUrl.delQueryParam("ssl_verify");
506   curlUrl.delQueryParam("ssl_clientcert");
507   curlUrl.delQueryParam("timeout");
508   curlUrl.delQueryParam("auth");
509   curlUrl.delQueryParam("username");
510   curlUrl.delQueryParam("password");
511   curlUrl.delQueryParam("mediahandler");
512   curlUrl.delQueryParam("credentials");
513   curlUrl.delQueryParam("head_requests");
514   return curlUrl;
515 }
516
517 TransferSettings & MediaCurl::settings()
518 {
519     return _settings;
520 }
521
522
523 void MediaCurl::setCookieFile( const Pathname &fileName )
524 {
525   _cookieFile = fileName;
526 }
527
528 ///////////////////////////////////////////////////////////////////
529
530 void MediaCurl::checkProtocol(const Url &url) const
531 {
532   curl_version_info_data *curl_info = NULL;
533   curl_info = curl_version_info(CURLVERSION_NOW);
534   // curl_info does not need any free (is static)
535   if (curl_info->protocols)
536   {
537     const char * const *proto;
538     std::string        scheme( url.getScheme());
539     bool               found = false;
540     for(proto=curl_info->protocols; !found && *proto; ++proto)
541     {
542       if( scheme == std::string((const char *)*proto))
543         found = true;
544     }
545     if( !found)
546     {
547       std::string msg("Unsupported protocol '");
548       msg += scheme;
549       msg += "'";
550       ZYPP_THROW(MediaBadUrlException(_url, msg));
551     }
552   }
553 }
554
555 void MediaCurl::setupEasy()
556 {
557   {
558     char *ptr = getenv("ZYPP_MEDIA_CURL_DEBUG");
559     _curlDebug = (ptr && *ptr) ? str::strtonum<long>( ptr) : 0L;
560     if( _curlDebug > 0)
561     {
562       curl_easy_setopt( _curl, CURLOPT_VERBOSE, 1L);
563       curl_easy_setopt( _curl, CURLOPT_DEBUGFUNCTION, log_curl);
564       curl_easy_setopt( _curl, CURLOPT_DEBUGDATA, &_curlDebug);
565     }
566   }
567
568   curl_easy_setopt(_curl, CURLOPT_HEADERFUNCTION, log_redirects_curl);
569   CURLcode ret = curl_easy_setopt( _curl, CURLOPT_ERRORBUFFER, _curlError );
570   if ( ret != 0 ) {
571     ZYPP_THROW(MediaCurlSetOptException(_url, "Error setting error buffer"));
572   }
573
574   SET_OPTION(CURLOPT_FAILONERROR, 1L);
575   SET_OPTION(CURLOPT_NOSIGNAL, 1L);
576
577   // create non persistant settings
578   // so that we don't add headers twice
579   TransferSettings vol_settings(_settings);
580
581   // add custom headers for download.opensuse.org (bsc#955801)
582   if ( _url.getHost() == "download.opensuse.org" )
583   {
584     vol_settings.addHeader(anonymousIdHeader());
585     vol_settings.addHeader(distributionFlavorHeader());
586   }
587   vol_settings.addHeader("Pragma:");
588
589   _settings.setTimeout(ZConfig::instance().download_transfer_timeout());
590   _settings.setConnectTimeout(CONNECT_TIMEOUT);
591
592   _settings.setUserAgentString(agentString());
593
594   // fill some settings from url query parameters
595   try
596   {
597       fillSettingsFromUrl(_url, _settings);
598   }
599   catch ( const MediaException &e )
600   {
601       disconnectFrom();
602       ZYPP_RETHROW(e);
603   }
604   // if the proxy was not set (or explicitly unset) by url, then look...
605   if ( _settings.proxy().empty() )
606   {
607       // ...at the system proxy settings
608       fillSettingsSystemProxy(_url, _settings);
609   }
610
611  /**
612   * Connect timeout
613   */
614   SET_OPTION(CURLOPT_CONNECTTIMEOUT, _settings.connectTimeout());
615   // If a transfer timeout is set, also set CURLOPT_TIMEOUT to an upper limit
616   // just in case curl does not trigger its progress callback frequently
617   // enough.
618   if ( _settings.timeout() )
619   {
620     SET_OPTION(CURLOPT_TIMEOUT, 3600L);
621   }
622
623   // follow any Location: header that the server sends as part of
624   // an HTTP header (#113275)
625   SET_OPTION(CURLOPT_FOLLOWLOCATION, 1L);
626   // 3 redirects seem to be too few in some cases (bnc #465532)
627   SET_OPTION(CURLOPT_MAXREDIRS, 6L);
628
629   if ( _url.getScheme() == "https" )
630   {
631 #if CURLVERSION_AT_LEAST(7,19,4)
632     // restrict following of redirections from https to https only
633     SET_OPTION( CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTPS );
634 #endif
635
636     if( _settings.verifyPeerEnabled() ||
637         _settings.verifyHostEnabled() )
638     {
639       SET_OPTION(CURLOPT_CAPATH, _settings.certificateAuthoritiesPath().c_str());
640     }
641
642     if( ! _settings.clientCertificatePath().empty() )
643     {
644       SET_OPTION(CURLOPT_SSLCERT, _settings.clientCertificatePath().c_str());
645     }
646     if( ! _settings.clientKeyPath().empty() )
647     {
648       SET_OPTION(CURLOPT_SSLKEY, _settings.clientKeyPath().c_str());
649     }
650
651 #ifdef CURLSSLOPT_ALLOW_BEAST
652     // see bnc#779177
653     ret = curl_easy_setopt( _curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_ALLOW_BEAST );
654     if ( ret != 0 ) {
655       disconnectFrom();
656       ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
657     }
658 #endif
659     SET_OPTION(CURLOPT_SSL_VERIFYPEER, _settings.verifyPeerEnabled() ? 1L : 0L);
660     SET_OPTION(CURLOPT_SSL_VERIFYHOST, _settings.verifyHostEnabled() ? 2L : 0L);
661     // bnc#903405 - POODLE: libzypp should only talk TLS
662     SET_OPTION(CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
663   }
664
665   SET_OPTION(CURLOPT_USERAGENT, _settings.userAgentString().c_str() );
666
667   /*---------------------------------------------------------------*
668    CURLOPT_USERPWD: [user name]:[password]
669
670    Url::username/password -> CURLOPT_USERPWD
671    If not provided, anonymous FTP identification
672    *---------------------------------------------------------------*/
673
674   if ( _settings.userPassword().size() )
675   {
676     SET_OPTION(CURLOPT_USERPWD, _settings.userPassword().c_str());
677     string use_auth = _settings.authType();
678     if (use_auth.empty())
679       use_auth = "digest,basic";        // our default
680     long auth = CurlAuthData::auth_type_str2long(use_auth);
681     if( auth != CURLAUTH_NONE)
682     {
683       DBG << "Enabling HTTP authentication methods: " << use_auth
684           << " (CURLOPT_HTTPAUTH=" << auth << ")" << std::endl;
685       SET_OPTION(CURLOPT_HTTPAUTH, auth);
686     }
687   }
688
689   if ( _settings.proxyEnabled() && ! _settings.proxy().empty() )
690   {
691     DBG << "Proxy: '" << _settings.proxy() << "'" << endl;
692     SET_OPTION(CURLOPT_PROXY, _settings.proxy().c_str());
693     SET_OPTION(CURLOPT_PROXYAUTH, CURLAUTH_BASIC|CURLAUTH_DIGEST|CURLAUTH_NTLM );
694     /*---------------------------------------------------------------*
695      *    CURLOPT_PROXYUSERPWD: [user name]:[password]
696      *
697      * Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
698      *  If not provided, $HOME/.curlrc is evaluated
699      *---------------------------------------------------------------*/
700
701     string proxyuserpwd = _settings.proxyUserPassword();
702
703     if ( proxyuserpwd.empty() )
704     {
705       CurlConfig curlconf;
706       CurlConfig::parseConfig(curlconf); // parse ~/.curlrc
707       if ( curlconf.proxyuserpwd.empty() )
708         DBG << "Proxy: ~/.curlrc does not contain the proxy-user option" << endl;
709       else
710       {
711         proxyuserpwd = curlconf.proxyuserpwd;
712         DBG << "Proxy: using proxy-user from ~/.curlrc" << endl;
713       }
714     }
715     else
716     {
717       DBG << "Proxy: using provided proxy-user '" << _settings.proxyUsername() << "'" << endl;
718     }
719
720     if ( ! proxyuserpwd.empty() )
721     {
722       SET_OPTION(CURLOPT_PROXYUSERPWD, unEscape( proxyuserpwd ).c_str());
723     }
724   }
725 #if CURLVERSION_AT_LEAST(7,19,4)
726   else if ( _settings.proxy() == EXPLICITLY_NO_PROXY )
727   {
728     // Explicitly disabled in URL (see fillSettingsFromUrl()).
729     // This should also prevent libcurl from looking into the environment.
730     DBG << "Proxy: explicitly NOPROXY" << endl;
731     SET_OPTION(CURLOPT_NOPROXY, "*");
732   }
733 #endif
734   else
735   {
736     DBG << "Proxy: not explicitly set" << endl;
737     DBG << "Proxy: libcurl may look into the environment" << endl;
738   }
739
740   /** Speed limits */
741   if ( _settings.minDownloadSpeed() != 0 )
742   {
743       SET_OPTION(CURLOPT_LOW_SPEED_LIMIT, _settings.minDownloadSpeed());
744       // default to 10 seconds at low speed
745       SET_OPTION(CURLOPT_LOW_SPEED_TIME, 60L);
746   }
747
748 #if CURLVERSION_AT_LEAST(7,15,5)
749   if ( _settings.maxDownloadSpeed() != 0 )
750       SET_OPTION_OFFT(CURLOPT_MAX_RECV_SPEED_LARGE, _settings.maxDownloadSpeed());
751 #endif
752
753   /*---------------------------------------------------------------*
754    *---------------------------------------------------------------*/
755
756   _currentCookieFile = _cookieFile.asString();
757   if ( str::strToBool( _url.getQueryParam( "cookies" ), true ) )
758     SET_OPTION(CURLOPT_COOKIEFILE, _currentCookieFile.c_str() );
759   else
760     MIL << "No cookies requested" << endl;
761   SET_OPTION(CURLOPT_COOKIEJAR, _currentCookieFile.c_str() );
762   SET_OPTION(CURLOPT_PROGRESSFUNCTION, &progressCallback );
763   SET_OPTION(CURLOPT_NOPROGRESS, 0L);
764
765 #if CURLVERSION_AT_LEAST(7,18,0)
766   // bnc #306272
767     SET_OPTION(CURLOPT_PROXY_TRANSFER_MODE, 1L );
768 #endif
769   // append settings custom headers to curl
770   for ( TransferSettings::Headers::const_iterator it = vol_settings.headersBegin();
771         it != vol_settings.headersEnd();
772         ++it )
773   {
774     // MIL << "HEADER " << *it << std::endl;
775
776       _customHeaders = curl_slist_append(_customHeaders, it->c_str());
777       if ( !_customHeaders )
778           ZYPP_THROW(MediaCurlInitException(_url));
779   }
780
781   SET_OPTION(CURLOPT_HTTPHEADER, _customHeaders);
782 }
783
784 ///////////////////////////////////////////////////////////////////
785
786
787 void MediaCurl::attachTo (bool next)
788 {
789   if ( next )
790     ZYPP_THROW(MediaNotSupportedException(_url));
791
792   if ( !_url.isValid() )
793     ZYPP_THROW(MediaBadUrlException(_url));
794
795   checkProtocol(_url);
796   if( !isUseableAttachPoint(attachPoint()))
797   {
798     std::string mountpoint = createAttachPoint().asString();
799
800     if( mountpoint.empty())
801       ZYPP_THROW( MediaBadAttachPointException(url()));
802
803     setAttachPoint( mountpoint, true);
804   }
805
806   disconnectFrom(); // clean _curl if needed
807   _curl = curl_easy_init();
808   if ( !_curl ) {
809     ZYPP_THROW(MediaCurlInitException(_url));
810   }
811   try
812     {
813       setupEasy();
814     }
815   catch (Exception & ex)
816     {
817       disconnectFrom();
818       ZYPP_RETHROW(ex);
819     }
820
821   // FIXME: need a derived class to propelly compare url's
822   MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
823   setMediaSource(media);
824 }
825
826 bool
827 MediaCurl::checkAttachPoint(const Pathname &apoint) const
828 {
829   return MediaHandler::checkAttachPoint( apoint, true, true);
830 }
831
832 ///////////////////////////////////////////////////////////////////
833
834 void MediaCurl::disconnectFrom()
835 {
836   if ( _customHeaders )
837   {
838     curl_slist_free_all(_customHeaders);
839     _customHeaders = 0L;
840   }
841
842   if ( _curl )
843   {
844     curl_easy_cleanup( _curl );
845     _curl = NULL;
846   }
847 }
848
849 ///////////////////////////////////////////////////////////////////
850
851 void MediaCurl::releaseFrom( const std::string & ejectDev )
852 {
853   disconnect();
854 }
855
856 Url MediaCurl::getFileUrl( const Pathname & filename_r ) const
857 {
858   // Simply extend the URLs pathname. An 'absolute' URL path
859   // is achieved by encoding the leading '/' in an URL path:
860   //   URL: ftp://user@server           -> ~user
861   //   URL: ftp://user@server/          -> ~user
862   //   URL: ftp://user@server//         -> ~user
863   //   URL: ftp://user@server/%2F       -> /
864   //                         ^- this '/' is just a separator
865   Url newurl( _url );
866   newurl.setPathName( ( Pathname("./"+_url.getPathName()) / filename_r ).asString().substr(1) );
867   return newurl;
868 }
869
870 ///////////////////////////////////////////////////////////////////
871
872 void MediaCurl::getFile( const Pathname & filename ) const
873 {
874     // Use absolute file name to prevent access of files outside of the
875     // hierarchy below the attach point.
876     getFileCopy(filename, localPath(filename).absolutename());
877 }
878
879 ///////////////////////////////////////////////////////////////////
880
881 void MediaCurl::getFileCopy( const Pathname & filename , const Pathname & target) const
882 {
883   callback::SendReport<DownloadProgressReport> report;
884
885   Url fileurl(getFileUrl(filename));
886
887   bool retry = false;
888
889   do
890   {
891     try
892     {
893       doGetFileCopy(filename, target, report);
894       retry = false;
895     }
896     // retry with proper authentication data
897     catch (MediaUnauthorizedException & ex_r)
898     {
899       if(authenticate(ex_r.hint(), !retry))
900         retry = true;
901       else
902       {
903         report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
904         ZYPP_RETHROW(ex_r);
905       }
906     }
907     // unexpected exception
908     catch (MediaException & excpt_r)
909     {
910       // FIXME: error number fix
911       report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
912       ZYPP_RETHROW(excpt_r);
913     }
914   }
915   while (retry);
916
917   report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
918 }
919
920 ///////////////////////////////////////////////////////////////////
921
922 bool MediaCurl::getDoesFileExist( const Pathname & filename ) const
923 {
924   bool retry = false;
925
926   do
927   {
928     try
929     {
930       return doGetDoesFileExist( filename );
931     }
932     // authentication problem, retry with proper authentication data
933     catch (MediaUnauthorizedException & ex_r)
934     {
935       if(authenticate(ex_r.hint(), !retry))
936         retry = true;
937       else
938         ZYPP_RETHROW(ex_r);
939     }
940     // unexpected exception
941     catch (MediaException & excpt_r)
942     {
943       ZYPP_RETHROW(excpt_r);
944     }
945   }
946   while (retry);
947
948   return false;
949 }
950
951 ///////////////////////////////////////////////////////////////////
952
953 void MediaCurl::evaluateCurlCode( const Pathname &filename,
954                                   CURLcode code,
955                                   bool timeout_reached ) const
956 {
957   if ( code != 0 )
958   {
959     Url url;
960     if (filename.empty())
961       url = _url;
962     else
963       url = getFileUrl(filename);
964     std::string err;
965     try
966     {
967       switch ( code )
968       {
969       case CURLE_UNSUPPORTED_PROTOCOL:
970       case CURLE_URL_MALFORMAT:
971       case CURLE_URL_MALFORMAT_USER:
972           err = " Bad URL";
973           break;
974       case CURLE_LOGIN_DENIED:
975           ZYPP_THROW(
976               MediaUnauthorizedException(url, "Login failed.", _curlError, ""));
977           break;
978       case CURLE_HTTP_RETURNED_ERROR:
979       {
980         long httpReturnCode = 0;
981         CURLcode infoRet = curl_easy_getinfo( _curl,
982                                               CURLINFO_RESPONSE_CODE,
983                                               &httpReturnCode );
984         if ( infoRet == CURLE_OK )
985         {
986           string msg = "HTTP response: " + str::numstring( httpReturnCode );
987           switch ( httpReturnCode )
988           {
989           case 401:
990           {
991             string auth_hint = getAuthHint();
992
993             DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
994             DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
995
996             ZYPP_THROW(MediaUnauthorizedException(
997                            url, "Login failed.", _curlError, auth_hint
998                            ));
999           }
1000
1001           case 503: // service temporarily unavailable (bnc #462545)
1002             ZYPP_THROW(MediaTemporaryProblemException(url));
1003           case 504: // gateway timeout
1004             ZYPP_THROW(MediaTimeoutException(url));
1005           case 403:
1006           {
1007             string msg403;
1008             if (url.asString().find("novell.com") != string::npos)
1009               msg403 = _("Visit the Novell Customer Center to check whether your registration is valid and has not expired.");
1010             ZYPP_THROW(MediaForbiddenException(url, msg403));
1011           }
1012           case 404:
1013               ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1014           }
1015
1016           DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1017           ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1018         }
1019         else
1020         {
1021           string msg = "Unable to retrieve HTTP response:";
1022           DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1023           ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1024         }
1025       }
1026       break;
1027       case CURLE_FTP_COULDNT_RETR_FILE:
1028 #if CURLVERSION_AT_LEAST(7,16,0)
1029       case CURLE_REMOTE_FILE_NOT_FOUND:
1030 #endif
1031       case CURLE_FTP_ACCESS_DENIED:
1032       case CURLE_TFTP_NOTFOUND:
1033         err = "File not found";
1034         ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1035         break;
1036       case CURLE_BAD_PASSWORD_ENTERED:
1037       case CURLE_FTP_USER_PASSWORD_INCORRECT:
1038           err = "Login failed";
1039           break;
1040       case CURLE_COULDNT_RESOLVE_PROXY:
1041       case CURLE_COULDNT_RESOLVE_HOST:
1042       case CURLE_COULDNT_CONNECT:
1043       case CURLE_FTP_CANT_GET_HOST:
1044         err = "Connection failed";
1045         break;
1046       case CURLE_WRITE_ERROR:
1047         err = "Write error";
1048         break;
1049       case CURLE_PARTIAL_FILE:
1050       case CURLE_OPERATION_TIMEDOUT:
1051         timeout_reached = true; // fall though to TimeoutException
1052         // fall though...
1053       case CURLE_ABORTED_BY_CALLBACK:
1054          if( timeout_reached )
1055         {
1056           err  = "Timeout reached";
1057           ZYPP_THROW(MediaTimeoutException(url));
1058         }
1059         else
1060         {
1061           err = "User abort";
1062         }
1063         break;
1064       case CURLE_SSL_PEER_CERTIFICATE:
1065       default:
1066         err = "Unrecognized error";
1067         break;
1068       }
1069
1070       // uhm, no 0 code but unknown curl exception
1071       ZYPP_THROW(MediaCurlException(url, err, _curlError));
1072     }
1073     catch (const MediaException & excpt_r)
1074     {
1075       ZYPP_RETHROW(excpt_r);
1076     }
1077   }
1078   else
1079   {
1080     // actually the code is 0, nothing happened
1081   }
1082 }
1083
1084 ///////////////////////////////////////////////////////////////////
1085
1086 bool MediaCurl::doGetDoesFileExist( const Pathname & filename ) const
1087 {
1088   DBG << filename.asString() << endl;
1089
1090   if(!_url.isValid())
1091     ZYPP_THROW(MediaBadUrlException(_url));
1092
1093   if(_url.getHost().empty())
1094     ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1095
1096   Url url(getFileUrl(filename));
1097
1098   DBG << "URL: " << url.asString() << endl;
1099     // Use URL without options and without username and passwd
1100     // (some proxies dislike them in the URL).
1101     // Curl seems to need the just scheme, hostname and a path;
1102     // the rest was already passed as curl options (in attachTo).
1103   Url curlUrl( clearQueryString(url) );
1104
1105   //
1106     // See also Bug #154197 and ftp url definition in RFC 1738:
1107     // The url "ftp://user@host/foo/bar/file" contains a path,
1108     // that is relative to the user's home.
1109     // The url "ftp://user@host//foo/bar/file" (or also with
1110     // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1111     // contains an absolute path.
1112   //
1113   string urlBuffer( curlUrl.asString());
1114   CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1115                                    urlBuffer.c_str() );
1116   if ( ret != 0 ) {
1117     ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1118   }
1119
1120   // instead of returning no data with NOBODY, we return
1121   // little data, that works with broken servers, and
1122   // works for ftp as well, because retrieving only headers
1123   // ftp will return always OK code ?
1124   // See http://curl.haxx.se/docs/knownbugs.html #58
1125   if (  (_url.getScheme() == "http" ||  _url.getScheme() == "https") &&
1126         _settings.headRequestsAllowed() )
1127     ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1L );
1128   else
1129     ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
1130
1131   if ( ret != 0 ) {
1132     curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1133     curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1134     /* yes, this is why we never got to get NOBODY working before,
1135        because setting it changes this option too, and we also
1136        need to reset it
1137        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1138     */
1139     curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1140     ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1141   }
1142
1143   FILE *file = ::fopen( "/dev/null", "w" );
1144   if ( !file ) {
1145       ERR << "fopen failed for /dev/null" << endl;
1146       curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1147       curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1148       /* yes, this is why we never got to get NOBODY working before,
1149        because setting it changes this option too, and we also
1150        need to reset it
1151        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1152       */
1153       curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1154       if ( ret != 0 ) {
1155           ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1156       }
1157       ZYPP_THROW(MediaWriteException("/dev/null"));
1158   }
1159
1160   ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1161   if ( ret != 0 ) {
1162       ::fclose(file);
1163       std::string err( _curlError);
1164       curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
1165       curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1166       /* yes, this is why we never got to get NOBODY working before,
1167        because setting it changes this option too, and we also
1168        need to reset it
1169        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1170       */
1171       curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L );
1172       if ( ret != 0 ) {
1173           ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1174       }
1175       ZYPP_THROW(MediaCurlSetOptException(url, err));
1176   }
1177
1178   CURLcode ok = curl_easy_perform( _curl );
1179   MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
1180
1181   // reset curl settings
1182   if (  _url.getScheme() == "http" ||  _url.getScheme() == "https" )
1183   {
1184     curl_easy_setopt( _curl, CURLOPT_NOBODY, 0L);
1185     if ( ret != 0 ) {
1186       ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1187     }
1188
1189     /* yes, this is why we never got to get NOBODY working before,
1190        because setting it changes this option too, and we also
1191        need to reset it
1192        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
1193     */
1194     curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1L);
1195     if ( ret != 0 ) {
1196       ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1197     }
1198
1199   }
1200   else
1201   {
1202     // for FTP we set different options
1203     curl_easy_setopt( _curl, CURLOPT_RANGE, NULL);
1204     if ( ret != 0 ) {
1205       ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1206     }
1207   }
1208
1209   // if the code is not zero, close the file
1210   if ( ok != 0 )
1211       ::fclose(file);
1212
1213   // as we are not having user interaction, the user can't cancel
1214   // the file existence checking, a callback or timeout return code
1215   // will be always a timeout.
1216   try {
1217       evaluateCurlCode( filename, ok, true /* timeout */);
1218   }
1219   catch ( const MediaFileNotFoundException &e ) {
1220       // if the file did not exist then we can return false
1221       return false;
1222   }
1223   catch ( const MediaException &e ) {
1224       // some error, we are not sure about file existence, rethrw
1225       ZYPP_RETHROW(e);
1226   }
1227   // exists
1228   return ( ok == CURLE_OK );
1229 }
1230
1231 ///////////////////////////////////////////////////////////////////
1232
1233
1234 #if DETECT_DIR_INDEX
1235 bool MediaCurl::detectDirIndex() const
1236 {
1237   if(_url.getScheme() != "http" && _url.getScheme() != "https")
1238     return false;
1239   //
1240   // try to check the effective url and set the not_a_file flag
1241   // if the url path ends with a "/", what usually means, that
1242   // we've received a directory index (index.html content).
1243   //
1244   // Note: This may be dangerous and break file retrieving in
1245   //       case of some server redirections ... ?
1246   //
1247   bool      not_a_file = false;
1248   char     *ptr = NULL;
1249   CURLcode  ret = curl_easy_getinfo( _curl,
1250                                      CURLINFO_EFFECTIVE_URL,
1251                                      &ptr);
1252   if ( ret == CURLE_OK && ptr != NULL)
1253   {
1254     try
1255     {
1256       Url         eurl( ptr);
1257       std::string path( eurl.getPathName());
1258       if( !path.empty() && path != "/" && *path.rbegin() == '/')
1259       {
1260         DBG << "Effective url ("
1261             << eurl
1262             << ") seems to provide the index of a directory"
1263             << endl;
1264         not_a_file = true;
1265       }
1266     }
1267     catch( ... )
1268     {}
1269   }
1270   return not_a_file;
1271 }
1272 #endif
1273
1274 ///////////////////////////////////////////////////////////////////
1275
1276 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1277 {
1278     Pathname dest = target.absolutename();
1279     if( assert_dir( dest.dirname() ) )
1280     {
1281       DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1282       Url url(getFileUrl(filename));
1283       ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1284     }
1285     string destNew = target.asString() + ".new.zypp.XXXXXX";
1286     char *buf = ::strdup( destNew.c_str());
1287     if( !buf)
1288     {
1289       ERR << "out of memory for temp file name" << endl;
1290       Url url(getFileUrl(filename));
1291       ZYPP_THROW(MediaSystemException(url, "out of memory for temp file name"));
1292     }
1293
1294     int tmp_fd = ::mkostemp( buf, O_CLOEXEC );
1295     if( tmp_fd == -1)
1296     {
1297       free( buf);
1298       ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1299       ZYPP_THROW(MediaWriteException(destNew));
1300     }
1301     destNew = buf;
1302     free( buf);
1303
1304     FILE *file = ::fdopen( tmp_fd, "we" );
1305     if ( !file ) {
1306       ::close( tmp_fd);
1307       filesystem::unlink( destNew );
1308       ERR << "fopen failed for file '" << destNew << "'" << endl;
1309       ZYPP_THROW(MediaWriteException(destNew));
1310     }
1311
1312     DBG << "dest: " << dest << endl;
1313     DBG << "temp: " << destNew << endl;
1314
1315     // set IFMODSINCE time condition (no download if not modified)
1316     if( PathInfo(target).isExist() && !(options & OPTION_NO_IFMODSINCE) )
1317     {
1318       curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1319       curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, (long)PathInfo(target).mtime());
1320     }
1321     else
1322     {
1323       curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1324       curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1325     }
1326     try
1327     {
1328       doGetFileCopyFile(filename, dest, file, report, options);
1329     }
1330     catch (Exception &e)
1331     {
1332       ::fclose( file );
1333       filesystem::unlink( destNew );
1334       curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1335       curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1336       ZYPP_RETHROW(e);
1337     }
1338
1339     long httpReturnCode = 0;
1340     CURLcode infoRet = curl_easy_getinfo(_curl,
1341                                          CURLINFO_RESPONSE_CODE,
1342                                          &httpReturnCode);
1343     bool modified = true;
1344     if (infoRet == CURLE_OK)
1345     {
1346       DBG << "HTTP response: " + str::numstring(httpReturnCode);
1347       if ( httpReturnCode == 304
1348            || ( httpReturnCode == 213 && (_url.getScheme() == "ftp" || _url.getScheme() == "tftp") ) ) // not modified
1349       {
1350         DBG << " Not modified.";
1351         modified = false;
1352       }
1353       DBG << endl;
1354     }
1355     else
1356     {
1357       WAR << "Could not get the reponse code." << endl;
1358     }
1359
1360     if (modified || infoRet != CURLE_OK)
1361     {
1362       // apply umask
1363       if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1364       {
1365         ERR << "Failed to chmod file " << destNew << endl;
1366       }
1367       if (::fclose( file ))
1368       {
1369         ERR << "Fclose failed for file '" << destNew << "'" << endl;
1370         ZYPP_THROW(MediaWriteException(destNew));
1371       }
1372       // move the temp file into dest
1373       if ( rename( destNew, dest ) != 0 ) {
1374         ERR << "Rename failed" << endl;
1375         ZYPP_THROW(MediaWriteException(dest));
1376       }
1377     }
1378     else
1379     {
1380       // close and remove the temp file
1381       ::fclose( file );
1382       filesystem::unlink( destNew );
1383     }
1384
1385     DBG << "done: " << PathInfo(dest) << endl;
1386 }
1387
1388 ///////////////////////////////////////////////////////////////////
1389
1390 void MediaCurl::doGetFileCopyFile( const Pathname & filename , const Pathname & dest, FILE *file, callback::SendReport<DownloadProgressReport> & report, RequestOptions options ) const
1391 {
1392     DBG << filename.asString() << endl;
1393
1394     if(!_url.isValid())
1395       ZYPP_THROW(MediaBadUrlException(_url));
1396
1397     if(_url.getHost().empty())
1398       ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1399
1400     Url url(getFileUrl(filename));
1401
1402     DBG << "URL: " << url.asString() << endl;
1403     // Use URL without options and without username and passwd
1404     // (some proxies dislike them in the URL).
1405     // Curl seems to need the just scheme, hostname and a path;
1406     // the rest was already passed as curl options (in attachTo).
1407     Url curlUrl( clearQueryString(url) );
1408
1409     //
1410     // See also Bug #154197 and ftp url definition in RFC 1738:
1411     // The url "ftp://user@host/foo/bar/file" contains a path,
1412     // that is relative to the user's home.
1413     // The url "ftp://user@host//foo/bar/file" (or also with
1414     // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1415     // contains an absolute path.
1416     //
1417     string urlBuffer( curlUrl.asString());
1418     CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1419                                      urlBuffer.c_str() );
1420     if ( ret != 0 ) {
1421       ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1422     }
1423
1424     ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1425     if ( ret != 0 ) {
1426       ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1427     }
1428
1429     // Set callback and perform.
1430     ProgressData progressData(_curl, _settings.timeout(), url, &report);
1431     if (!(options & OPTION_NO_REPORT_START))
1432       report->start(url, dest);
1433     if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1434       WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1435     }
1436
1437     ret = curl_easy_perform( _curl );
1438 #if CURLVERSION_AT_LEAST(7,19,4)
1439     // bnc#692260: If the client sends a request with an If-Modified-Since header
1440     // with a future date for the server, the server may respond 200 sending a
1441     // zero size file.
1442     // curl-7.19.4 introduces CURLINFO_CONDITION_UNMET to check this condition.
1443     if ( ftell(file) == 0 && ret == 0 )
1444     {
1445       long httpReturnCode = 33;
1446       if ( curl_easy_getinfo( _curl, CURLINFO_RESPONSE_CODE, &httpReturnCode ) == CURLE_OK && httpReturnCode == 200 )
1447       {
1448         long conditionUnmet = 33;
1449         if ( curl_easy_getinfo( _curl, CURLINFO_CONDITION_UNMET, &conditionUnmet ) == CURLE_OK && conditionUnmet )
1450         {
1451           WAR << "TIMECONDITION unmet - retry without." << endl;
1452           curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_NONE);
1453           curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, 0L);
1454           ret = curl_easy_perform( _curl );
1455         }
1456       }
1457     }
1458 #endif
1459
1460     if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1461       WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1462     }
1463
1464     if ( ret != 0 )
1465     {
1466       ERR << "curl error: " << ret << ": " << _curlError
1467           << ", temp file size " << ftell(file)
1468           << " bytes." << endl;
1469
1470       // the timeout is determined by the progress data object
1471       // which holds whether the timeout was reached or not,
1472       // otherwise it would be a user cancel
1473       try {
1474         evaluateCurlCode( filename, ret, progressData.reached);
1475       }
1476       catch ( const MediaException &e ) {
1477         // some error, we are not sure about file existence, rethrw
1478         ZYPP_RETHROW(e);
1479       }
1480     }
1481
1482 #if DETECT_DIR_INDEX
1483     if (!ret && detectDirIndex())
1484       {
1485         ZYPP_THROW(MediaNotAFileException(_url, filename));
1486       }
1487 #endif // DETECT_DIR_INDEX
1488 }
1489
1490 ///////////////////////////////////////////////////////////////////
1491
1492 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1493 {
1494   filesystem::DirContent content;
1495   getDirInfo( content, dirname, /*dots*/false );
1496
1497   for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1498       Pathname filename = dirname + it->name;
1499       int res = 0;
1500
1501       switch ( it->type ) {
1502       case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1503       case filesystem::FT_FILE:
1504         getFile( filename );
1505         break;
1506       case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1507         if ( recurse_r ) {
1508           getDir( filename, recurse_r );
1509         } else {
1510           res = assert_dir( localPath( filename ) );
1511           if ( res ) {
1512             WAR << "Ignore error (" << res <<  ") on creating local directory '" << localPath( filename ) << "'" << endl;
1513           }
1514         }
1515         break;
1516       default:
1517         // don't provide devices, sockets, etc.
1518         break;
1519       }
1520   }
1521 }
1522
1523 ///////////////////////////////////////////////////////////////////
1524
1525 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1526                                const Pathname & dirname, bool dots ) const
1527 {
1528   getDirectoryYast( retlist, dirname, dots );
1529 }
1530
1531 ///////////////////////////////////////////////////////////////////
1532
1533 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1534                             const Pathname & dirname, bool dots ) const
1535 {
1536   getDirectoryYast( retlist, dirname, dots );
1537 }
1538
1539 ///////////////////////////////////////////////////////////////////
1540
1541 int MediaCurl::progressCallback( void *clientp,
1542                                  double dltotal, double dlnow,
1543                                  double ultotal, double ulnow)
1544 {
1545   ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1546   if( pdata)
1547   {
1548     // work around curl bug that gives us old data
1549     long httpReturnCode = 0;
1550     if (curl_easy_getinfo(pdata->curl, CURLINFO_RESPONSE_CODE, &httpReturnCode) != CURLE_OK || httpReturnCode == 0)
1551       return 0;
1552
1553     time_t now   = time(NULL);
1554     if( now > 0)
1555     {
1556         // reset time of last change in case initial time()
1557         // failed or the time was adjusted (goes backward)
1558         if( pdata->ltime <= 0 || pdata->ltime > now)
1559         {
1560           pdata->ltime = now;
1561         }
1562
1563         // start time counting as soon as first data arrives
1564         // (skip the connection / redirection time at begin)
1565         time_t dif = 0;
1566         if (dlnow > 0 || ulnow > 0)
1567         {
1568           dif = (now - pdata->ltime);
1569           dif = dif > 0 ? dif : 0;
1570
1571           pdata->secs += dif;
1572         }
1573
1574         // update the drate_avg and drate_period only after a second has passed
1575         // (this callback is called much more often than a second)
1576         // otherwise the values would be far from accurate when measuring
1577         // the time in seconds
1578         //! \todo more accurate download rate computationn, e.g. compute average value from last 5 seconds, or work with milliseconds instead of seconds
1579
1580         if ( pdata->secs > 1 && (dif > 0 || dlnow == dltotal ))
1581           pdata->drate_avg = (dlnow / pdata->secs);
1582
1583         if ( dif > 0 )
1584         {
1585           pdata->drate_period = ((dlnow - pdata->dload_period) / dif);
1586           pdata->dload_period = dlnow;
1587         }
1588     }
1589
1590     // send progress report first, abort transfer if requested
1591     if( pdata->report)
1592     {
1593       if (!(*(pdata->report))->progress(int( dltotal ? dlnow * 100 / dltotal : 0 ),
1594                                         pdata->url,
1595                                         pdata->drate_avg,
1596                                         pdata->drate_period))
1597       {
1598         return 1; // abort transfer
1599       }
1600     }
1601
1602     // check if we there is a timeout set
1603     if( pdata->timeout > 0)
1604     {
1605       if( now > 0)
1606       {
1607         bool progress = false;
1608
1609         // update download data if changed, mark progress
1610         if( dlnow != pdata->dload)
1611         {
1612           progress     = true;
1613           pdata->dload = dlnow;
1614           pdata->ltime = now;
1615         }
1616         // update upload data if changed, mark progress
1617         if( ulnow != pdata->uload)
1618         {
1619           progress     = true;
1620           pdata->uload = ulnow;
1621           pdata->ltime = now;
1622         }
1623
1624         if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1625         {
1626           pdata->reached = true;
1627           return 1; // aborts transfer
1628         }
1629       }
1630     }
1631   }
1632   return 0;
1633 }
1634
1635 CURL *MediaCurl::progressCallback_getcurl( void *clientp )
1636 {
1637   ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1638   return pdata ? pdata->curl : 0;
1639 }
1640
1641 ///////////////////////////////////////////////////////////////////
1642
1643 string MediaCurl::getAuthHint() const
1644 {
1645   long auth_info = CURLAUTH_NONE;
1646
1647   CURLcode infoRet =
1648     curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1649
1650   if(infoRet == CURLE_OK)
1651   {
1652     return CurlAuthData::auth_type_long2str(auth_info);
1653   }
1654
1655   return "";
1656 }
1657
1658 ///////////////////////////////////////////////////////////////////
1659
1660 bool MediaCurl::authenticate(const string & availAuthTypes, bool firstTry) const
1661 {
1662   //! \todo need a way to pass different CredManagerOptions here
1663   Target_Ptr target = zypp::getZYpp()->getTarget();
1664   CredentialManager cm(CredManagerOptions(target ? target->root() : ""));
1665   CurlAuthData_Ptr credentials;
1666
1667   // get stored credentials
1668   AuthData_Ptr cmcred = cm.getCred(_url);
1669
1670   if (cmcred && firstTry)
1671   {
1672     credentials.reset(new CurlAuthData(*cmcred));
1673     DBG << "got stored credentials:" << endl << *credentials << endl;
1674   }
1675   // if not found, ask user
1676   else
1677   {
1678
1679     CurlAuthData_Ptr curlcred;
1680     curlcred.reset(new CurlAuthData());
1681     callback::SendReport<AuthenticationReport> auth_report;
1682
1683     // preset the username if present in current url
1684     if (!_url.getUsername().empty() && firstTry)
1685       curlcred->setUsername(_url.getUsername());
1686     // if CM has found some credentials, preset the username from there
1687     else if (cmcred)
1688       curlcred->setUsername(cmcred->username());
1689
1690     // indicate we have no good credentials from CM
1691     cmcred.reset();
1692
1693     string prompt_msg = boost::str(boost::format(
1694       //!\todo add comma to the message for the next release
1695       _("Authentication required for '%s'")) % _url.asString());
1696
1697     // set available authentication types from the exception
1698     // might be needed in prompt
1699     curlcred->setAuthType(availAuthTypes);
1700
1701     // ask user
1702     if (auth_report->prompt(_url, prompt_msg, *curlcred))
1703     {
1704       DBG << "callback answer: retry" << endl
1705           << "CurlAuthData: " << *curlcred << endl;
1706
1707       if (curlcred->valid())
1708       {
1709         credentials = curlcred;
1710           // if (credentials->username() != _url.getUsername())
1711           //   _url.setUsername(credentials->username());
1712           /**
1713            *  \todo find a way to save the url with changed username
1714            *  back to repoinfo or dont store urls with username
1715            *  (and either forbid more repos with the same url and different
1716            *  user, or return a set of credentials from CM and try them one
1717            *  by one)
1718            */
1719       }
1720     }
1721     else
1722     {
1723       DBG << "callback answer: cancel" << endl;
1724     }
1725   }
1726
1727   // set username and password
1728   if (credentials)
1729   {
1730     // HACK, why is this const?
1731     const_cast<MediaCurl*>(this)->_settings.setUsername(credentials->username());
1732     const_cast<MediaCurl*>(this)->_settings.setPassword(credentials->password());
1733
1734     // set username and password
1735     CURLcode ret = curl_easy_setopt(_curl, CURLOPT_USERPWD, _settings.userPassword().c_str());
1736     if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1737
1738     // set available authentication types from the exception
1739     if (credentials->authType() == CURLAUTH_NONE)
1740       credentials->setAuthType(availAuthTypes);
1741
1742     // set auth type (seems this must be set _after_ setting the userpwd)
1743     if (credentials->authType() != CURLAUTH_NONE)
1744     {
1745       // FIXME: only overwrite if not empty?
1746       const_cast<MediaCurl*>(this)->_settings.setAuthType(credentials->authTypeAsString());
1747       ret = curl_easy_setopt(_curl, CURLOPT_HTTPAUTH, credentials->authType());
1748       if ( ret != 0 ) ZYPP_THROW(MediaCurlSetOptException(_url, _curlError));
1749     }
1750
1751     if (!cmcred)
1752     {
1753       credentials->setUrl(_url);
1754       cm.addCred(*credentials);
1755       cm.save();
1756     }
1757
1758     return true;
1759   }
1760
1761   return false;
1762 }
1763
1764
1765   } // namespace media
1766 } // namespace zypp
1767 //