- Use CURLOPT_NOBODY instead of a CURLOPT_RANGE of 1 byte
[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   // instead of returning no data with NOBODY, we return
872   // little data, that works with broken servers, and
873   // works for ftp as well, because retrieving only headers
874   // ftp will return always OK code ?
875   if (  _url.getScheme() == "http" ||  _url.getScheme() == "https" )
876     ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, 1 );
877   else
878     ret = curl_easy_setopt( _curl, CURLOPT_RANGE, "0-1" );
879
880   if ( ret != 0 ) {
881     curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
882     curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
883     /* yes, this is why we never got to get NOBODY working before,
884        because setting it changes this option too, and we also
885        need to reset it
886        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
887     */
888     curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
889     ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
890   }
891
892
893   FILE *file = ::fopen( "/dev/null", "w" );
894   if ( !file ) {
895       ::fclose(file);
896       ERR << "fopen failed for /dev/null" << endl;
897       curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
898       curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
899       /* yes, this is why we never got to get NOBODY working before,
900        because setting it changes this option too, and we also
901        need to reset it
902        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
903       */
904       curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
905       if ( ret != 0 ) {
906           ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
907       }
908       ZYPP_THROW(MediaWriteException("/dev/null"));
909   }
910
911   ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
912   if ( ret != 0 ) {
913       ::fclose(file);
914       std::string err( _curlError);
915       curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
916       curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
917       /* yes, this is why we never got to get NOBODY working before,
918        because setting it changes this option too, and we also
919        need to reset it
920        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
921       */
922       curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
923       if ( ret != 0 ) {
924           ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
925       }
926       ZYPP_THROW(MediaCurlSetOptException(url, err));
927   }
928     // Set callback and perform.
929   //ProgressData progressData(_xfer_timeout, url, &report);
930   //report->start(url, dest);
931   //if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
932   //  WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
933   //}
934
935   CURLcode ok = curl_easy_perform( _curl );
936   MIL << "perform code: " << ok << " [ " << curl_easy_strerror(ok) << " ]" << endl;
937
938   // reset curl settings
939   if (  _url.getScheme() == "http" ||  _url.getScheme() == "https" )
940   {
941     ret = curl_easy_setopt( _curl, CURLOPT_NOBODY, NULL );
942     /* yes, this is why we never got to get NOBODY working before,
943        because setting it changes this option too, and we also
944        need to reset it
945        See: http://curl.haxx.se/mail/archive-2005-07/0073.html
946     */
947     ret = curl_easy_setopt( _curl, CURLOPT_HTTPGET, 1 );
948   }
949   else
950     ret = curl_easy_setopt( _curl, CURLOPT_RANGE, NULL );
951
952   if ( ret != 0 )
953   {
954     ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
955   }
956
957   if ( ok != 0 )
958   {
959     ::fclose( file );
960
961     std::string err;
962     try
963     {
964       bool err_file_not_found = false;
965       switch ( ok )
966       {
967       case CURLE_FTP_COULDNT_RETR_FILE:
968       case CURLE_FTP_ACCESS_DENIED:
969         err_file_not_found = true;
970         break;
971       case CURLE_HTTP_RETURNED_ERROR:
972         {
973           long httpReturnCode = 0;
974           CURLcode infoRet = curl_easy_getinfo( _curl,
975                                                 CURLINFO_RESPONSE_CODE,
976                                                 &httpReturnCode );
977           if ( infoRet == CURLE_OK )
978           {
979             string msg = "HTTP response: " +
980                           str::numstring( httpReturnCode );
981             if ( httpReturnCode == 401 )
982             {
983               std::string auth_hint = getAuthHint();
984
985               DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
986               DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
987
988               ZYPP_THROW(MediaUnauthorizedException(
989                 url, "Login failed.", _curlError, auth_hint
990               ));
991             }
992             else
993             if ( httpReturnCode == 404)
994             {
995                err_file_not_found = true;
996                break;
997             }
998
999             msg += err;
1000             DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1001             ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1002           }
1003           else
1004           {
1005             string msg = "Unable to retrieve HTTP response:";
1006             msg += err;
1007             DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1008             ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1009           }
1010         }
1011         break;
1012       case CURLE_UNSUPPORTED_PROTOCOL:
1013       case CURLE_URL_MALFORMAT:
1014       case CURLE_URL_MALFORMAT_USER:
1015       case CURLE_BAD_PASSWORD_ENTERED:
1016       case CURLE_FTP_USER_PASSWORD_INCORRECT:
1017       case CURLE_COULDNT_RESOLVE_PROXY:
1018       case CURLE_COULDNT_RESOLVE_HOST:
1019       case CURLE_COULDNT_CONNECT:
1020       case CURLE_FTP_CANT_GET_HOST:
1021       case CURLE_WRITE_ERROR:
1022       case CURLE_ABORTED_BY_CALLBACK:
1023       case CURLE_SSL_PEER_CERTIFICATE:
1024       default:
1025         err = curl_easy_strerror(ok);
1026         if (err.empty())
1027           err = "Unrecognized error";
1028         break;
1029       }
1030
1031       if( err_file_not_found)
1032       {
1033         // file does not exists
1034         return false;
1035       }
1036       else
1037       {
1038         // there was an error
1039         ZYPP_THROW(MediaCurlException(url, string(), _curlError));
1040       }
1041     }
1042     catch (const MediaException & excpt_r)
1043     {
1044       ZYPP_RETHROW(excpt_r);
1045     }
1046   }
1047
1048   // exists
1049   return ( ok == CURLE_OK );
1050   //if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1051   //  WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1052   //}
1053 }
1054
1055 void MediaCurl::doGetFileCopy( const Pathname & filename , const Pathname & target, callback::SendReport<DownloadProgressReport> & report) const
1056 {
1057     DBG << filename.asString() << endl;
1058
1059     if(!_url.isValid())
1060       ZYPP_THROW(MediaBadUrlException(_url));
1061
1062     if(_url.getHost().empty())
1063       ZYPP_THROW(MediaBadUrlEmptyHostException(_url));
1064
1065     string path = _url.getPathName();
1066     if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
1067          filename.absolute() ) {
1068       // If url has a path with trailing slash, remove the leading slash from
1069       // the absolute file name
1070       path += filename.asString().substr( 1, filename.asString().size() - 1 );
1071     } else if ( filename.relative() ) {
1072       // Add trailing slash to path, if not already there
1073       if (path.empty()) path = "/";
1074       else if (*path.rbegin() != '/' ) path += "/";
1075       // Remove "./" from begin of relative file name
1076       path += filename.asString().substr( 2, filename.asString().size() - 2 );
1077     } else {
1078       path += filename.asString();
1079     }
1080
1081     Url url( _url );
1082     url.setPathName( path );
1083
1084     Pathname dest = target.absolutename();
1085     if( assert_dir( dest.dirname() ) )
1086     {
1087       DBG << "assert_dir " << dest.dirname() << " failed" << endl;
1088       ZYPP_THROW( MediaSystemException(url, "System error on " + dest.dirname().asString()) );
1089     }
1090
1091     DBG << "URL: " << url.asString() << endl;
1092     // Use URL without options and without username and passwd
1093     // (some proxies dislike them in the URL).
1094     // Curl seems to need the just scheme, hostname and a path;
1095     // the rest was already passed as curl options (in attachTo).
1096     Url curlUrl( url );
1097
1098     // Use asString + url::ViewOptions instead?
1099     curlUrl.setUsername( "" );
1100     curlUrl.setPassword( "" );
1101     curlUrl.setPathParams( "" );
1102     curlUrl.setQueryString( "" );
1103     curlUrl.setFragment( "" );
1104
1105     //
1106     // See also Bug #154197 and ftp url definition in RFC 1738:
1107     // The url "ftp://user@host/foo/bar/file" contains a path,
1108     // that is relative to the user's home.
1109     // The url "ftp://user@host//foo/bar/file" (or also with
1110     // encoded slash as %2f) "ftp://user@host/%2ffoo/bar/file"
1111     // contains an absolute path.
1112     //
1113     string urlBuffer( curlUrl.asString());
1114     CURLcode ret = curl_easy_setopt( _curl, CURLOPT_URL,
1115                                      urlBuffer.c_str() );
1116     if ( ret != 0 ) {
1117       ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1118     }
1119
1120     // set IFMODSINCE time condition (no download if not modified)
1121     curl_easy_setopt(_curl, CURLOPT_TIMECONDITION, CURL_TIMECOND_IFMODSINCE);
1122     curl_easy_setopt(_curl, CURLOPT_TIMEVALUE, PathInfo(target).mtime());
1123
1124     string destNew = target.asString() + ".new.zypp.XXXXXX";
1125     char *buf = ::strdup( destNew.c_str());
1126     if( !buf)
1127     {
1128       ERR << "out of memory for temp file name" << endl;
1129       ZYPP_THROW(MediaSystemException(
1130         url, "out of memory for temp file name"
1131       ));
1132     }
1133
1134     int tmp_fd = ::mkstemp( buf );
1135     if( tmp_fd == -1)
1136     {
1137       free( buf);
1138       ERR << "mkstemp failed for file '" << destNew << "'" << endl;
1139       ZYPP_THROW(MediaWriteException(destNew));
1140     }
1141     destNew = buf;
1142     free( buf);
1143
1144     FILE *file = ::fdopen( tmp_fd, "w" );
1145     if ( !file ) {
1146       ::close( tmp_fd);
1147       filesystem::unlink( destNew );
1148       ERR << "fopen failed for file '" << destNew << "'" << endl;
1149       ZYPP_THROW(MediaWriteException(destNew));
1150     }
1151
1152     DBG << "dest: " << dest << endl;
1153     DBG << "temp: " << destNew << endl;
1154
1155     ret = curl_easy_setopt( _curl, CURLOPT_WRITEDATA, file );
1156     if ( ret != 0 ) {
1157       ::fclose( file );
1158       filesystem::unlink( destNew );
1159       ZYPP_THROW(MediaCurlSetOptException(url, _curlError));
1160     }
1161
1162     // Set callback and perform.
1163     ProgressData progressData(_xfer_timeout, url, &report);
1164     report->start(url, dest);
1165     if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, &progressData ) != 0 ) {
1166       WAR << "Can't set CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1167     }
1168
1169     ret = curl_easy_perform( _curl );
1170
1171     if ( curl_easy_setopt( _curl, CURLOPT_PROGRESSDATA, NULL ) != 0 ) {
1172       WAR << "Can't unset CURLOPT_PROGRESSDATA: " << _curlError << endl;;
1173     }
1174
1175     if ( ret != 0 ) {
1176       ERR << "curl error: " << ret << ": " << _curlError
1177           << ", temp file size " << PathInfo(destNew).size()
1178           << " byte." << endl;
1179
1180       ::fclose( file );
1181       filesystem::unlink( destNew );
1182
1183       std::string err;
1184       try {
1185        bool err_file_not_found = false;
1186        switch ( ret ) {
1187         case CURLE_UNSUPPORTED_PROTOCOL:
1188         case CURLE_URL_MALFORMAT:
1189         case CURLE_URL_MALFORMAT_USER:
1190           err = " Bad URL";
1191         case CURLE_HTTP_RETURNED_ERROR:
1192           {
1193             long httpReturnCode = 0;
1194             CURLcode infoRet = curl_easy_getinfo( _curl,
1195                                                   CURLINFO_RESPONSE_CODE,
1196                                                   &httpReturnCode );
1197             if ( infoRet == CURLE_OK ) {
1198               string msg = "HTTP response: " +
1199                            str::numstring( httpReturnCode );
1200               if ( httpReturnCode == 401 )
1201               {
1202                 std::string auth_hint = getAuthHint();
1203
1204                 DBG << msg << " Login failed (URL: " << url.asString() << ")" << std::endl;
1205                 DBG << "MediaUnauthorizedException auth hint: '" << auth_hint << "'" << std::endl;
1206
1207                 ZYPP_THROW(MediaUnauthorizedException(
1208                   url, "Login failed.", _curlError, auth_hint
1209                 ));
1210               }
1211               else
1212               if ( httpReturnCode == 404)
1213               {
1214                  ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1215               }
1216
1217               msg += err;
1218               DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1219               ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1220             }
1221             else
1222             {
1223               string msg = "Unable to retrieve HTTP response:";
1224               msg += err;
1225               DBG << msg << " (URL: " << url.asString() << ")" << std::endl;
1226               ZYPP_THROW(MediaCurlException(url, msg, _curlError));
1227             }
1228           }
1229           break;
1230         case CURLE_FTP_COULDNT_RETR_FILE:
1231         case CURLE_FTP_ACCESS_DENIED:
1232           err = "File not found";
1233           err_file_not_found = true;
1234           break;
1235         case CURLE_BAD_PASSWORD_ENTERED:
1236         case CURLE_FTP_USER_PASSWORD_INCORRECT:
1237           err = "Login failed";
1238           break;
1239         case CURLE_COULDNT_RESOLVE_PROXY:
1240         case CURLE_COULDNT_RESOLVE_HOST:
1241         case CURLE_COULDNT_CONNECT:
1242         case CURLE_FTP_CANT_GET_HOST:
1243           err = "Connection failed";
1244           break;
1245         case CURLE_WRITE_ERROR:
1246           err = "Write error";
1247           break;
1248         case CURLE_ABORTED_BY_CALLBACK:
1249           if( progressData.reached)
1250           {
1251             err  = "Timeout reached";
1252           }
1253           else
1254           {
1255             err = "User abort";
1256           }
1257           break;
1258         case CURLE_SSL_PEER_CERTIFICATE:
1259         default:
1260           err = "Unrecognized error";
1261           break;
1262        }
1263        if( err_file_not_found)
1264        {
1265          ZYPP_THROW(MediaFileNotFoundException(_url, filename));
1266        }
1267        else
1268        {
1269          ZYPP_THROW(MediaCurlException(url, err, _curlError));
1270        }
1271       }
1272       catch (const MediaException & excpt_r)
1273       {
1274         ZYPP_RETHROW(excpt_r);
1275       }
1276     }
1277 #if DETECT_DIR_INDEX
1278     else
1279     if(curlUrl.getScheme() == "http" ||
1280        curlUrl.getScheme() == "https")
1281     {
1282       //
1283       // try to check the effective url and set the not_a_file flag
1284       // if the url path ends with a "/", what usually means, that
1285       // we've received a directory index (index.html content).
1286       //
1287       // Note: This may be dangerous and break file retrieving in
1288       //       case of some server redirections ... ?
1289       //
1290       bool      not_a_file = false;
1291       char     *ptr = NULL;
1292       CURLcode  ret = curl_easy_getinfo( _curl,
1293                                          CURLINFO_EFFECTIVE_URL,
1294                                          &ptr);
1295       if ( ret == CURLE_OK && ptr != NULL)
1296       {
1297         try
1298         {
1299           Url         eurl( ptr);
1300           std::string path( eurl.getPathName());
1301           if( !path.empty() && path != "/" && *path.rbegin() == '/')
1302           {
1303             DBG << "Effective url ("
1304                 << eurl
1305                 << ") seems to provide the index of a directory"
1306                 << endl;
1307             not_a_file = true;
1308           }
1309         }
1310         catch( ... )
1311         {}
1312       }
1313
1314       if( not_a_file)
1315       {
1316         ::fclose( file );
1317         filesystem::unlink( destNew );
1318         ZYPP_THROW(MediaNotAFileException(_url, filename));
1319       }
1320     }
1321 #endif // DETECT_DIR_INDEX
1322
1323     long httpReturnCode = 0;
1324     CURLcode infoRet = curl_easy_getinfo(_curl,
1325                                          CURLINFO_RESPONSE_CODE,
1326                                          &httpReturnCode);
1327     bool modified = true;
1328     if (infoRet == CURLE_OK)
1329     {
1330       DBG << "HTTP response: " + str::numstring(httpReturnCode);
1331       if ( httpReturnCode == 304 ) // not modified
1332       {
1333         DBG << " Not modified.";
1334         modified = false;
1335       }
1336       DBG << endl;
1337     }
1338     else
1339     {
1340       WAR << "Could not get the reponse code." << endl;
1341     }
1342
1343     if (modified || infoRet != CURLE_OK)
1344     {
1345       // apply umask
1346       if ( ::fchmod( ::fileno(file), filesystem::applyUmaskTo( 0644 ) ) )
1347       {
1348         ERR << "Failed to chmod file " << destNew << endl;
1349       }
1350       ::fclose( file );
1351
1352       // move the temp file into dest
1353       if ( rename( destNew, dest ) != 0 ) {
1354         ERR << "Rename failed" << endl;
1355         ZYPP_THROW(MediaWriteException(dest));
1356       }
1357     }
1358     else
1359     {
1360       // close and remove the temp file
1361       ::fclose( file );
1362       filesystem::unlink( destNew );
1363     }
1364
1365     DBG << "done: " << PathInfo(dest) << endl;
1366 }
1367
1368
1369 ///////////////////////////////////////////////////////////////////
1370 //
1371 //
1372 //        METHOD NAME : MediaCurl::getDir
1373 //        METHOD TYPE : PMError
1374 //
1375 //        DESCRIPTION : Asserted that media is attached
1376 //
1377 void MediaCurl::getDir( const Pathname & dirname, bool recurse_r ) const
1378 {
1379   filesystem::DirContent content;
1380   getDirInfo( content, dirname, /*dots*/false );
1381
1382   for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
1383       Pathname filename = dirname + it->name;
1384       int res = 0;
1385
1386       switch ( it->type ) {
1387       case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
1388       case filesystem::FT_FILE:
1389         getFile( filename );
1390         break;
1391       case filesystem::FT_DIR: // newer directory.yast contain at least directory info
1392         if ( recurse_r ) {
1393           getDir( filename, recurse_r );
1394         } else {
1395           res = assert_dir( localPath( filename ) );
1396           if ( res ) {
1397             WAR << "Ignore error (" << res <<  ") on creating local directory '" << localPath( filename ) << "'" << endl;
1398           }
1399         }
1400         break;
1401       default:
1402         // don't provide devices, sockets, etc.
1403         break;
1404       }
1405   }
1406 }
1407
1408 ///////////////////////////////////////////////////////////////////
1409 //
1410 //
1411 //        METHOD NAME : MediaCurl::getDirInfo
1412 //        METHOD TYPE : PMError
1413 //
1414 //        DESCRIPTION : Asserted that media is attached and retlist is empty.
1415 //
1416 void MediaCurl::getDirInfo( std::list<std::string> & retlist,
1417                                const Pathname & dirname, bool dots ) const
1418 {
1419   getDirectoryYast( retlist, dirname, dots );
1420 }
1421
1422 ///////////////////////////////////////////////////////////////////
1423 //
1424 //
1425 //        METHOD NAME : MediaCurl::getDirInfo
1426 //        METHOD TYPE : PMError
1427 //
1428 //        DESCRIPTION : Asserted that media is attached and retlist is empty.
1429 //
1430 void MediaCurl::getDirInfo( filesystem::DirContent & retlist,
1431                             const Pathname & dirname, bool dots ) const
1432 {
1433   getDirectoryYast( retlist, dirname, dots );
1434 }
1435
1436 ///////////////////////////////////////////////////////////////////
1437 //
1438 //
1439 //        METHOD NAME : MediaCurl::progressCallback
1440 //        METHOD TYPE : int
1441 //
1442 //        DESCRIPTION : Progress callback triggered from MediaCurl::getFile
1443 //
1444 int MediaCurl::progressCallback( void *clientp, double dltotal, double dlnow,
1445                                  double ultotal, double ulnow )
1446 {
1447   ProgressData *pdata = reinterpret_cast<ProgressData *>(clientp);
1448   if( pdata)
1449   {
1450     // send progress report first, abort transfer if requested
1451     if( pdata->report)
1452     {
1453       if (! (*(pdata->report))->progress(int( dlnow * 100 / dltotal ), pdata->url))
1454       {
1455         return 1; // abort transfer
1456       }
1457     }
1458
1459     // check if we there is a timeout set
1460     if( pdata->timeout > 0)
1461     {
1462       time_t now = time(NULL);
1463       if( now > 0)
1464       {
1465         bool progress = false;
1466
1467         // reset time of last change in case initial time()
1468         // failed or the time was adjusted (goes backward)
1469         if( pdata->ltime <= 0 || pdata->ltime > now)
1470           pdata->ltime = now;
1471
1472         // update download data if changed, mark progress
1473         if( dlnow != pdata->dload)
1474         {
1475           progress     = true;
1476           pdata->dload = dlnow;
1477           pdata->ltime = now;
1478         }
1479         // update upload data if changed, mark progress
1480         if( ulnow != pdata->uload)
1481         {
1482           progress     = true;
1483           pdata->uload = ulnow;
1484           pdata->ltime = now;
1485         }
1486
1487         if( !progress && (now >= (pdata->ltime + pdata->timeout)))
1488         {
1489           pdata->reached = true;
1490           return 1; // aborts transfer
1491         }
1492       }
1493     }
1494   }
1495   return 0;
1496 }
1497
1498 string MediaCurl::getAuthHint() const
1499 {
1500   long auth_info = CURLAUTH_NONE;
1501
1502   CURLcode infoRet =
1503     curl_easy_getinfo(_curl, CURLINFO_HTTPAUTH_AVAIL, &auth_info);
1504
1505   if(infoRet == CURLE_OK)
1506   {
1507     return CurlAuthData::auth_type_long2str(auth_info);
1508   }
1509
1510   return "";
1511 }
1512
1513   } // namespace media
1514 } // namespace zypp
1515 //