- add Target::baseProduct for convenence. disable flavor header for now
[platform/upstream/libzypp.git] / zypp / media / MediaAria2c.cc
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/media/MediaAria2c.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/ProgressData.h"
19 #include "zypp/base/String.h"
20 #include "zypp/base/Gettext.h"
21 #include "zypp/base/Sysconfig.h"
22 #include "zypp/base/Gettext.h"
23 #include "zypp/ZYppCallbacks.h"
24
25 #include "zypp/Target.h"
26 #include "zypp/ZYppFactory.h"
27
28 #include "zypp/media/MediaAria2c.h"
29 #include "zypp/media/proxyinfo/ProxyInfos.h"
30 #include "zypp/media/ProxyInfo.h"
31 #include "zypp/media/MediaUserAuth.h"
32 #include "zypp/thread/Once.h"
33 #include <cstdlib>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <sys/mount.h>
37 #include <errno.h>
38 #include <dirent.h>
39 #include <unistd.h>
40 #include <boost/format.hpp>
41
42 #define  DETECT_DIR_INDEX       0
43 #define  CONNECT_TIMEOUT        60
44 #define  TRANSFER_TIMEOUT       60 * 3
45 #define  TRANSFER_TIMEOUT_MAX   60 * 60
46
47
48 using namespace std;
49 using namespace zypp::base;
50
51 namespace zypp 
52 {
53 namespace media 
54 {
55
56 Pathname MediaAria2c::_cookieFile = "/var/lib/YaST2/cookies";
57 Pathname MediaAria2c::_aria2cPath = "/usr/local/bin/aria2c";
58 std::string MediaAria2c::_aria2cVersion = "WE DON'T KNOW ARIA2C VERSION";
59
60 //check if aria2c is present in the system
61 bool
62 MediaAria2c::existsAria2cmd()
63 {
64     const char* argv[] =
65     {
66       "whereis",
67       "-b",
68       "aria2c",
69       NULL
70     };
71
72     ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
73            
74     std::string ariaResponse( aria.receiveLine());
75     string::size_type pos = ariaResponse.find('/', 0 );
76     if( pos != string::npos )
77         return true;
78     else
79         return false;
80 }
81
82 static const char *const anonymousIdHeader()
83 {
84   // we need to add the release and identifier to the
85   // agent string.
86   // The target could be not initialized, and then this information
87   // is not available.
88   Target_Ptr target;
89   // FIXME this has to go away as soon as the target
90   // does not throw when not initialized.
91   try {
92       target = zypp::getZYpp()->target();
93   }
94   catch ( const Exception &e )
95   {
96       // nothing to do
97   }
98
99   static const std::string _value(
100       str::form(
101           "X-Zypp-AnonymousId: %s",
102           target ? target->anonymousUniqueId().c_str() : "" )
103   );
104   return _value.c_str();
105 }
106
107 const char *const MediaAria2c::agentString()
108 {
109   // we need to add the release and identifier to the
110   // agent string.
111   // The target could be not initialized, and then this information
112   // is not available.
113   Target_Ptr target;
114   // FIXME this has to go away as soon as the target
115   // does not throw when not initialized.
116   try {
117       target = zypp::getZYpp()->target();
118   }
119   catch ( const Exception &e )
120   {
121       // nothing to do
122   }
123
124   static const std::string _value(
125     str::form(
126        "ZYpp %s (%s) %s"
127        , VERSION
128        , MediaAria2c::_aria2cVersion.c_str()
129        , target ? target->targetDistribution().c_str() : ""
130     )
131   );
132   return _value.c_str();
133 }
134
135
136 MediaAria2c::MediaAria2c( const Url &      url_r,
137                       const Pathname & attach_point_hint_r )
138     : MediaHandler( url_r, attach_point_hint_r,
139                     "/", // urlpath at attachpoint
140                     true ) // does_download
141 {
142   MIL << "MediaAria2c::MediaAria2c(" << url_r << ", " << attach_point_hint_r << ")" << endl;
143       
144   if( !attachPoint().empty())
145   {
146     PathInfo ainfo(attachPoint());
147     Pathname apath(attachPoint() + "XXXXXX");
148     char    *atemp = ::strdup( apath.asString().c_str());
149     char    *atest = NULL;
150     if( !ainfo.isDir() || !ainfo.userMayRWX() ||
151          atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
152     {
153       WAR << "attach point " << ainfo.path()
154           << " is not useable for " << url_r.getScheme() << endl;
155       setAttachPoint("", true);
156     }
157     else if( atest != NULL)
158       ::rmdir(atest);
159
160     if( atemp != NULL)
161       ::free(atemp);
162   }
163
164    //At this point, we initialize aria2c path
165    _aria2cPath = Pathname( whereisAria2c().asString() );
166
167    //Get aria2c version
168    _aria2cVersion = getAria2cVersion();
169 }
170
171 void MediaAria2c::attachTo (bool next)
172 {
173    // clear last arguments
174    _args.clear();   
175
176   if ( next )
177     ZYPP_THROW(MediaNotSupportedException(_url));
178
179   if ( !_url.isValid() )
180     ZYPP_THROW(MediaBadUrlException(_url));
181
182   if( !isUseableAttachPoint(attachPoint()))
183   {
184     std::string mountpoint = createAttachPoint().asString();
185
186     if( mountpoint.empty())
187       ZYPP_THROW( MediaBadAttachPointException(url()));
188
189     setAttachPoint( mountpoint, true);
190   }
191
192   disconnectFrom(); 
193
194   // Build the aria command.
195   _args.push_back(_aria2cPath.asString());
196   _args.push_back(str::form("--user-agent=%s", agentString()));
197   _args.push_back("--summary-interval=1");
198   _args.push_back("--follow-metalink=mem");
199   _args.push_back( "--check-integrity=true");
200   
201    // add the anonymous id.
202    _args.push_back(str::form("--header=%s", anonymousIdHeader() ));
203   // TODO add debug option
204    
205   // Transfer timeout
206   {
207     _xfer_timeout = TRANSFER_TIMEOUT;
208
209     std::string param(_url.getQueryParam("timeout"));
210     if( !param.empty())
211     {
212       long num = str::strtonum<long>( param);
213       if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
214         _xfer_timeout = num;
215     }
216   }
217
218   _args.push_back( str::form("--connect-timeout=%d", CONNECT_TIMEOUT));
219
220   // TODO limit redirections
221   // TODO Implement certificate validation
222
223   // FTP defaults to anonymous
224
225
226   if ( _url.getUsername().empty() )
227   {
228     if ( _url.getScheme() == "ftp" )
229     {
230       string id = "yast2@";
231       id += VERSION;
232       DBG << "Anonymous FTP identification: '" << id << "'" << endl;
233       _userpwd = "anonymous:" + id;
234     }
235   } 
236   else 
237   {
238      if ( _url.getScheme() == "ftp" )
239      { 
240          _args.push_back(str::form("--ftp-user=%s", _url.getUsername().c_str() ));
241      }
242      else if ( _url.getScheme() == "http" ||
243                _url.getScheme() == "https" )
244     {
245         _args.push_back(str::form("--http-user=%s", _url.getUsername().c_str() ));
246     }
247      
248     if ( _url.getPassword().size() )
249     {
250       if ( _url.getScheme() == "ftp" )
251       { 
252           _args.push_back(str::form("--ftp-passwd=%s", _url.getPassword().c_str() ));
253       }
254       else if ( _url.getScheme() == "http" ||
255                _url.getScheme() == "https" )
256       {
257           _args.push_back(str::form("--http-passwd=%s", _url.getPassword().c_str() ));
258       }
259     }
260   }
261
262   // note, aria2c does not support setting the auth type with
263   // (basic, digest yet)
264   
265
266   /*---------------------------------------------------------------*
267    CURLOPT_PROXY: host[:port]
268
269    Url::option(proxy and proxyport)
270    If not provided, /etc/sysconfig/proxy is evaluated
271    *---------------------------------------------------------------*/
272
273   _proxy = _url.getQueryParam( "proxy" );
274
275   if ( ! _proxy.empty() )
276   {
277     string proxyport( _url.getQueryParam( "proxyport" ) );
278     if ( ! proxyport.empty() ) {
279       _proxy += ":" + proxyport;
280     }
281   }
282   else
283   {
284
285     ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
286
287     if ( proxy_info.enabled())
288     {
289       bool useproxy = true;
290
291       std::list<std::string> nope = proxy_info.noProxy();
292       for (ProxyInfo::NoProxyIterator it = proxy_info.noProxyBegin();
293            it != proxy_info.noProxyEnd();
294            it++)
295       {
296         std::string host( str::toLower(_url.getHost()));
297         std::string temp( str::toLower(*it));
298
299         // no proxy if it points to a suffix
300         // preceeded by a '.', that maches
301         // the trailing portion of the host.
302         if( temp.size() > 1 && temp.at(0) == '.')
303         {
304           if(host.size() > temp.size() &&
305              host.compare(host.size() - temp.size(), temp.size(), temp) == 0)
306           {
307             DBG << "NO_PROXY: '" << *it  << "' matches host '"
308                                  << host << "'" << endl;
309             useproxy = false;
310             break;
311           }
312         }
313         else
314         // no proxy if we have an exact match
315         if( host == temp)
316         {
317           DBG << "NO_PROXY: '" << *it  << "' matches host '"
318                                << host << "'" << endl;
319           useproxy = false;
320           break;
321         }
322       }
323
324       if ( useproxy ) {
325         _proxy = proxy_info.proxy(_url.getScheme());
326       }
327     }
328   }
329
330   DBG << "Proxy: " << (_proxy.empty() ? "-none-" : _proxy) << endl;
331
332   if ( ! _proxy.empty() )
333   {
334       _args.push_back(str::form("--http-proxy=%s", _proxy.c_str() ));
335
336      /*---------------------------------------------------------------*
337      CURLOPT_PROXYUSERPWD: [user name]:[password]
338
339      Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
340      If not provided, $HOME/.curlrc is evaluated
341      *---------------------------------------------------------------*/
342
343     _proxyuserpwd = _url.getQueryParam( "proxyuser" );
344
345     if ( ! _proxyuserpwd.empty() ) {
346         _args.push_back(str::form("--http-proxy-user=%s", _proxyuserpwd.c_str() ));
347       
348       string proxypassword( _url.getQueryParam( "proxypassword" ) );
349       if ( ! proxypassword.empty() ) {
350           _args.push_back(str::form("--http-proxy-passwd=%s", proxypassword.c_str() ));
351       }
352     }
353   }
354
355   //_currentCookieFile = _cookieFile.asString();
356   //_args.push_back(str::form("--load-cookies=%s", _currentCookieFile.c_str()));
357   //NOTE cookie jar?
358
359   // FIXME: need a derived class to propelly compare url's
360   MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
361   setMediaSource(media);
362         
363 }
364
365 bool
366 MediaAria2c::checkAttachPoint(const Pathname &apoint) const
367 {
368   return MediaHandler::checkAttachPoint( apoint, true, true);
369 }
370
371 void MediaAria2c::disconnectFrom()
372 {
373 }
374
375 void MediaAria2c::releaseFrom( const std::string & ejectDev )
376 {
377   disconnect();
378 }
379
380 static Url getFileUrl(const Url & url, const Pathname & filename)
381 {
382   Url newurl(url);
383   string path = url.getPathName();
384   if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
385        filename.absolute() )
386   {
387     // If url has a path with trailing slash, remove the leading slash from
388     // the absolute file name
389     path += filename.asString().substr( 1, filename.asString().size() - 1 );
390   }
391   else if ( filename.relative() )
392   {
393     // Add trailing slash to path, if not already there
394     if (path.empty()) path = "/";
395     else if (*path.rbegin() != '/' ) path += "/";
396     // Remove "./" from begin of relative file name
397     path += filename.asString().substr( 2, filename.asString().size() - 2 );
398   }
399   else
400   {
401     path += filename.asString();
402   }
403
404   newurl.setPathName(path);
405   return newurl;
406 }
407
408 void MediaAria2c::getFile( const Pathname & filename ) const
409 {
410     // Use absolute file name to prevent access of files outside of the
411     // hierarchy below the attach point.    
412     getFileCopy(filename, localPath(filename).absolutename());
413 }
414
415 void MediaAria2c::getFileCopy( const Pathname & filename , const Pathname & target) const
416 {
417   callback::SendReport<DownloadProgressReport> report;
418
419   Url fileurl(getFileUrl(_url, filename));  
420
421   bool retry = false;
422
423   ExternalProgram::Arguments args = _args;
424   args.push_back(str::form("--dir=%s", target.dirname().c_str()));
425   args.push_back(fileurl.asString());
426   
427   do
428   {
429     try
430     {   
431       report->start(_url, target.asString() );  
432         
433       ExternalProgram aria(args, ExternalProgram::Stderr_To_Stdout);       
434       int nLine = 0;   
435
436       //Process response
437       for(std::string ariaResponse( aria.receiveLine());
438           ariaResponse.length(); 
439           ariaResponse = aria.receiveLine())
440       { 
441         //cout << ariaResponse;
442
443         if (!ariaResponse.substr(0,31).compare("Exception: Authorization failed") )
444         {
445             ZYPP_THROW(MediaUnauthorizedException(
446                   _url, "Login failed.", "Login failed", "auth hint"
447                 ));
448         }
449         if (!ariaResponse.substr(0,29).compare("Exception: Resource not found") )
450         {
451             ZYPP_THROW(MediaFileNotFoundException(_url, filename));
452         }        
453
454         if (!ariaResponse.substr(0,9).compare("[#2 SIZE:")) {
455                 
456           if (!nLine) 
457           {
458             size_t left_bound = ariaResponse.find('(',0) + 1;
459             size_t count = ariaResponse.find('%',left_bound) - left_bound;
460             //cout << ariaResponse.substr(left_bound, count) << endl;
461             //progressData.toMax();
462             report->progress ( std::atoi(ariaResponse.substr(left_bound, count).c_str()), _url, -1, -1 );
463             nLine = 1;
464           } 
465           else
466           {
467             nLine = 0;
468           }                  
469         } 
470       }
471       aria.close();
472         
473       report->finish( _url ,  zypp::media::DownloadProgressReport::NO_ERROR, "");
474       retry = false;
475     }
476  
477     // retry with proper authentication data
478     catch (MediaUnauthorizedException & ex_r)
479     {
480       if(authenticate(ex_r.hint(), !retry))
481         retry = true;
482       else
483       {
484         report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserString());
485         ZYPP_RETHROW(ex_r);
486       }
487
488     }
489     // unexpected exception
490     catch (MediaException & excpt_r)
491     {
492       // FIXME: error number fix
493       report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserString());
494       ZYPP_RETHROW(excpt_r);
495     }
496   }
497   while (retry);
498
499   report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
500 }
501
502 bool MediaAria2c::getDoesFileExist( const Pathname & filename ) const
503 {
504   bool retry = false;
505   AuthData auth_data;
506
507   do
508   {
509     try
510     {
511       return doGetDoesFileExist( filename );
512     }
513     // authentication problem, retry with proper authentication data
514     catch (MediaUnauthorizedException & ex_r)
515     {
516       if(authenticate(ex_r.hint(), !retry))
517         retry = true;
518       else
519         ZYPP_RETHROW(ex_r);
520     }
521     // unexpected exception
522     catch (MediaException & excpt_r)
523     {
524       ZYPP_RETHROW(excpt_r);
525     }
526   }
527   while (retry);
528
529   return false;
530 }
531
532 bool MediaAria2c::doGetDoesFileExist( const Pathname & filename ) const
533 {
534         
535   DBG << filename.asString() << endl;
536   return true;
537 }
538
539 void MediaAria2c::getDir( const Pathname & dirname, bool recurse_r ) const
540 {
541   filesystem::DirContent content;
542   getDirInfo( content, dirname, /*dots*/false );
543
544   for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
545       Pathname filename = dirname + it->name;
546       int res = 0;
547
548       switch ( it->type ) {
549       case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
550       case filesystem::FT_FILE:
551         getFile( filename );
552         break;
553       case filesystem::FT_DIR: // newer directory.yast contain at least directory info
554         if ( recurse_r ) {
555           getDir( filename, recurse_r );
556         } else {
557           res = assert_dir( localPath( filename ) );
558           if ( res ) {
559             WAR << "Ignore error (" << res <<  ") on creating local directory '" << localPath( filename ) << "'" << endl;
560           }
561         }
562         break;
563       default:
564         // don't provide devices, sockets, etc.
565         break;
566       }
567   }
568 }
569
570 bool MediaAria2c::authenticate(const std::string & availAuthTypes, bool firstTry) const
571 {
572     return false;
573 }
574
575
576 void MediaAria2c::getDirInfo( std::list<std::string> & retlist,
577                                const Pathname & dirname, bool dots ) const
578 {
579   getDirectoryYast( retlist, dirname, dots );
580 }
581
582 void MediaAria2c::getDirInfo( filesystem::DirContent & retlist,
583                             const Pathname & dirname, bool dots ) const
584 {
585   getDirectoryYast( retlist, dirname, dots );
586 }
587
588 std::string MediaAria2c::getAria2cVersion() 
589 {
590     const char* argv[] =
591     {
592         _aria2cPath.c_str(),
593       "--version",
594       NULL
595     };
596
597     ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
598
599     std::string vResponse = aria.receiveLine();
600     aria.close();
601     return str::trim(vResponse);
602 }
603
604 #define ARIA_DEFAULT_BINARY "/usr/bin/aria2c"
605
606 Pathname MediaAria2c::whereisAria2c()
607 {
608     Pathname aria2cPathr(ARIA_DEFAULT_BINARY);
609     
610     const char* argv[] =
611     {
612       "whereis",
613       "-b",
614       "aria2c",
615       NULL
616     };
617
618     ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
619            
620     std::string ariaResponse( aria.receiveLine());
621     aria.close();
622     
623     string::size_type pos = ariaResponse.find('/', 0 );
624     if( pos != string::npos ) 
625     {
626         aria2cPathr = ariaResponse;
627         string::size_type pose = ariaResponse.find(' ', pos + 1 );
628         aria2cPathr = ariaResponse.substr( pos , pose - pos );
629         MIL << "We will use aria2c located here:  " << ariaResponse.substr( pos , pose - pos) << endl;
630     }
631     else 
632     {
633         MIL << "We don't know were is ari2ac binary. We will use aria2c located here:  " << aria2cPathr << endl;
634     }
635     
636     return aria2cPathr;
637 }
638
639 } // namespace media
640 } // namespace zypp
641 //