1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/media/MediaAria2c.cc
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"
25 #include "zypp/Target.h"
26 #include "zypp/ZYppFactory.h"
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"
34 #include <sys/types.h>
36 #include <sys/mount.h>
40 #include <boost/format.hpp>
42 #define DETECT_DIR_INDEX 0
43 #define CONNECT_TIMEOUT 60
44 #define TRANSFER_TIMEOUT 60 * 3
45 #define TRANSFER_TIMEOUT_MAX 60 * 60
49 using namespace zypp::base;
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";
60 //check if aria2c is present in the system
62 MediaAria2c::existsAria2cmd()
72 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
74 std::string ariaResponse( aria.receiveLine());
75 string::size_type pos = ariaResponse.find('/', 0 );
76 if( pos != string::npos )
82 static const char *const anonymousIdHeader()
84 // we need to add the release and identifier to the
86 // The target could be not initialized, and then this information
88 Target_Ptr target = zypp::getZYpp()->getTarget();
90 static const std::string _value(
92 "X-Zypp-AnonymousId: %s",
93 target ? target->anonymousUniqueId().c_str() : "" )
95 return _value.c_str();
98 static const char *const distributionFlavorHeader()
100 // we need to add the release and identifier to the
102 // The target could be not initialized, and then this information
104 Target_Ptr target = zypp::getZYpp()->getTarget();
106 static const std::string _value(
107 str::trim( str::form(
108 "X-ZYpp-DistributionFlavor: %s",
109 target ? target->distributionFlavor().c_str() : "" ) )
111 return _value.c_str();
114 const char *const MediaAria2c::agentString()
116 // we need to add the release and identifier to the
118 // The target could be not initialized, and then this information
120 Target_Ptr target = zypp::getZYpp()->getTarget();
122 static const std::string _value(
126 , MediaAria2c::_aria2cVersion.c_str()
127 , target ? target->targetDistribution().c_str() : ""
130 return _value.c_str();
134 MediaAria2c::MediaAria2c( const Url & url_r,
135 const Pathname & attach_point_hint_r )
136 : MediaHandler( url_r, attach_point_hint_r,
137 "/", // urlpath at attachpoint
138 true ) // does_download
140 MIL << "MediaAria2c::MediaAria2c(" << url_r << ", " << attach_point_hint_r << ")" << endl;
142 if( !attachPoint().empty())
144 PathInfo ainfo(attachPoint());
145 Pathname apath(attachPoint() + "XXXXXX");
146 char *atemp = ::strdup( apath.asString().c_str());
148 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
149 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
151 WAR << "attach point " << ainfo.path()
152 << " is not useable for " << url_r.getScheme() << endl;
153 setAttachPoint("", true);
155 else if( atest != NULL)
162 //At this point, we initialize aria2c path
163 _aria2cPath = Pathname( whereisAria2c().asString() );
166 _aria2cVersion = getAria2cVersion();
169 void MediaAria2c::attachTo (bool next)
171 // clear last arguments
175 ZYPP_THROW(MediaNotSupportedException(_url));
177 if ( !_url.isValid() )
178 ZYPP_THROW(MediaBadUrlException(_url));
180 if( !isUseableAttachPoint(attachPoint()))
182 std::string mountpoint = createAttachPoint().asString();
184 if( mountpoint.empty())
185 ZYPP_THROW( MediaBadAttachPointException(url()));
187 setAttachPoint( mountpoint, true);
192 // Build the aria command.
193 _args.push_back(_aria2cPath.asString());
194 _args.push_back(str::form("--user-agent=%s", agentString()));
195 _args.push_back("--summary-interval=1");
196 _args.push_back("--follow-metalink=mem");
197 _args.push_back( "--check-integrity=true");
199 // add the anonymous id.
200 _args.push_back(str::form("--header=%s", anonymousIdHeader() ));
201 _args.push_back(str::form("--header=%s", distributionFlavorHeader() ));
202 // TODO add debug option
206 _xfer_timeout = TRANSFER_TIMEOUT;
208 std::string param(_url.getQueryParam("timeout"));
211 long num = str::strtonum<long>( param);
212 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
217 _args.push_back( str::form("--connect-timeout=%d", CONNECT_TIMEOUT));
219 // TODO limit redirections
220 // TODO Implement certificate validation
222 // FTP defaults to anonymous
225 if ( _url.getUsername().empty() )
227 if ( _url.getScheme() == "ftp" )
229 string id = "yast2@";
231 DBG << "Anonymous FTP identification: '" << id << "'" << endl;
232 _userpwd = "anonymous:" + id;
237 if ( _url.getScheme() == "ftp" )
239 _args.push_back(str::form("--ftp-user=%s", _url.getUsername().c_str() ));
241 else if ( _url.getScheme() == "http" ||
242 _url.getScheme() == "https" )
244 _args.push_back(str::form("--http-user=%s", _url.getUsername().c_str() ));
247 if ( _url.getPassword().size() )
249 if ( _url.getScheme() == "ftp" )
251 _args.push_back(str::form("--ftp-passwd=%s", _url.getPassword().c_str() ));
253 else if ( _url.getScheme() == "http" ||
254 _url.getScheme() == "https" )
256 _args.push_back(str::form("--http-passwd=%s", _url.getPassword().c_str() ));
261 // note, aria2c does not support setting the auth type with
262 // (basic, digest yet)
265 /*---------------------------------------------------------------*
266 CURLOPT_PROXY: host[:port]
268 Url::option(proxy and proxyport)
269 If not provided, /etc/sysconfig/proxy is evaluated
270 *---------------------------------------------------------------*/
272 _proxy = _url.getQueryParam( "proxy" );
274 if ( ! _proxy.empty() )
276 string proxyport( _url.getQueryParam( "proxyport" ) );
277 if ( ! proxyport.empty() ) {
278 _proxy += ":" + proxyport;
284 ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
286 if ( proxy_info.enabled())
288 bool useproxy = true;
290 std::list<std::string> nope = proxy_info.noProxy();
291 for (ProxyInfo::NoProxyIterator it = proxy_info.noProxyBegin();
292 it != proxy_info.noProxyEnd();
295 std::string host( str::toLower(_url.getHost()));
296 std::string temp( str::toLower(*it));
298 // no proxy if it points to a suffix
299 // preceeded by a '.', that maches
300 // the trailing portion of the host.
301 if( temp.size() > 1 && temp.at(0) == '.')
303 if(host.size() > temp.size() &&
304 host.compare(host.size() - temp.size(), temp.size(), temp) == 0)
306 DBG << "NO_PROXY: '" << *it << "' matches host '"
307 << host << "'" << endl;
313 // no proxy if we have an exact match
316 DBG << "NO_PROXY: '" << *it << "' matches host '"
317 << host << "'" << endl;
324 _proxy = proxy_info.proxy(_url.getScheme());
329 DBG << "Proxy: " << (_proxy.empty() ? "-none-" : _proxy) << endl;
331 if ( ! _proxy.empty() )
333 _args.push_back(str::form("--http-proxy=%s", _proxy.c_str() ));
335 /*---------------------------------------------------------------*
336 CURLOPT_PROXYUSERPWD: [user name]:[password]
338 Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
339 If not provided, $HOME/.curlrc is evaluated
340 *---------------------------------------------------------------*/
342 _proxyuserpwd = _url.getQueryParam( "proxyuser" );
344 if ( ! _proxyuserpwd.empty() ) {
345 _args.push_back(str::form("--http-proxy-user=%s", _proxyuserpwd.c_str() ));
347 string proxypassword( _url.getQueryParam( "proxypassword" ) );
348 if ( ! proxypassword.empty() ) {
349 _args.push_back(str::form("--http-proxy-passwd=%s", proxypassword.c_str() ));
354 //_currentCookieFile = _cookieFile.asString();
355 //_args.push_back(str::form("--load-cookies=%s", _currentCookieFile.c_str()));
358 // FIXME: need a derived class to propelly compare url's
359 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
360 setMediaSource(media);
365 MediaAria2c::checkAttachPoint(const Pathname &apoint) const
367 return MediaHandler::checkAttachPoint( apoint, true, true);
370 void MediaAria2c::disconnectFrom()
374 void MediaAria2c::releaseFrom( const std::string & ejectDev )
379 static Url getFileUrl(const Url & url, const Pathname & filename)
382 string path = url.getPathName();
383 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
384 filename.absolute() )
386 // If url has a path with trailing slash, remove the leading slash from
387 // the absolute file name
388 path += filename.asString().substr( 1, filename.asString().size() - 1 );
390 else if ( filename.relative() )
392 // Add trailing slash to path, if not already there
393 if (path.empty()) path = "/";
394 else if (*path.rbegin() != '/' ) path += "/";
395 // Remove "./" from begin of relative file name
396 path += filename.asString().substr( 2, filename.asString().size() - 2 );
400 path += filename.asString();
403 newurl.setPathName(path);
407 void MediaAria2c::getFile( const Pathname & filename ) const
409 // Use absolute file name to prevent access of files outside of the
410 // hierarchy below the attach point.
411 getFileCopy(filename, localPath(filename).absolutename());
414 void MediaAria2c::getFileCopy( const Pathname & filename , const Pathname & target) const
416 callback::SendReport<DownloadProgressReport> report;
418 Url fileurl(getFileUrl(_url, filename));
422 ExternalProgram::Arguments args = _args;
423 args.push_back(str::form("--dir=%s", target.dirname().c_str()));
425 args.push_back(fileurl.asString());
431 report->start(_url, target.asString() );
433 ExternalProgram aria(args, ExternalProgram::Stderr_To_Stdout);
437 for(std::string ariaResponse( aria.receiveLine());
438 ariaResponse.length();
439 ariaResponse = aria.receiveLine())
441 //cout << ariaResponse;
443 if (!ariaResponse.substr(0,31).compare("Exception: Authorization failed") )
445 ZYPP_THROW(MediaUnauthorizedException(
446 _url, "Login failed.", "Login failed", "auth hint"
449 if (!ariaResponse.substr(0,29).compare("Exception: Resource not found") )
451 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
454 if (!ariaResponse.substr(0,9).compare("[#2 SIZE:"))
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 );
474 report->finish( _url , zypp::media::DownloadProgressReport::NO_ERROR, "");
478 // retry with proper authentication data
479 catch (MediaUnauthorizedException & ex_r)
481 if(authenticate(ex_r.hint(), !retry))
485 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
490 // unexpected exception
491 catch (MediaException & excpt_r)
493 // FIXME: error number fix
494 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
495 ZYPP_RETHROW(excpt_r);
500 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
503 bool MediaAria2c::getDoesFileExist( const Pathname & filename ) const
512 return doGetDoesFileExist( filename );
514 // authentication problem, retry with proper authentication data
515 catch (MediaUnauthorizedException & ex_r)
517 if(authenticate(ex_r.hint(), !retry))
522 // unexpected exception
523 catch (MediaException & excpt_r)
525 ZYPP_RETHROW(excpt_r);
533 bool MediaAria2c::doGetDoesFileExist( const Pathname & filename ) const
536 DBG << filename.asString() << endl;
540 void MediaAria2c::getDir( const Pathname & dirname, bool recurse_r ) const
542 filesystem::DirContent content;
543 getDirInfo( content, dirname, /*dots*/false );
545 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
546 Pathname filename = dirname + it->name;
549 switch ( it->type ) {
550 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
551 case filesystem::FT_FILE:
554 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
556 getDir( filename, recurse_r );
558 res = assert_dir( localPath( filename ) );
560 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
565 // don't provide devices, sockets, etc.
571 bool MediaAria2c::authenticate(const std::string & availAuthTypes, bool firstTry) const
577 void MediaAria2c::getDirInfo( std::list<std::string> & retlist,
578 const Pathname & dirname, bool dots ) const
580 getDirectoryYast( retlist, dirname, dots );
583 void MediaAria2c::getDirInfo( filesystem::DirContent & retlist,
584 const Pathname & dirname, bool dots ) const
586 getDirectoryYast( retlist, dirname, dots );
589 std::string MediaAria2c::getAria2cVersion()
598 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
600 std::string vResponse = aria.receiveLine();
602 return str::trim(vResponse);
605 #define ARIA_DEFAULT_BINARY "/usr/bin/aria2c"
607 Pathname MediaAria2c::whereisAria2c()
609 Pathname aria2cPathr(ARIA_DEFAULT_BINARY);
619 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
621 std::string ariaResponse( aria.receiveLine());
624 string::size_type pos = ariaResponse.find('/', 0 );
625 if( pos != string::npos )
627 aria2cPathr = ariaResponse;
628 string::size_type pose = ariaResponse.find(' ', pos + 1 );
629 aria2cPathr = ariaResponse.substr( pos , pose - pos );
630 MIL << "We will use aria2c located here: " << ariaResponse.substr( pos , pose - pos) << endl;
634 MIL << "We don't know were is ari2ac binary. We will use aria2c located here: " << aria2cPathr << endl;