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 const char *const MediaAria2c::anonymousIdHeader()
84 // we need to add the release and identifier to the
86 // The target could be not initialized, and then this information
89 // FIXME this has to go away as soon as the target
90 // does not throw when not initialized.
92 target = zypp::getZYpp()->target();
94 catch ( const Exception &e )
99 static const std::string _value(
101 "X-ZYpp-AnonymousUniqueId: %s",
102 target ? target->anonymousUniqueId().c_str() : "" )
104 return _value.c_str();
107 const char *const MediaAria2c::agentString()
109 // we need to add the release and identifier to the
111 // The target could be not initialized, and then this information
114 // FIXME this has to go away as soon as the target
115 // does not throw when not initialized.
117 target = zypp::getZYpp()->target();
119 catch ( const Exception &e )
124 static const std::string _value(
126 "ZYpp %s (aria2c %s) %s"
128 , MediaAria2c::_aria2cVersion.c_str()
129 , target ? target->targetDistribution().c_str() : ""
132 return _value.c_str();
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
142 MIL << "MediaAria2c::MediaAria2c(" << url_r << ", " << attach_point_hint_r << ")" << endl;
144 if( !attachPoint().empty())
146 PathInfo ainfo(attachPoint());
147 Pathname apath(attachPoint() + "XXXXXX");
148 char *atemp = ::strdup( apath.asString().c_str());
150 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
151 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
153 WAR << "attach point " << ainfo.path()
154 << " is not useable for " << url_r.getScheme() << endl;
155 setAttachPoint("", true);
157 else if( atest != NULL)
164 //At this point, we initialize aria2c path
165 _aria2cPath = Pathname( whereisAria2c().asString() );
168 _aria2cVersion = getAria2cVersion();
171 void MediaAria2c::attachTo (bool next)
173 // clear last arguments
176 _args.push_back(_aria2cPath.asString());
177 _args.push_back("--summary-interval=1");
178 _args.push_back("--follow-metalink=mem");
179 _args.push_back("--check-integrity=true");
181 // add the anonymous id.
182 _args.push_back(str::form("--header=\"%s\"", anonymousIdHeader() ));
186 ZYPP_THROW(MediaNotSupportedException(_url));
188 if ( !_url.isValid() )
189 ZYPP_THROW(MediaBadUrlException(_url));
191 if( !isUseableAttachPoint(attachPoint()))
193 std::string mountpoint = createAttachPoint().asString();
195 if( mountpoint.empty())
196 ZYPP_THROW( MediaBadAttachPointException(url()));
198 setAttachPoint( mountpoint, true);
203 // Build the aria command.
204 _args.push_back(_aria2cPath.asString());
205 _args.push_back(str::form("--user-agent=\"%s\"", agentString()));
206 _args.push_back("--summary-interval=1");
207 _args.push_back("--follow-metalink=mem");
208 _args.push_back( "--check-integrity=true");
210 // TODO add debug option
214 _xfer_timeout = TRANSFER_TIMEOUT;
216 std::string param(_url.getQueryParam("timeout"));
219 long num = str::strtonum<long>( param);
220 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
225 _args.push_back( str::form("--connect-timeout=%d", CONNECT_TIMEOUT));
227 // TODO limit redirections
228 // TODO Implement certificate validation
230 // FTP defaults to anonymous
233 if ( _url.getUsername().empty() )
235 if ( _url.getScheme() == "ftp" )
237 string id = "yast2@";
239 DBG << "Anonymous FTP identification: '" << id << "'" << endl;
240 _userpwd = "anonymous:" + id;
245 if ( _url.getScheme() == "ftp" )
247 _args.push_back("--ftp-user");
248 _args.push_back(_url.getUsername());
250 else if ( _url.getScheme() == "http" ||
251 _url.getScheme() == "https" )
253 _args.push_back("--http-user");
254 _args.push_back(_url.getUsername());
257 if ( _url.getPassword().size() )
259 if ( _url.getScheme() == "ftp" )
261 _args.push_back("--ftp-passwd");
262 _args.push_back(_url.getPassword());
264 else if ( _url.getScheme() == "http" ||
265 _url.getScheme() == "https" )
267 _args.push_back("--http-passwd");
268 _args.push_back(_url.getPassword());
273 // note, aria2c does not support setting the auth type with
274 // (basic, digest yet)
277 /*---------------------------------------------------------------*
278 CURLOPT_PROXY: host[:port]
280 Url::option(proxy and proxyport)
281 If not provided, /etc/sysconfig/proxy is evaluated
282 *---------------------------------------------------------------*/
284 _proxy = _url.getQueryParam( "proxy" );
286 if ( ! _proxy.empty() )
288 string proxyport( _url.getQueryParam( "proxyport" ) );
289 if ( ! proxyport.empty() ) {
290 _proxy += ":" + proxyport;
296 ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
298 if ( proxy_info.enabled())
300 bool useproxy = true;
302 std::list<std::string> nope = proxy_info.noProxy();
303 for (ProxyInfo::NoProxyIterator it = proxy_info.noProxyBegin();
304 it != proxy_info.noProxyEnd();
307 std::string host( str::toLower(_url.getHost()));
308 std::string temp( str::toLower(*it));
310 // no proxy if it points to a suffix
311 // preceeded by a '.', that maches
312 // the trailing portion of the host.
313 if( temp.size() > 1 && temp.at(0) == '.')
315 if(host.size() > temp.size() &&
316 host.compare(host.size() - temp.size(), temp.size(), temp) == 0)
318 DBG << "NO_PROXY: '" << *it << "' matches host '"
319 << host << "'" << endl;
325 // no proxy if we have an exact match
328 DBG << "NO_PROXY: '" << *it << "' matches host '"
329 << host << "'" << endl;
336 _proxy = proxy_info.proxy(_url.getScheme());
341 DBG << "Proxy: " << (_proxy.empty() ? "-none-" : _proxy) << endl;
343 if ( ! _proxy.empty() )
345 _args.push_back("-—http-proxy");
346 _args.push_back(_proxy);
348 /*---------------------------------------------------------------*
349 CURLOPT_PROXYUSERPWD: [user name]:[password]
351 Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
352 If not provided, $HOME/.curlrc is evaluated
353 *---------------------------------------------------------------*/
355 _proxyuserpwd = _url.getQueryParam( "proxyuser" );
357 if ( ! _proxyuserpwd.empty() ) {
358 _args.push_back("-—http-proxy-user");
359 _args.push_back(_proxyuserpwd);
361 string proxypassword( _url.getQueryParam( "proxypassword" ) );
362 if ( ! proxypassword.empty() ) {
363 _args.push_back("-—http-proxy-passwd");
364 _args.push_back(proxypassword);
369 _currentCookieFile = _cookieFile.asString();
370 _args.push_back("-—load-cookies");
371 _args.push_back(_currentCookieFile);
375 // FIXME: need a derived class to propelly compare url's
376 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
377 setMediaSource(media);
382 MediaAria2c::checkAttachPoint(const Pathname &apoint) const
384 return MediaHandler::checkAttachPoint( apoint, true, true);
387 void MediaAria2c::disconnectFrom()
391 void MediaAria2c::releaseFrom( const std::string & ejectDev )
396 static Url getFileUrl(const Url & url, const Pathname & filename)
399 string path = url.getPathName();
400 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
401 filename.absolute() )
403 // If url has a path with trailing slash, remove the leading slash from
404 // the absolute file name
405 path += filename.asString().substr( 1, filename.asString().size() - 1 );
407 else if ( filename.relative() )
409 // Add trailing slash to path, if not already there
410 if (path.empty()) path = "/";
411 else if (*path.rbegin() != '/' ) path += "/";
412 // Remove "./" from begin of relative file name
413 path += filename.asString().substr( 2, filename.asString().size() - 2 );
417 path += filename.asString();
420 newurl.setPathName(path);
424 void MediaAria2c::getFile( const Pathname & filename ) const
426 // Use absolute file name to prevent access of files outside of the
427 // hierarchy below the attach point.
428 getFileCopy(filename, localPath(filename).absolutename());
431 void MediaAria2c::getFileCopy( const Pathname & filename , const Pathname & target) const
433 callback::SendReport<DownloadProgressReport> report;
435 Url fileurl(getFileUrl(_url, filename));
439 ExternalProgram::Arguments args = _args;
440 args.push_back(str::form("--dir=\"%s\"", target.dirname().c_str()));
441 args.push_back(fileurl.asString());
447 report->start(_url, target.asString() );
449 ExternalProgram aria(args, ExternalProgram::Stderr_To_Stdout);
453 for(std::string ariaResponse( aria.receiveLine());
454 ariaResponse.length();
455 ariaResponse = aria.receiveLine())
457 //cout << ariaResponse;
459 if (!ariaResponse.substr(0,31).compare("Exception: Authorization failed") )
461 ZYPP_THROW(MediaUnauthorizedException(
462 _url, "Login failed.", "Login failed", "auth hint"
465 if (!ariaResponse.substr(0,29).compare("Exception: Resource not found") )
467 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
470 if (!ariaResponse.substr(0,9).compare("[#2 SIZE:")) {
474 size_t left_bound = ariaResponse.find('(',0) + 1;
475 size_t count = ariaResponse.find('%',left_bound) - left_bound;
476 //cout << ariaResponse.substr(left_bound, count) << endl;
477 //progressData.toMax();
478 report->progress ( std::atoi(ariaResponse.substr(left_bound, count).c_str()), _url, -1, -1 );
489 report->finish( _url , zypp::media::DownloadProgressReport::NO_ERROR, "");
493 // retry with proper authentication data
494 catch (MediaUnauthorizedException & ex_r)
496 if(authenticate(ex_r.hint(), !retry))
500 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserString());
505 // unexpected exception
506 catch (MediaException & excpt_r)
508 // FIXME: error number fix
509 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserString());
510 ZYPP_RETHROW(excpt_r);
515 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
518 bool MediaAria2c::getDoesFileExist( const Pathname & filename ) const
527 return doGetDoesFileExist( filename );
529 // authentication problem, retry with proper authentication data
530 catch (MediaUnauthorizedException & ex_r)
532 if(authenticate(ex_r.hint(), !retry))
537 // unexpected exception
538 catch (MediaException & excpt_r)
540 ZYPP_RETHROW(excpt_r);
548 bool MediaAria2c::doGetDoesFileExist( const Pathname & filename ) const
551 DBG << filename.asString() << endl;
555 void MediaAria2c::getDir( const Pathname & dirname, bool recurse_r ) const
557 filesystem::DirContent content;
558 getDirInfo( content, dirname, /*dots*/false );
560 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
561 Pathname filename = dirname + it->name;
564 switch ( it->type ) {
565 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
566 case filesystem::FT_FILE:
569 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
571 getDir( filename, recurse_r );
573 res = assert_dir( localPath( filename ) );
575 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
580 // don't provide devices, sockets, etc.
586 bool MediaAria2c::authenticate(const std::string & availAuthTypes, bool firstTry) const
592 void MediaAria2c::getDirInfo( std::list<std::string> & retlist,
593 const Pathname & dirname, bool dots ) const
595 getDirectoryYast( retlist, dirname, dots );
598 void MediaAria2c::getDirInfo( filesystem::DirContent & retlist,
599 const Pathname & dirname, bool dots ) const
601 getDirectoryYast( retlist, dirname, dots );
604 std::string MediaAria2c::getAria2cVersion()
613 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
615 std::string vResponse = aria.receiveLine();
620 #define ARIA_DEFAULT_BINARY "/usr/bin/aria2c"
622 Pathname MediaAria2c::whereisAria2c()
624 Pathname aria2cPathr(ARIA_DEFAULT_BINARY);
634 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
636 std::string ariaResponse( aria.receiveLine());
639 string::size_type pos = ariaResponse.find('/', 0 );
640 if( pos != string::npos )
642 aria2cPathr = ariaResponse;
643 string::size_type pose = ariaResponse.find(' ', pos + 1 );
644 aria2cPathr = ariaResponse.substr( pos , pose - pos );
645 MIL << "We will use aria2c located here: " << ariaResponse.substr( pos , pose - pos) << endl;
649 MIL << "We don't know were is ari2ac binary. We will use aria2c located here: " << aria2cPathr << endl;