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