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()
71 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
72 return ( aria.close() == 0 );
75 static const char *const anonymousIdHeader()
77 // we need to add the release and identifier to the
79 // The target could be not initialized, and then this information
81 Target_Ptr target = zypp::getZYpp()->getTarget();
83 static const std::string _value(
85 "X-Zypp-AnonymousId: %s",
86 target ? target->anonymousUniqueId().c_str() : "" )
88 return _value.c_str();
91 static const char *const distributionFlavorHeader()
93 // we need to add the release and identifier to the
95 // The target could be not initialized, and then this information
97 Target_Ptr target = zypp::getZYpp()->getTarget();
99 static const std::string _value(
100 str::trim( str::form(
101 "X-ZYpp-DistributionFlavor: %s",
102 target ? target->distributionFlavor().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
113 Target_Ptr target = zypp::getZYpp()->getTarget();
115 static const std::string _value(
119 , MediaAria2c::_aria2cVersion.c_str()
120 , target ? target->targetDistribution().c_str() : ""
123 return _value.c_str();
127 MediaAria2c::MediaAria2c( const Url & url_r,
128 const Pathname & attach_point_hint_r )
129 : MediaHandler( url_r, attach_point_hint_r,
130 "/", // urlpath at attachpoint
131 true ) // does_download
133 MIL << "MediaAria2c::MediaAria2c(" << url_r << ", " << attach_point_hint_r << ")" << endl;
135 if( !attachPoint().empty())
137 PathInfo ainfo(attachPoint());
138 Pathname apath(attachPoint() + "XXXXXX");
139 char *atemp = ::strdup( apath.asString().c_str());
141 if( !ainfo.isDir() || !ainfo.userMayRWX() ||
142 atemp == NULL || (atest=::mkdtemp(atemp)) == NULL)
144 WAR << "attach point " << ainfo.path()
145 << " is not useable for " << url_r.getScheme() << endl;
146 setAttachPoint("", true);
148 else if( atest != NULL)
155 //At this point, we initialize aria2c path
156 _aria2cPath = Pathname( whereisAria2c().asString() );
159 _aria2cVersion = getAria2cVersion();
162 void MediaAria2c::attachTo (bool next)
164 // clear last arguments
168 ZYPP_THROW(MediaNotSupportedException(_url));
170 if ( !_url.isValid() )
171 ZYPP_THROW(MediaBadUrlException(_url));
173 if( !isUseableAttachPoint(attachPoint()))
175 std::string mountpoint = createAttachPoint().asString();
177 if( mountpoint.empty())
178 ZYPP_THROW( MediaBadAttachPointException(url()));
180 setAttachPoint( mountpoint, true);
185 // Build the aria command.
186 _args.push_back(_aria2cPath.asString());
187 _args.push_back(str::form("--user-agent=%s", agentString()));
188 _args.push_back("--summary-interval=1");
189 _args.push_back("--follow-metalink=mem");
190 _args.push_back( "--check-integrity=true");
192 // add the anonymous id.
193 _args.push_back(str::form("--header=%s", anonymousIdHeader() ));
194 _args.push_back(str::form("--header=%s", distributionFlavorHeader() ));
195 // TODO add debug option
199 _xfer_timeout = TRANSFER_TIMEOUT;
201 std::string param(_url.getQueryParam("timeout"));
204 long num = str::strtonum<long>( param);
205 if( num >= 0 && num <= TRANSFER_TIMEOUT_MAX)
210 _args.push_back( str::form("--connect-timeout=%d", CONNECT_TIMEOUT));
212 // TODO limit redirections
213 // TODO Implement certificate validation
215 // FTP defaults to anonymous
218 if ( _url.getUsername().empty() )
220 if ( _url.getScheme() == "ftp" )
222 string id = "yast2@";
224 DBG << "Anonymous FTP identification: '" << id << "'" << endl;
225 _userpwd = "anonymous:" + id;
230 if ( _url.getScheme() == "ftp" )
232 _args.push_back(str::form("--ftp-user=%s", _url.getUsername().c_str() ));
234 else if ( _url.getScheme() == "http" ||
235 _url.getScheme() == "https" )
237 _args.push_back(str::form("--http-user=%s", _url.getUsername().c_str() ));
240 if ( _url.getPassword().size() )
242 if ( _url.getScheme() == "ftp" )
244 _args.push_back(str::form("--ftp-passwd=%s", _url.getPassword().c_str() ));
246 else if ( _url.getScheme() == "http" ||
247 _url.getScheme() == "https" )
249 _args.push_back(str::form("--http-passwd=%s", _url.getPassword().c_str() ));
254 // note, aria2c does not support setting the auth type with
255 // (basic, digest yet)
258 /*---------------------------------------------------------------*
259 CURLOPT_PROXY: host[:port]
261 Url::option(proxy and proxyport)
262 If not provided, /etc/sysconfig/proxy is evaluated
263 *---------------------------------------------------------------*/
265 _proxy = _url.getQueryParam( "proxy" );
267 if ( ! _proxy.empty() )
269 string proxyport( _url.getQueryParam( "proxyport" ) );
270 if ( ! proxyport.empty() ) {
271 _proxy += ":" + proxyport;
277 ProxyInfo proxy_info (ProxyInfo::ImplPtr(new ProxyInfoSysconfig("proxy")));
279 if ( proxy_info.enabled())
281 bool useproxy = true;
283 std::list<std::string> nope = proxy_info.noProxy();
284 for (ProxyInfo::NoProxyIterator it = proxy_info.noProxyBegin();
285 it != proxy_info.noProxyEnd();
288 std::string host( str::toLower(_url.getHost()));
289 std::string temp( str::toLower(*it));
291 // no proxy if it points to a suffix
292 // preceeded by a '.', that maches
293 // the trailing portion of the host.
294 if( temp.size() > 1 && temp.at(0) == '.')
296 if(host.size() > temp.size() &&
297 host.compare(host.size() - temp.size(), temp.size(), temp) == 0)
299 DBG << "NO_PROXY: '" << *it << "' matches host '"
300 << host << "'" << endl;
306 // no proxy if we have an exact match
309 DBG << "NO_PROXY: '" << *it << "' matches host '"
310 << host << "'" << endl;
317 _proxy = proxy_info.proxy(_url.getScheme());
322 DBG << "Proxy: " << (_proxy.empty() ? "-none-" : _proxy) << endl;
324 if ( ! _proxy.empty() )
326 _args.push_back(str::form("--http-proxy=%s", _proxy.c_str() ));
328 /*---------------------------------------------------------------*
329 CURLOPT_PROXYUSERPWD: [user name]:[password]
331 Url::option(proxyuser and proxypassword) -> CURLOPT_PROXYUSERPWD
332 If not provided, $HOME/.curlrc is evaluated
333 *---------------------------------------------------------------*/
335 _proxyuserpwd = _url.getQueryParam( "proxyuser" );
337 if ( ! _proxyuserpwd.empty() ) {
338 _args.push_back(str::form("--http-proxy-user=%s", _proxyuserpwd.c_str() ));
340 string proxypassword( _url.getQueryParam( "proxypassword" ) );
341 if ( ! proxypassword.empty() ) {
342 _args.push_back(str::form("--http-proxy-passwd=%s", proxypassword.c_str() ));
347 //_currentCookieFile = _cookieFile.asString();
348 //_args.push_back(str::form("--load-cookies=%s", _currentCookieFile.c_str()));
351 // FIXME: need a derived class to propelly compare url's
352 MediaSourceRef media( new MediaSource(_url.getScheme(), _url.asString()));
353 setMediaSource(media);
358 MediaAria2c::checkAttachPoint(const Pathname &apoint) const
360 return MediaHandler::checkAttachPoint( apoint, true, true);
363 void MediaAria2c::disconnectFrom()
367 void MediaAria2c::releaseFrom( const std::string & ejectDev )
372 static Url getFileUrl(const Url & url, const Pathname & filename)
375 string path = url.getPathName();
376 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
377 filename.absolute() )
379 // If url has a path with trailing slash, remove the leading slash from
380 // the absolute file name
381 path += filename.asString().substr( 1, filename.asString().size() - 1 );
383 else if ( filename.relative() )
385 // Add trailing slash to path, if not already there
386 if (path.empty()) path = "/";
387 else if (*path.rbegin() != '/' ) path += "/";
388 // Remove "./" from begin of relative file name
389 path += filename.asString().substr( 2, filename.asString().size() - 2 );
393 path += filename.asString();
396 newurl.setPathName(path);
400 void MediaAria2c::getFile( const Pathname & filename ) const
402 // Use absolute file name to prevent access of files outside of the
403 // hierarchy below the attach point.
404 getFileCopy(filename, localPath(filename).absolutename());
407 void MediaAria2c::getFileCopy( const Pathname & filename , const Pathname & target) const
409 callback::SendReport<DownloadProgressReport> report;
411 Url fileurl(getFileUrl(_url, filename));
415 ExternalProgram::Arguments args = _args;
416 args.push_back(str::form("--dir=%s", target.dirname().c_str()));
418 args.push_back(fileurl.asString());
424 report->start(_url, target.asString() );
426 ExternalProgram aria(args, ExternalProgram::Stderr_To_Stdout);
430 for(std::string ariaResponse( aria.receiveLine());
431 ariaResponse.length();
432 ariaResponse = aria.receiveLine())
434 //cout << ariaResponse;
436 if (!ariaResponse.substr(0,31).compare("Exception: Authorization failed") )
438 ZYPP_THROW(MediaUnauthorizedException(
439 _url, "Login failed.", "Login failed", "auth hint"
442 if (!ariaResponse.substr(0,29).compare("Exception: Resource not found") )
444 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
447 if (!ariaResponse.substr(0,9).compare("[#2 SIZE:"))
451 size_t left_bound = ariaResponse.find('(',0) + 1;
452 size_t count = ariaResponse.find('%',left_bound) - left_bound;
453 //cout << ariaResponse.substr(left_bound, count) << endl;
454 //progressData.toMax();
455 report->progress ( std::atoi(ariaResponse.substr(left_bound, count).c_str()), _url, -1, -1 );
467 report->finish( _url , zypp::media::DownloadProgressReport::NO_ERROR, "");
471 // retry with proper authentication data
472 catch (MediaUnauthorizedException & ex_r)
474 if(authenticate(ex_r.hint(), !retry))
478 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
483 // unexpected exception
484 catch (MediaException & excpt_r)
486 // FIXME: error number fix
487 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
488 ZYPP_RETHROW(excpt_r);
493 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
496 bool MediaAria2c::getDoesFileExist( const Pathname & filename ) const
505 return doGetDoesFileExist( filename );
507 // authentication problem, retry with proper authentication data
508 catch (MediaUnauthorizedException & ex_r)
510 if(authenticate(ex_r.hint(), !retry))
515 // unexpected exception
516 catch (MediaException & excpt_r)
518 ZYPP_RETHROW(excpt_r);
526 bool MediaAria2c::doGetDoesFileExist( const Pathname & filename ) const
529 DBG << filename.asString() << endl;
533 void MediaAria2c::getDir( const Pathname & dirname, bool recurse_r ) const
535 filesystem::DirContent content;
536 getDirInfo( content, dirname, /*dots*/false );
538 for ( filesystem::DirContent::const_iterator it = content.begin(); it != content.end(); ++it ) {
539 Pathname filename = dirname + it->name;
542 switch ( it->type ) {
543 case filesystem::FT_NOT_AVAIL: // old directory.yast contains no typeinfo at all
544 case filesystem::FT_FILE:
547 case filesystem::FT_DIR: // newer directory.yast contain at least directory info
549 getDir( filename, recurse_r );
551 res = assert_dir( localPath( filename ) );
553 WAR << "Ignore error (" << res << ") on creating local directory '" << localPath( filename ) << "'" << endl;
558 // don't provide devices, sockets, etc.
564 bool MediaAria2c::authenticate(const std::string & availAuthTypes, bool firstTry) const
570 void MediaAria2c::getDirInfo( std::list<std::string> & retlist,
571 const Pathname & dirname, bool dots ) const
573 getDirectoryYast( retlist, dirname, dots );
576 void MediaAria2c::getDirInfo( filesystem::DirContent & retlist,
577 const Pathname & dirname, bool dots ) const
579 getDirectoryYast( retlist, dirname, dots );
582 std::string MediaAria2c::getAria2cVersion()
591 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
593 std::string vResponse = aria.receiveLine();
595 return str::trim(vResponse);
598 #define ARIA_DEFAULT_BINARY "/usr/bin/aria2c"
600 Pathname MediaAria2c::whereisAria2c()
602 Pathname aria2cPathr(ARIA_DEFAULT_BINARY);
611 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
613 std::string ariaResponse( aria.receiveLine());
614 int code = aria.close();
618 aria2cPathr = str::trim(ariaResponse);
619 MIL << "We will use aria2c located here: " << aria2cPathr << endl;
623 MIL << "We don't know were is ari2ac binary. We will use aria2c located here: " << aria2cPathr << endl;