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