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