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