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