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