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