1 /*---------------------------------------------------------------------\
3 | |__ / \ / / . \ . \ |
8 \---------------------------------------------------------------------*/
9 /** \file zypp/media/MediaAria2c.cc
16 #include <boost/lexical_cast.hpp>
18 #include "zypp/base/Logger.h"
19 #include "zypp/ExternalProgram.h"
20 #include "zypp/ProgressData.h"
21 #include "zypp/base/String.h"
22 #include "zypp/base/Gettext.h"
23 #include "zypp/base/Sysconfig.h"
24 #include "zypp/base/Gettext.h"
25 #include "zypp/ZYppCallbacks.h"
27 #include "zypp/Edition.h"
28 #include "zypp/Target.h"
29 #include "zypp/ZYppFactory.h"
31 #include "zypp/media/MediaAria2c.h"
32 #include "zypp/media/proxyinfo/ProxyInfos.h"
33 #include "zypp/media/ProxyInfo.h"
34 #include "zypp/media/MediaUserAuth.h"
35 #include "zypp/media/MediaCurl.h"
36 #include "zypp/thread/Once.h"
38 #include <sys/types.h>
40 #include <sys/mount.h>
44 #include <boost/format.hpp>
46 #define DETECT_DIR_INDEX 0
47 #define CONNECT_TIMEOUT 60
48 #define TRANSFER_TIMEOUT 60 * 3
49 #define TRANSFER_TIMEOUT_MAX 60 * 60
53 using namespace zypp::base;
60 Pathname MediaAria2c::_cookieFile = "/var/lib/YaST2/cookies";
61 Pathname MediaAria2c::_aria2cPath = "/usr/local/bin/aria2c";
62 std::string MediaAria2c::_aria2cVersion = "WE DON'T KNOW ARIA2C VERSION";
64 //check if aria2c is present in the system
66 MediaAria2c::existsAria2cmd()
75 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
77 for(std::string ariaResponse( aria.receiveLine());
78 ariaResponse.length();
79 ariaResponse = aria.receiveLine())
84 return ( aria.close() == 0 );
88 * comannd line for aria.
89 * The argument list gets passed as reference
92 void fillAriaCmdLine( const Pathname &ariapath,
93 const string &ariaver,
94 const TransferSettings &s,
96 const Pathname &destination,
97 ExternalProgram::Arguments &args )
99 args.push_back(ariapath.c_str());
100 args.push_back(str::form("--user-agent=%s", s.userAgentString().c_str()));
101 args.push_back("--summary-interval=1");
102 args.push_back("--follow-metalink=mem");
103 args.push_back("--check-integrity=true");
104 args.push_back("--file-allocation=none");
106 // only present in recent aria lets find out the aria version
107 vector<string> fields;
108 // "aria2c version x.x"
109 str::split( ariaver, std::back_inserter(fields));
110 if ( fields.size() == 3 )
112 if ( Edition(fields[2]) >= Edition("1.1.2") )
113 args.push_back( "--use-head=false");
116 if ( s.maxDownloadSpeed() > 0 )
117 args.push_back(str::form("--max-download-limit=%ld", s.maxDownloadSpeed()));
118 if ( s.minDownloadSpeed() > 0 )
119 args.push_back(str::form("--lowest-speed-limit=%ld", s.minDownloadSpeed()));
121 args.push_back(str::form("--max-tries=%ld", s.maxSilentTries()));
123 if ( Edition(fields[2]) < Edition("1.2.0") )
124 WAR << "aria2c is older than 1.2.0, some features may be disabled" << endl;
126 // TODO make this one configurable
127 args.push_back(str::form("--max-concurrent-downloads=%ld", s.maxConcurrentConnections()));
129 // add the anonymous id.
130 for ( TransferSettings::Headers::const_iterator it = s.headersBegin();
131 it != s.headersEnd();
133 args.push_back(str::form("--header=%s", it->c_str() ));
135 args.push_back( str::form("--connect-timeout=%ld", s.timeout()));
137 if ( s.username().empty() )
139 if ( url.getScheme() == "ftp" )
142 args.push_back(str::form("--ftp-user=%s", "suseuser" ));
143 args.push_back(str::form("--ftp-passwd=%s", VERSION ));
147 DBG << "Anonymous FTP identification: '" << id << "'" << endl;
152 if ( url.getScheme() == "ftp" )
153 args.push_back(str::form("--ftp-user=%s", s.username().c_str() ));
154 else if ( url.getScheme() == "http" ||
155 url.getScheme() == "https" )
156 args.push_back(str::form("--http-user=%s", s.username().c_str() ));
158 if ( s.password().size() )
160 if ( url.getScheme() == "ftp" )
161 args.push_back(str::form("--ftp-passwd=%s", s.password().c_str() ));
162 else if ( url.getScheme() == "http" ||
163 url.getScheme() == "https" )
164 args.push_back(str::form("--http-passwd=%s", s.password().c_str() ));
168 if ( s.proxyEnabled() )
170 args.push_back(str::form("--http-proxy=%s", s.proxy().c_str() ));
171 if ( ! s.proxyUsername().empty() )
173 args.push_back(str::form("--http-proxy-user=%s", s.proxyUsername().c_str() ));
174 if ( ! s.proxyPassword().empty() )
175 args.push_back(str::form("--http-proxy-passwd=%s", s.proxyPassword().c_str() ));
179 if ( ! destination.empty() )
180 args.push_back(str::form("--dir=%s", destination.c_str()));
182 args.push_back(url.asString().c_str());
185 const char *const MediaAria2c::agentString()
187 // we need to add the release and identifier to the
189 // The target could be not initialized, and then this information
191 Target_Ptr target = zypp::getZYpp()->getTarget();
193 static const std::string _value(
197 , MediaAria2c::_aria2cVersion.c_str()
198 , target ? target->targetDistribution().c_str() : ""
201 return _value.c_str();
206 MediaAria2c::MediaAria2c( const Url & url_r,
207 const Pathname & attach_point_hint_r )
208 : MediaCurl( url_r, attach_point_hint_r )
210 MIL << "MediaAria2c::MediaAria2c(" << url_r << ", " << attach_point_hint_r << ")" << endl;
212 //At this point, we initialize aria2c path
213 _aria2cPath = Pathname( whereisAria2c().asString() );
216 _aria2cVersion = getAria2cVersion();
219 void MediaAria2c::attachTo (bool next)
221 MediaCurl::attachTo(next);
222 _settings.setUserAgentString(agentString());
226 MediaAria2c::checkAttachPoint(const Pathname &apoint) const
228 return MediaCurl::checkAttachPoint( apoint );
231 void MediaAria2c::disconnectFrom()
233 MediaCurl::disconnectFrom();
236 void MediaAria2c::releaseFrom( const std::string & ejectDev )
238 MediaCurl::releaseFrom(ejectDev);
241 static Url getFileUrl(const Url & url, const Pathname & filename)
244 string path = url.getPathName();
245 if ( !path.empty() && path != "/" && *path.rbegin() == '/' &&
246 filename.absolute() )
248 // If url has a path with trailing slash, remove the leading slash from
249 // the absolute file name
250 path += filename.asString().substr( 1, filename.asString().size() - 1 );
252 else if ( filename.relative() )
254 // Add trailing slash to path, if not already there
255 if (path.empty()) path = "/";
256 else if (*path.rbegin() != '/' ) path += "/";
257 // Remove "./" from begin of relative file name
258 path += filename.asString().substr( 2, filename.asString().size() - 2 );
262 path += filename.asString();
265 newurl.setPathName(path);
269 void MediaAria2c::getFile( const Pathname & filename ) const
271 // Use absolute file name to prevent access of files outside of the
272 // hierarchy below the attach point.
273 getFileCopy(filename, localPath(filename).absolutename());
276 void MediaAria2c::getFileCopy( const Pathname & filename , const Pathname & target) const
278 callback::SendReport<DownloadProgressReport> report;
280 Url fileurl(getFileUrl(_url, filename));
284 ExternalProgram::Arguments args;
286 fillAriaCmdLine(_aria2cPath, _aria2cVersion, _settings, fileurl, target.dirname(), args);
292 report->start(_url, target.asString() );
294 ExternalProgram aria(args, ExternalProgram::Stderr_To_Stdout);
296 // progress line like: [#1 SIZE:8.3MiB/10.1MiB(82%) CN:5 SPD:6899.88KiB/s]
297 // we save it until we find a string with FILE: later
299 // file line, which tell which file is the previous progress
300 // ie: FILE: ./packages.FL.gz
301 double average_speed = 0;
302 long average_speed_count = 0;
305 for(std::string ariaResponse( aria.receiveLine());
306 ariaResponse.length();
307 ariaResponse = aria.receiveLine())
309 //cout << ariaResponse;
310 string line = str::trim(ariaResponse);
312 if (!line.substr(0,31).compare("Exception: Authorization failed") )
314 ZYPP_THROW(MediaUnauthorizedException(
315 _url, "Login failed.", "Login failed", "auth hint"
318 if (!line.substr(0,29).compare("Exception: Resource not found") )
320 ZYPP_THROW(MediaFileNotFoundException(_url, filename));
323 // look for the progress line and save it for later
324 if ( str::hasPrefix(line, "[#") )
327 if ( str::hasPrefix(line, "FILE: ") )
330 Pathname theFile(line.substr(6, line.size()));
331 // is the report about the filename we are downloading?
332 // aria may report progress about metalinks, torrent and
333 // other stuff which is not the main transfer
334 if ( theFile == target )
336 // once we find the FILE: line, progress has to be
338 if ( ! progressLine.empty() )
340 // get the percentage (progress) data
342 size_t left_bound = progressLine.find('(',0) + 1;
343 size_t count = progressLine.find('%',left_bound) - left_bound;
344 string progressStr = progressLine.substr(left_bound, count);
346 if ( count != string::npos )
347 progress = std::atoi(progressStr.c_str());
349 ERR << "Can't parse progress from '" << progressStr << "'" << endl;
351 double current_speed = 0;
352 left_bound = progressLine.find("SPD:",0) + 4;
353 count = progressLine.find("KiB/s",left_bound) - left_bound;
354 if ( count != string::npos )
355 { // convert the string to a double
356 string speedStr = progressLine.substr(left_bound, count);
358 current_speed = boost::lexical_cast<double>(speedStr);
360 catch (const std::exception&) {
361 ERR << "Can't parse speed from '" << speedStr << "'" << endl;
366 // we have a new average speed
367 average_speed_count++;
369 // this is basically A: average
370 // ((n-1)A(n-1) + Xn)/n = A(n)
371 average_speed = (((average_speed_count - 1 )*average_speed) + current_speed)/average_speed_count;
373 report->progress ( progress, _url, average_speed, current_speed );
374 // clear the progress line to detect mismatches between
375 // [# and FILE: lines
376 progressLine.clear();
380 WAR << "aria2c reported a file, but no progress data available" << endl;
386 DBG << "Progress is not about '" << target << "' but '" << theFile << "'" << endl;
393 report->finish( _url , zypp::media::DownloadProgressReport::NO_ERROR, "");
397 // retry with proper authentication data
398 catch (MediaUnauthorizedException & ex_r)
400 if(authenticate(ex_r.hint(), !retry))
404 report->finish(fileurl, zypp::media::DownloadProgressReport::ACCESS_DENIED, ex_r.asUserHistory());
409 // unexpected exception
410 catch (MediaException & excpt_r)
412 // FIXME: error number fix
413 report->finish(fileurl, zypp::media::DownloadProgressReport::ERROR, excpt_r.asUserHistory());
414 ZYPP_RETHROW(excpt_r);
419 report->finish(fileurl, zypp::media::DownloadProgressReport::NO_ERROR, "");
422 bool MediaAria2c::getDoesFileExist( const Pathname & filename ) const
424 return MediaCurl::getDoesFileExist(filename);
427 bool MediaAria2c::doGetDoesFileExist( const Pathname & filename ) const
429 return MediaCurl::doGetDoesFileExist(filename);
432 void MediaAria2c::getDir( const Pathname & dirname, bool recurse_r ) const
434 MediaCurl::getDir(dirname, recurse_r);
437 bool MediaAria2c::authenticate(const std::string & availAuthTypes, bool firstTry) const
443 void MediaAria2c::getDirInfo( std::list<std::string> & retlist,
444 const Pathname & dirname, bool dots ) const
446 getDirectoryYast( retlist, dirname, dots );
449 void MediaAria2c::getDirInfo( filesystem::DirContent & retlist,
450 const Pathname & dirname, bool dots ) const
452 getDirectoryYast( retlist, dirname, dots );
455 std::string MediaAria2c::getAria2cVersion()
464 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
466 std::string vResponse = aria.receiveLine();
468 return str::trim(vResponse);
471 #define ARIA_DEFAULT_BINARY "/usr/bin/aria2c"
473 Pathname MediaAria2c::whereisAria2c()
475 Pathname aria2cPathr(ARIA_DEFAULT_BINARY);
484 ExternalProgram aria(argv, ExternalProgram::Stderr_To_Stdout);
486 std::string ariaResponse( aria.receiveLine());
487 int code = aria.close();
491 aria2cPathr = str::trim(ariaResponse);
492 MIL << "We will use aria2c located here: " << aria2cPathr << endl;
496 MIL << "We don't know were is ari2ac binary. We will use aria2c located here: " << aria2cPathr << endl;