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