RpcMethodImpl.cc 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2009 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "RpcMethodImpl.h"
  36. #include <cassert>
  37. #include <algorithm>
  38. #include <sstream>
  39. #include "Logger.h"
  40. #include "LogFactory.h"
  41. #include "DlAbortEx.h"
  42. #include "Option.h"
  43. #include "OptionParser.h"
  44. #include "OptionHandler.h"
  45. #include "DownloadEngine.h"
  46. #include "RequestGroup.h"
  47. #include "download_helper.h"
  48. #include "util.h"
  49. #include "fmt.h"
  50. #include "RpcRequest.h"
  51. #include "PieceStorage.h"
  52. #include "DownloadContext.h"
  53. #include "DiskAdaptor.h"
  54. #include "FileEntry.h"
  55. #include "prefs.h"
  56. #include "message.h"
  57. #include "FeatureConfig.h"
  58. #include "array_fun.h"
  59. #include "RpcMethodFactory.h"
  60. #include "RpcResponse.h"
  61. #include "SegmentMan.h"
  62. #include "TimedHaltCommand.h"
  63. #include "PeerStat.h"
  64. #include "base64.h"
  65. #include "BitfieldMan.h"
  66. #ifdef ENABLE_MESSAGE_DIGEST
  67. # include "MessageDigest.h"
  68. # include "message_digest_helper.h"
  69. #endif // ENABLE_MESSAGE_DIGEST
  70. #ifdef ENABLE_BITTORRENT
  71. # include "bittorrent_helper.h"
  72. # include "BtRegistry.h"
  73. # include "PeerStorage.h"
  74. # include "Peer.h"
  75. # include "BtRuntime.h"
  76. # include "BtAnnounce.h"
  77. #endif // ENABLE_BITTORRENT
  78. namespace aria2 {
  79. namespace rpc {
  80. namespace {
  81. const SharedHandle<String> VLB_TRUE = String::g("true");
  82. const SharedHandle<String> VLB_FALSE = String::g("false");
  83. const SharedHandle<String> VLB_OK = String::g("OK");
  84. const SharedHandle<String> VLB_ACTIVE = String::g("active");
  85. const SharedHandle<String> VLB_WAITING = String::g("waiting");
  86. const SharedHandle<String> VLB_PAUSED = String::g("paused");
  87. const SharedHandle<String> VLB_REMOVED = String::g("removed");
  88. const SharedHandle<String> VLB_ERROR = String::g("error");
  89. const SharedHandle<String> VLB_COMPLETE = String::g("complete");
  90. const SharedHandle<String> VLB_USED = String::g("used");
  91. const SharedHandle<String> VLB_ZERO = String::g("0");
  92. const std::string KEY_GID = "gid";
  93. const std::string KEY_ERROR_CODE = "errorCode";
  94. const std::string KEY_STATUS = "status";
  95. const std::string KEY_TOTAL_LENGTH = "totalLength";
  96. const std::string KEY_COMPLETED_LENGTH = "completedLength";
  97. const std::string KEY_DOWNLOAD_SPEED = "downloadSpeed";
  98. const std::string KEY_UPLOAD_SPEED = "uploadSpeed";
  99. const std::string KEY_UPLOAD_LENGTH = "uploadLength";
  100. const std::string KEY_CONNECTIONS = "connections";
  101. const std::string KEY_BITFIELD = "bitfield";
  102. const std::string KEY_PIECE_LENGTH = "pieceLength";
  103. const std::string KEY_NUM_PIECES = "numPieces";
  104. const std::string KEY_FOLLOWED_BY = "followedBy";
  105. const std::string KEY_BELONGS_TO = "belongsTo";
  106. const std::string KEY_INFO_HASH = "infoHash";
  107. const std::string KEY_NUM_SEEDERS = "numSeeders";
  108. const std::string KEY_PEER_ID = "peerId";
  109. const std::string KEY_IP = "ip";
  110. const std::string KEY_PORT = "port";
  111. const std::string KEY_AM_CHOKING = "amChoking";
  112. const std::string KEY_PEER_CHOKING = "peerChoking";
  113. const std::string KEY_SEEDER = "seeder";
  114. const std::string KEY_INDEX = "index";
  115. const std::string KEY_PATH = "path";
  116. const std::string KEY_SELECTED = "selected";
  117. const std::string KEY_LENGTH = "length";
  118. const std::string KEY_URI = "uri";
  119. const std::string KEY_CURRENT_URI = "currentUri";
  120. const std::string KEY_VERSION = "version";
  121. const std::string KEY_ENABLED_FEATURES = "enabledFeatures";
  122. const std::string KEY_METHOD_NAME = "methodName";
  123. const std::string KEY_PARAMS = "params";
  124. const std::string KEY_SESSION_ID = "sessionId";
  125. const std::string KEY_FILES = "files";
  126. const std::string KEY_DIR = "dir";
  127. const std::string KEY_URIS = "uris";
  128. const std::string KEY_BITTORRENT = "bittorrent";
  129. const std::string KEY_INFO = "info";
  130. const std::string KEY_NAME = "name";
  131. const std::string KEY_ANNOUNCE_LIST = "announceList";
  132. const std::string KEY_COMMENT = "comment";
  133. const std::string KEY_CREATION_DATE = "creationDate";
  134. const std::string KEY_MODE = "mode";
  135. const std::string KEY_SERVERS = "servers";
  136. const std::string KEY_NUM_WAITING = "numWaiting";
  137. const std::string KEY_NUM_STOPPED = "numStopped";
  138. const std::string KEY_NUM_ACTIVE = "numActive";
  139. } // namespace
  140. namespace {
  141. SharedHandle<ValueBase> createGIDResponse(a2_gid_t gid)
  142. {
  143. return String::g(GroupId::toHex(gid));
  144. }
  145. } // namespace
  146. namespace {
  147. SharedHandle<ValueBase>
  148. addRequestGroup(const SharedHandle<RequestGroup>& group,
  149. DownloadEngine* e,
  150. bool posGiven, int pos)
  151. {
  152. if(posGiven) {
  153. e->getRequestGroupMan()->insertReservedGroup(pos, group);
  154. } else {
  155. e->getRequestGroupMan()->addReservedGroup(group);
  156. }
  157. return createGIDResponse(group->getGID());
  158. }
  159. } // namespace
  160. namespace {
  161. bool checkPosParam(const Integer* posParam)
  162. {
  163. if(posParam) {
  164. if(posParam->i() >= 0) {
  165. return true;
  166. } else {
  167. throw DL_ABORT_EX("Position must be greater than or equal to 0.");
  168. }
  169. }
  170. return false;
  171. }
  172. } // namespace
  173. namespace {
  174. a2_gid_t str2Gid(const String* str)
  175. {
  176. assert(str);
  177. if(str->s().size() > sizeof(a2_gid_t)*2) {
  178. throw DL_ABORT_EX(fmt("Invalid GID %s", str->s().c_str()));
  179. }
  180. a2_gid_t n;
  181. switch(GroupId::expandUnique(n, str->s().c_str())) {
  182. case GroupId::ERR_NOT_UNIQUE:
  183. throw DL_ABORT_EX(fmt("GID %s is not unique", str->s().c_str()));
  184. case GroupId::ERR_NOT_FOUND:
  185. throw DL_ABORT_EX(fmt("GID %s is not found", str->s().c_str()));
  186. case GroupId::ERR_INVALID:
  187. throw DL_ABORT_EX(fmt("Invalid GID %s", str->s().c_str()));
  188. }
  189. return n;
  190. }
  191. } // namespace
  192. namespace {
  193. template<typename OutputIterator>
  194. void extractUris(OutputIterator out, const List* src)
  195. {
  196. if(src) {
  197. for(List::ValueType::const_iterator i = src->begin(), eoi = src->end();
  198. i != eoi; ++i) {
  199. const String* uri = downcast<String>(*i);
  200. if(uri) {
  201. out++ = uri->s();
  202. }
  203. }
  204. }
  205. }
  206. } // namespace
  207. SharedHandle<ValueBase> AddUriRpcMethod::process
  208. (const RpcRequest& req, DownloadEngine* e)
  209. {
  210. const List* urisParam = checkRequiredParam<List>(req, 0);
  211. const Dict* optsParam = checkParam<Dict>(req, 1);
  212. const Integer* posParam = checkParam<Integer>(req, 2);
  213. std::vector<std::string> uris;
  214. extractUris(std::back_inserter(uris), urisParam);
  215. if(uris.empty()) {
  216. throw DL_ABORT_EX("URI is not provided.");
  217. }
  218. SharedHandle<Option> requestOption(new Option(*e->getOption()));
  219. gatherRequestOption(requestOption.get(), optsParam);
  220. bool posGiven = checkPosParam(posParam);
  221. size_t pos = posGiven ? posParam->i() : 0;
  222. std::vector<SharedHandle<RequestGroup> > result;
  223. createRequestGroupForUri(result, requestOption, uris,
  224. /* ignoreForceSeq = */ true,
  225. /* ignoreLocalPath = */ true);
  226. if(!result.empty()) {
  227. return addRequestGroup(result.front(), e, posGiven, pos);
  228. } else {
  229. throw DL_ABORT_EX("No URI to download.");
  230. }
  231. }
  232. #ifdef ENABLE_MESSAGE_DIGEST
  233. namespace {
  234. std::string getHexSha1(const std::string& s)
  235. {
  236. unsigned char hash[20];
  237. message_digest::digest(hash, sizeof(hash), MessageDigest::sha1(),
  238. s.data(), s.size());
  239. return util::toHex(hash, sizeof(hash));
  240. }
  241. } // namespace
  242. #endif // ENABLE_MESSAGE_DIGEST
  243. #ifdef ENABLE_BITTORRENT
  244. SharedHandle<ValueBase> AddTorrentRpcMethod::process
  245. (const RpcRequest& req, DownloadEngine* e)
  246. {
  247. const String* torrentParam = checkRequiredParam<String>(req, 0);
  248. const List* urisParam = checkParam<List>(req, 1);
  249. const Dict* optsParam = checkParam<Dict>(req, 2);
  250. const Integer* posParam = checkParam<Integer>(req, 3);
  251. SharedHandle<String> tempTorrentParam;
  252. if(req.jsonRpc) {
  253. tempTorrentParam = String::g
  254. (base64::decode(torrentParam->s().begin(),
  255. torrentParam->s().end()));
  256. torrentParam = tempTorrentParam.get();
  257. }
  258. std::vector<std::string> uris;
  259. extractUris(std::back_inserter(uris), urisParam);
  260. SharedHandle<Option> requestOption(new Option(*e->getOption()));
  261. gatherRequestOption(requestOption.get(), optsParam);
  262. bool posGiven = checkPosParam(posParam);
  263. size_t pos = posGiven ? posParam->i() : 0;
  264. std::string filename;
  265. if(requestOption->getAsBool(PREF_RPC_SAVE_UPLOAD_METADATA)) {
  266. filename = util::applyDir
  267. (requestOption->get(PREF_DIR), getHexSha1(torrentParam->s())+".torrent");
  268. // Save uploaded data in order to save this download in
  269. // --save-session file.
  270. if(util::saveAs(filename, torrentParam->s(), true)) {
  271. A2_LOG_INFO(fmt("Uploaded torrent data was saved as %s",
  272. filename.c_str()));
  273. requestOption->put(PREF_TORRENT_FILE, filename);
  274. } else {
  275. A2_LOG_INFO(fmt("Uploaded torrent data was not saved."
  276. " Failed to write file %s", filename.c_str()));
  277. filename.clear();
  278. }
  279. }
  280. std::vector<SharedHandle<RequestGroup> > result;
  281. createRequestGroupForBitTorrent(result, requestOption, uris, filename,
  282. torrentParam->s());
  283. if(!result.empty()) {
  284. return addRequestGroup(result.front(), e, posGiven, pos);
  285. } else {
  286. throw DL_ABORT_EX("No Torrent to download.");
  287. }
  288. }
  289. #endif // ENABLE_BITTORRENT
  290. #ifdef ENABLE_METALINK
  291. SharedHandle<ValueBase> AddMetalinkRpcMethod::process
  292. (const RpcRequest& req, DownloadEngine* e)
  293. {
  294. const String* metalinkParam = checkRequiredParam<String>(req, 0);
  295. const Dict* optsParam = checkParam<Dict>(req, 1);
  296. const Integer* posParam = checkParam<Integer>(req, 2);
  297. SharedHandle<String> tempMetalinkParam;
  298. if(req.jsonRpc) {
  299. tempMetalinkParam = String::g
  300. (base64::decode(metalinkParam->s().begin(),
  301. metalinkParam->s().end()));
  302. metalinkParam = tempMetalinkParam.get();
  303. }
  304. SharedHandle<Option> requestOption(new Option(*e->getOption()));
  305. gatherRequestOption(requestOption.get(), optsParam);
  306. bool posGiven = checkPosParam(posParam);
  307. size_t pos = posGiven ? posParam->i() : 0;
  308. std::vector<SharedHandle<RequestGroup> > result;
  309. #ifdef ENABLE_MESSAGE_DIGEST
  310. std::string filename;
  311. if(requestOption->getAsBool(PREF_RPC_SAVE_UPLOAD_METADATA)) {
  312. // TODO RFC5854 Metalink has the extension .meta4 and Metalink
  313. // Version 3 uses .metalink extension. We use .meta4 for both
  314. // RFC5854 Metalink and Version 3. aria2 can detect which of which
  315. // by reading content rather than extension.
  316. filename = util::applyDir
  317. (requestOption->get(PREF_DIR), getHexSha1(metalinkParam->s())+".meta4");
  318. // Save uploaded data in order to save this download in
  319. // --save-session file.
  320. if(util::saveAs(filename, metalinkParam->s(), true)) {
  321. A2_LOG_INFO(fmt("Uploaded metalink data was saved as %s",
  322. filename.c_str()));
  323. requestOption->put(PREF_METALINK_FILE, filename);
  324. createRequestGroupForMetalink(result, requestOption);
  325. } else {
  326. A2_LOG_INFO(fmt("Uploaded metalink data was not saved."
  327. " Failed to write file %s", filename.c_str()));
  328. createRequestGroupForMetalink(result, requestOption, metalinkParam->s());
  329. }
  330. } else {
  331. createRequestGroupForMetalink(result, requestOption, metalinkParam->s());
  332. }
  333. #else // !ENABLE_MESSAGE_DIGEST
  334. createRequestGroupForMetalink(result, requestOption, metalinkParam->s());
  335. #endif // !ENABLE_MESSAGE_DIGEST
  336. SharedHandle<List> gids = List::g();
  337. if(!result.empty()) {
  338. if(posGiven) {
  339. e->getRequestGroupMan()->insertReservedGroup(pos, result);
  340. } else {
  341. e->getRequestGroupMan()->addReservedGroup(result);
  342. }
  343. for(std::vector<SharedHandle<RequestGroup> >::const_iterator i =
  344. result.begin(), eoi = result.end(); i != eoi; ++i) {
  345. gids->append(GroupId::toHex((*i)->getGID()));
  346. }
  347. }
  348. return gids;
  349. }
  350. #endif // ENABLE_METALINK
  351. namespace {
  352. SharedHandle<ValueBase> removeDownload
  353. (const RpcRequest& req, DownloadEngine* e, bool forceRemove)
  354. {
  355. const String* gidParam = checkRequiredParam<String>(req, 0);
  356. a2_gid_t gid = str2Gid(gidParam);
  357. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  358. if(group) {
  359. if(group->getState() == RequestGroup::STATE_ACTIVE) {
  360. if(forceRemove) {
  361. group->setForceHaltRequested(true, RequestGroup::USER_REQUEST);
  362. } else {
  363. group->setHaltRequested(true, RequestGroup::USER_REQUEST);
  364. }
  365. e->setRefreshInterval(0);
  366. } else {
  367. if(group->isDependencyResolved()) {
  368. e->getRequestGroupMan()->removeReservedGroup(gid);
  369. } else {
  370. throw DL_ABORT_EX(fmt("GID#%s cannot be removed now",
  371. GroupId::toHex(gid).c_str()));
  372. }
  373. }
  374. } else {
  375. throw DL_ABORT_EX(fmt("Active Download not found for GID#%s",
  376. GroupId::toHex(gid).c_str()));
  377. }
  378. return createGIDResponse(gid);
  379. }
  380. } // namespace
  381. SharedHandle<ValueBase> RemoveRpcMethod::process
  382. (const RpcRequest& req, DownloadEngine* e)
  383. {
  384. return removeDownload(req, e, false);
  385. }
  386. SharedHandle<ValueBase> ForceRemoveRpcMethod::process
  387. (const RpcRequest& req, DownloadEngine* e)
  388. {
  389. return removeDownload(req, e, true);
  390. }
  391. namespace {
  392. SharedHandle<ValueBase> pauseDownload
  393. (const RpcRequest& req, DownloadEngine* e, bool forcePause)
  394. {
  395. const String* gidParam = checkRequiredParam<String>(req, 0);
  396. a2_gid_t gid = str2Gid(gidParam);
  397. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  398. if(group) {
  399. bool reserved = group->getState() == RequestGroup::STATE_WAITING;
  400. if(pauseRequestGroup(group, reserved, forcePause)) {
  401. e->setRefreshInterval(0);
  402. return createGIDResponse(gid);
  403. }
  404. }
  405. throw DL_ABORT_EX(fmt("GID#%s cannot be paused now",
  406. GroupId::toHex(gid).c_str()));
  407. }
  408. } // namespace
  409. SharedHandle<ValueBase> PauseRpcMethod::process
  410. (const RpcRequest& req, DownloadEngine* e)
  411. {
  412. return pauseDownload(req, e, false);
  413. }
  414. SharedHandle<ValueBase> ForcePauseRpcMethod::process
  415. (const RpcRequest& req, DownloadEngine* e)
  416. {
  417. return pauseDownload(req, e, true);
  418. }
  419. namespace {
  420. template<typename InputIterator>
  421. void pauseRequestGroups
  422. (InputIterator first, InputIterator last, bool reserved, bool forcePause)
  423. {
  424. for(; first != last; ++first) {
  425. pauseRequestGroup(*first, reserved, forcePause);
  426. }
  427. }
  428. } // namespace
  429. namespace {
  430. SharedHandle<ValueBase> pauseAllDownloads
  431. (const RpcRequest& req, DownloadEngine* e, bool forcePause)
  432. {
  433. const RequestGroupList& groups = e->getRequestGroupMan()->getRequestGroups();
  434. pauseRequestGroups(groups.begin(), groups.end(), false, forcePause);
  435. const RequestGroupList& reservedGroups =
  436. e->getRequestGroupMan()->getReservedGroups();
  437. pauseRequestGroups(reservedGroups.begin(), reservedGroups.end(),
  438. true, forcePause);
  439. return VLB_OK;
  440. }
  441. } // namespace
  442. SharedHandle<ValueBase> PauseAllRpcMethod::process
  443. (const RpcRequest& req, DownloadEngine* e)
  444. {
  445. return pauseAllDownloads(req, e, false);
  446. }
  447. SharedHandle<ValueBase> ForcePauseAllRpcMethod::process
  448. (const RpcRequest& req, DownloadEngine* e)
  449. {
  450. return pauseAllDownloads(req, e, true);
  451. }
  452. SharedHandle<ValueBase> UnpauseRpcMethod::process
  453. (const RpcRequest& req, DownloadEngine* e)
  454. {
  455. const String* gidParam = checkRequiredParam<String>(req, 0);
  456. a2_gid_t gid = str2Gid(gidParam);
  457. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  458. if(!group ||
  459. group->getState() != RequestGroup::STATE_WAITING ||
  460. !group->isPauseRequested()) {
  461. throw DL_ABORT_EX(fmt("GID#%s cannot be unpaused now",
  462. GroupId::toHex(gid).c_str()));
  463. } else {
  464. group->setPauseRequested(false);
  465. e->getRequestGroupMan()->requestQueueCheck();
  466. }
  467. return createGIDResponse(gid);
  468. }
  469. SharedHandle<ValueBase> UnpauseAllRpcMethod::process
  470. (const RpcRequest& req, DownloadEngine* e)
  471. {
  472. const RequestGroupList& groups =
  473. e->getRequestGroupMan()->getReservedGroups();
  474. for(RequestGroupList::const_iterator i = groups.begin(),
  475. eoi = groups.end(); i != eoi; ++i) {
  476. (*i)->setPauseRequested(false);
  477. }
  478. e->getRequestGroupMan()->requestQueueCheck();
  479. return VLB_OK;
  480. }
  481. namespace {
  482. template<typename InputIterator>
  483. void createUriEntry
  484. (const SharedHandle<List>& uriList,
  485. InputIterator first, InputIterator last,
  486. const SharedHandle<String>& status)
  487. {
  488. for(; first != last; ++first) {
  489. SharedHandle<Dict> entry = Dict::g();
  490. entry->put(KEY_URI, *first);
  491. entry->put(KEY_STATUS, status);
  492. uriList->append(entry);
  493. }
  494. }
  495. } // namespace
  496. namespace {
  497. void createUriEntry
  498. (const SharedHandle<List>& uriList, const SharedHandle<FileEntry>& file)
  499. {
  500. createUriEntry(uriList,
  501. file->getSpentUris().begin(),
  502. file->getSpentUris().end(),
  503. VLB_USED);
  504. createUriEntry(uriList,
  505. file->getRemainingUris().begin(),
  506. file->getRemainingUris().end(),
  507. VLB_WAITING);
  508. }
  509. } // namespace
  510. namespace {
  511. template<typename InputIterator>
  512. void createFileEntry
  513. (const SharedHandle<List>& files,
  514. InputIterator first, InputIterator last,
  515. const BitfieldMan* bf)
  516. {
  517. size_t index = 1;
  518. for(; first != last; ++first, ++index) {
  519. SharedHandle<Dict> entry = Dict::g();
  520. entry->put(KEY_INDEX, util::uitos(index));
  521. entry->put(KEY_PATH, (*first)->getPath());
  522. entry->put(KEY_SELECTED, (*first)->isRequested()?VLB_TRUE:VLB_FALSE);
  523. entry->put(KEY_LENGTH, util::itos((*first)->getLength()));
  524. int64_t completedLength = bf->getOffsetCompletedLength
  525. ((*first)->getOffset(), (*first)->getLength());
  526. entry->put(KEY_COMPLETED_LENGTH, util::itos(completedLength));
  527. SharedHandle<List> uriList = List::g();
  528. createUriEntry(uriList, *first);
  529. entry->put(KEY_URIS, uriList);
  530. files->append(entry);
  531. }
  532. }
  533. } // namespace
  534. namespace {
  535. template<typename InputIterator>
  536. void createFileEntry
  537. (const SharedHandle<List>& files,
  538. InputIterator first, InputIterator last,
  539. int64_t totalLength,
  540. int32_t pieceLength,
  541. const std::string& bitfield)
  542. {
  543. BitfieldMan bf(pieceLength, totalLength);
  544. bf.setBitfield(reinterpret_cast<const unsigned char*>(bitfield.data()),
  545. bitfield.size());
  546. createFileEntry(files, first, last, &bf);
  547. }
  548. } // namespace
  549. namespace {
  550. template<typename InputIterator>
  551. void createFileEntry
  552. (const SharedHandle<List>& files,
  553. InputIterator first, InputIterator last,
  554. int64_t totalLength,
  555. int32_t pieceLength,
  556. const SharedHandle<PieceStorage>& ps)
  557. {
  558. BitfieldMan bf(pieceLength, totalLength);
  559. if(ps) {
  560. bf.setBitfield(ps->getBitfield(), ps->getBitfieldLength());
  561. }
  562. createFileEntry(files, first, last, &bf);
  563. }
  564. } // namespace
  565. namespace {
  566. bool requested_key
  567. (const std::vector<std::string>& keys, const std::string& k)
  568. {
  569. return keys.empty() || std::find(keys.begin(), keys.end(), k) != keys.end();
  570. }
  571. } // namespace
  572. void gatherProgressCommon
  573. (const SharedHandle<Dict>& entryDict,
  574. const SharedHandle<RequestGroup>& group,
  575. const std::vector<std::string>& keys)
  576. {
  577. const SharedHandle<PieceStorage>& ps = group->getPieceStorage();
  578. if(requested_key(keys, KEY_GID)) {
  579. entryDict->put(KEY_GID, GroupId::toHex(group->getGID()).c_str());
  580. }
  581. if(requested_key(keys, KEY_TOTAL_LENGTH)) {
  582. // This is "filtered" total length if --select-file is used.
  583. entryDict->put(KEY_TOTAL_LENGTH, util::itos(group->getTotalLength()));
  584. }
  585. if(requested_key(keys, KEY_COMPLETED_LENGTH)) {
  586. // This is "filtered" total length if --select-file is used.
  587. entryDict->put
  588. (KEY_COMPLETED_LENGTH,util::itos(group->getCompletedLength()));
  589. }
  590. TransferStat stat = group->calculateStat();
  591. if(requested_key(keys, KEY_DOWNLOAD_SPEED)) {
  592. entryDict->put(KEY_DOWNLOAD_SPEED, util::itos(stat.downloadSpeed));
  593. }
  594. if(requested_key(keys, KEY_UPLOAD_SPEED)) {
  595. entryDict->put(KEY_UPLOAD_SPEED, util::itos(stat.uploadSpeed));
  596. }
  597. if(requested_key(keys, KEY_UPLOAD_LENGTH)) {
  598. entryDict->put
  599. (KEY_UPLOAD_LENGTH, util::itos(stat.allTimeUploadLength));
  600. }
  601. if(requested_key(keys, KEY_CONNECTIONS)) {
  602. entryDict->put(KEY_CONNECTIONS, util::itos(group->getNumConnection()));
  603. }
  604. if(requested_key(keys, KEY_BITFIELD)) {
  605. if(ps) {
  606. if(ps->getBitfieldLength() > 0) {
  607. entryDict->put(KEY_BITFIELD,
  608. util::toHex(ps->getBitfield(), ps->getBitfieldLength()));
  609. }
  610. }
  611. }
  612. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  613. if(requested_key(keys, KEY_PIECE_LENGTH)) {
  614. entryDict->put(KEY_PIECE_LENGTH, util::itos(dctx->getPieceLength()));
  615. }
  616. if(requested_key(keys, KEY_NUM_PIECES)) {
  617. entryDict->put(KEY_NUM_PIECES, util::uitos(dctx->getNumPieces()));
  618. }
  619. if(requested_key(keys, KEY_FOLLOWED_BY)) {
  620. if(!group->followedBy().empty()) {
  621. SharedHandle<List> list = List::g();
  622. // The element is GID.
  623. for(std::vector<a2_gid_t>::const_iterator i = group->followedBy().begin(),
  624. eoi = group->followedBy().end(); i != eoi; ++i) {
  625. list->append(GroupId::toHex(*i));
  626. }
  627. entryDict->put(KEY_FOLLOWED_BY, list);
  628. }
  629. }
  630. if(requested_key(keys, KEY_BELONGS_TO)) {
  631. if(group->belongsTo()) {
  632. entryDict->put(KEY_BELONGS_TO, GroupId::toHex(group->belongsTo()));
  633. }
  634. }
  635. if(requested_key(keys, KEY_FILES)) {
  636. SharedHandle<List> files = List::g();
  637. createFileEntry
  638. (files, dctx->getFileEntries().begin(), dctx->getFileEntries().end(),
  639. dctx->getTotalLength(), dctx->getPieceLength(), ps);
  640. entryDict->put(KEY_FILES, files);
  641. }
  642. if(requested_key(keys, KEY_DIR)) {
  643. entryDict->put(KEY_DIR, group->getOption()->get(PREF_DIR));
  644. }
  645. }
  646. #ifdef ENABLE_BITTORRENT
  647. void gatherBitTorrentMetadata
  648. (const SharedHandle<Dict>& btDict,
  649. const SharedHandle<TorrentAttribute>& torrentAttrs)
  650. {
  651. if(!torrentAttrs->comment.empty()) {
  652. btDict->put(KEY_COMMENT, torrentAttrs->comment);
  653. }
  654. if(torrentAttrs->creationDate) {
  655. btDict->put(KEY_CREATION_DATE, Integer::g(torrentAttrs->creationDate));
  656. }
  657. if(!torrentAttrs->mode.empty()) {
  658. btDict->put(KEY_MODE, torrentAttrs->mode);
  659. }
  660. SharedHandle<List> destAnnounceList = List::g();
  661. for(std::vector<std::vector<std::string> >::const_iterator l =
  662. torrentAttrs->announceList.begin(),
  663. eoi = torrentAttrs->announceList.end(); l != eoi; ++l) {
  664. SharedHandle<List> destAnnounceTier = List::g();
  665. for(std::vector<std::string>::const_iterator t = (*l).begin(),
  666. eoi2 = (*l).end(); t != eoi2; ++t) {
  667. destAnnounceTier->append(*t);
  668. }
  669. destAnnounceList->append(destAnnounceTier);
  670. }
  671. btDict->put(KEY_ANNOUNCE_LIST, destAnnounceList);
  672. if(!torrentAttrs->metadata.empty()) {
  673. SharedHandle<Dict> infoDict = Dict::g();
  674. infoDict->put(KEY_NAME, torrentAttrs->name);
  675. btDict->put(KEY_INFO, infoDict);
  676. }
  677. }
  678. namespace {
  679. void gatherProgressBitTorrent
  680. (const SharedHandle<Dict>& entryDict,
  681. const SharedHandle<TorrentAttribute>& torrentAttrs,
  682. const SharedHandle<BtObject>& btObject,
  683. const std::vector<std::string>& keys)
  684. {
  685. if(requested_key(keys, KEY_INFO_HASH)) {
  686. entryDict->put(KEY_INFO_HASH, util::toHex(torrentAttrs->infoHash));
  687. }
  688. if(requested_key(keys, KEY_BITTORRENT)) {
  689. SharedHandle<Dict> btDict = Dict::g();
  690. gatherBitTorrentMetadata(btDict, torrentAttrs);
  691. entryDict->put(KEY_BITTORRENT, btDict);
  692. }
  693. if(requested_key(keys, KEY_NUM_SEEDERS)) {
  694. if(!btObject) {
  695. entryDict->put(KEY_NUM_SEEDERS, VLB_ZERO);
  696. } else {
  697. const SharedHandle<PeerStorage>& peerStorage = btObject->peerStorage;
  698. assert(peerStorage);
  699. const PeerSet& peers = peerStorage->getUsedPeers();
  700. entryDict->put(KEY_NUM_SEEDERS,
  701. util::uitos(countSeeder(peers.begin(), peers.end())));
  702. }
  703. }
  704. }
  705. } // namespace
  706. namespace {
  707. void gatherPeer
  708. (const SharedHandle<List>& peers, const SharedHandle<PeerStorage>& ps)
  709. {
  710. const PeerSet& usedPeers = ps->getUsedPeers();
  711. for(PeerSet::const_iterator i = usedPeers.begin(), eoi = usedPeers.end();
  712. i != eoi; ++i) {
  713. if(!(*i)->isActive()) {
  714. continue;
  715. }
  716. SharedHandle<Dict> peerEntry = Dict::g();
  717. peerEntry->put(KEY_PEER_ID, util::torrentPercentEncode((*i)->getPeerId(),
  718. PEER_ID_LENGTH));
  719. peerEntry->put(KEY_IP, (*i)->getIPAddress());
  720. if((*i)->isIncomingPeer()) {
  721. peerEntry->put(KEY_PORT, VLB_ZERO);
  722. } else {
  723. peerEntry->put(KEY_PORT, util::uitos((*i)->getPort()));
  724. }
  725. peerEntry->put(KEY_BITFIELD,
  726. util::toHex((*i)->getBitfield(), (*i)->getBitfieldLength()));
  727. peerEntry->put(KEY_AM_CHOKING, (*i)->amChoking()?VLB_TRUE:VLB_FALSE);
  728. peerEntry->put(KEY_PEER_CHOKING, (*i)->peerChoking()?VLB_TRUE:VLB_FALSE);
  729. peerEntry->put(KEY_DOWNLOAD_SPEED,
  730. util::itos((*i)->calculateDownloadSpeed()));
  731. peerEntry->put(KEY_UPLOAD_SPEED,
  732. util::itos((*i)->calculateUploadSpeed()));
  733. peerEntry->put(KEY_SEEDER, (*i)->isSeeder()?VLB_TRUE:VLB_FALSE);
  734. peers->append(peerEntry);
  735. }
  736. }
  737. } // namespace
  738. #endif // ENABLE_BITTORRENT
  739. namespace {
  740. void gatherProgress
  741. (const SharedHandle<Dict>& entryDict,
  742. const SharedHandle<RequestGroup>& group,
  743. DownloadEngine* e,
  744. const std::vector<std::string>& keys)
  745. {
  746. gatherProgressCommon(entryDict, group, keys);
  747. #ifdef ENABLE_BITTORRENT
  748. if(group->getDownloadContext()->hasAttribute(CTX_ATTR_BT)) {
  749. SharedHandle<TorrentAttribute> torrentAttrs =
  750. bittorrent::getTorrentAttrs(group->getDownloadContext());
  751. const SharedHandle<BtObject>& btObject =
  752. e->getBtRegistry()->get(group->getGID());
  753. gatherProgressBitTorrent(entryDict, torrentAttrs, btObject, keys);
  754. }
  755. #endif // ENABLE_BITTORRENT
  756. }
  757. } // namespace
  758. void gatherStoppedDownload
  759. (const SharedHandle<Dict>& entryDict, const SharedHandle<DownloadResult>& ds,
  760. const std::vector<std::string>& keys)
  761. {
  762. if(requested_key(keys, KEY_GID)) {
  763. entryDict->put(KEY_GID, ds->gid->toHex());
  764. }
  765. if(requested_key(keys, KEY_ERROR_CODE)) {
  766. entryDict->put(KEY_ERROR_CODE, util::itos(static_cast<int>(ds->result)));
  767. }
  768. if(requested_key(keys, KEY_STATUS)) {
  769. if(ds->result == error_code::REMOVED) {
  770. entryDict->put(KEY_STATUS, VLB_REMOVED);
  771. } else if(ds->result == error_code::FINISHED) {
  772. entryDict->put(KEY_STATUS, VLB_COMPLETE);
  773. } else {
  774. entryDict->put(KEY_STATUS, VLB_ERROR);
  775. }
  776. }
  777. if(requested_key(keys, KEY_FOLLOWED_BY)) {
  778. if(!ds->followedBy.empty()) {
  779. SharedHandle<List> list = List::g();
  780. // The element is GID.
  781. for(std::vector<a2_gid_t>::const_iterator i = ds->followedBy.begin(),
  782. eoi = ds->followedBy.end(); i != eoi; ++i) {
  783. list->append(GroupId::toHex(*i));
  784. }
  785. entryDict->put(KEY_FOLLOWED_BY, list);
  786. }
  787. }
  788. if(requested_key(keys, KEY_BELONGS_TO)) {
  789. if(ds->belongsTo) {
  790. entryDict->put(KEY_BELONGS_TO, GroupId::toHex(ds->belongsTo));
  791. }
  792. }
  793. if(requested_key(keys, KEY_FILES)) {
  794. SharedHandle<List> files = List::g();
  795. createFileEntry(files, ds->fileEntries.begin(), ds->fileEntries.end(),
  796. ds->totalLength, ds->pieceLength, ds->bitfield);
  797. entryDict->put(KEY_FILES, files);
  798. }
  799. if(requested_key(keys, KEY_TOTAL_LENGTH)) {
  800. entryDict->put(KEY_TOTAL_LENGTH, util::itos(ds->totalLength));
  801. }
  802. if(requested_key(keys, KEY_COMPLETED_LENGTH)) {
  803. entryDict->put(KEY_COMPLETED_LENGTH, util::itos(ds->completedLength));
  804. }
  805. if(requested_key(keys, KEY_UPLOAD_LENGTH)) {
  806. entryDict->put(KEY_UPLOAD_LENGTH, util::itos(ds->uploadLength));
  807. }
  808. if(requested_key(keys, KEY_BITFIELD)) {
  809. if(!ds->bitfield.empty()) {
  810. entryDict->put(KEY_BITFIELD, util::toHex(ds->bitfield));
  811. }
  812. }
  813. if(requested_key(keys, KEY_DOWNLOAD_SPEED)) {
  814. entryDict->put(KEY_DOWNLOAD_SPEED, VLB_ZERO);
  815. }
  816. if(requested_key(keys, KEY_UPLOAD_SPEED)) {
  817. entryDict->put(KEY_UPLOAD_SPEED, VLB_ZERO);
  818. }
  819. if(!ds->infoHash.empty()) {
  820. if(requested_key(keys, KEY_INFO_HASH)) {
  821. entryDict->put(KEY_INFO_HASH, util::toHex(ds->infoHash));
  822. }
  823. if(requested_key(keys, KEY_NUM_SEEDERS)) {
  824. entryDict->put(KEY_NUM_SEEDERS, VLB_ZERO);
  825. }
  826. }
  827. if(requested_key(keys, KEY_PIECE_LENGTH)) {
  828. entryDict->put(KEY_PIECE_LENGTH, util::itos(ds->pieceLength));
  829. }
  830. if(requested_key(keys, KEY_NUM_PIECES)) {
  831. entryDict->put(KEY_NUM_PIECES, util::uitos(ds->numPieces));
  832. }
  833. if(requested_key(keys, KEY_CONNECTIONS)) {
  834. entryDict->put(KEY_CONNECTIONS, VLB_ZERO);
  835. }
  836. if(requested_key(keys, KEY_DIR)) {
  837. entryDict->put(KEY_DIR, ds->dir);
  838. }
  839. }
  840. SharedHandle<ValueBase> GetFilesRpcMethod::process
  841. (const RpcRequest& req, DownloadEngine* e)
  842. {
  843. const String* gidParam = checkRequiredParam<String>(req, 0);
  844. a2_gid_t gid = str2Gid(gidParam);
  845. SharedHandle<List> files = List::g();
  846. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  847. if(!group) {
  848. SharedHandle<DownloadResult> dr =
  849. e->getRequestGroupMan()->findDownloadResult(gid);
  850. if(!dr) {
  851. throw DL_ABORT_EX(fmt("No file data is available for GID#%s",
  852. GroupId::toHex(gid).c_str()));
  853. } else {
  854. createFileEntry(files, dr->fileEntries.begin(), dr->fileEntries.end(),
  855. dr->totalLength, dr->pieceLength, dr->bitfield);
  856. }
  857. } else {
  858. const SharedHandle<PieceStorage>& ps = group->getPieceStorage();
  859. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  860. createFileEntry(files,
  861. group->getDownloadContext()->getFileEntries().begin(),
  862. group->getDownloadContext()->getFileEntries().end(),
  863. dctx->getTotalLength(),
  864. dctx->getPieceLength(),
  865. ps);
  866. }
  867. return files;
  868. }
  869. SharedHandle<ValueBase> GetUrisRpcMethod::process
  870. (const RpcRequest& req, DownloadEngine* e)
  871. {
  872. const String* gidParam = checkRequiredParam<String>(req, 0);
  873. a2_gid_t gid = str2Gid(gidParam);
  874. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  875. if(!group) {
  876. throw DL_ABORT_EX(fmt("No URI data is available for GID#%s",
  877. GroupId::toHex(gid).c_str()));
  878. }
  879. SharedHandle<List> uriList = List::g();
  880. // TODO Current implementation just returns first FileEntry's URIs.
  881. if(!group->getDownloadContext()->getFileEntries().empty()) {
  882. createUriEntry(uriList, group->getDownloadContext()->getFirstFileEntry());
  883. }
  884. return uriList;
  885. }
  886. #ifdef ENABLE_BITTORRENT
  887. SharedHandle<ValueBase> GetPeersRpcMethod::process
  888. (const RpcRequest& req, DownloadEngine* e)
  889. {
  890. const String* gidParam = checkRequiredParam<String>(req, 0);
  891. a2_gid_t gid = str2Gid(gidParam);
  892. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  893. if(!group) {
  894. throw DL_ABORT_EX(fmt("No peer data is available for GID#%s",
  895. GroupId::toHex(gid).c_str()));
  896. }
  897. SharedHandle<List> peers = List::g();
  898. const SharedHandle<BtObject>& btObject =
  899. e->getBtRegistry()->get(group->getGID());
  900. if(btObject) {
  901. assert(btObject->peerStorage);
  902. gatherPeer(peers, btObject->peerStorage);
  903. }
  904. return peers;
  905. }
  906. #endif // ENABLE_BITTORRENT
  907. SharedHandle<ValueBase> TellStatusRpcMethod::process
  908. (const RpcRequest& req, DownloadEngine* e)
  909. {
  910. const String* gidParam = checkRequiredParam<String>(req, 0);
  911. const List* keysParam = checkParam<List>(req, 1);
  912. a2_gid_t gid = str2Gid(gidParam);
  913. std::vector<std::string> keys;
  914. toStringList(std::back_inserter(keys), keysParam);
  915. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  916. SharedHandle<Dict> entryDict = Dict::g();
  917. if(!group) {
  918. SharedHandle<DownloadResult> ds =
  919. e->getRequestGroupMan()->findDownloadResult(gid);
  920. if(!ds) {
  921. throw DL_ABORT_EX(fmt("No such download for GID#%s",
  922. GroupId::toHex(gid).c_str()));
  923. }
  924. gatherStoppedDownload(entryDict, ds, keys);
  925. } else {
  926. if(requested_key(keys, KEY_STATUS)) {
  927. if(group->getState() == RequestGroup::STATE_ACTIVE) {
  928. entryDict->put(KEY_STATUS, VLB_ACTIVE);
  929. } else {
  930. if(group->isPauseRequested()) {
  931. entryDict->put(KEY_STATUS, VLB_PAUSED);
  932. } else {
  933. entryDict->put(KEY_STATUS, VLB_WAITING);
  934. }
  935. }
  936. }
  937. gatherProgress(entryDict, group, e, keys);
  938. }
  939. return entryDict;
  940. }
  941. SharedHandle<ValueBase> TellActiveRpcMethod::process
  942. (const RpcRequest& req, DownloadEngine* e)
  943. {
  944. const List* keysParam = checkParam<List>(req, 0);
  945. std::vector<std::string> keys;
  946. toStringList(std::back_inserter(keys), keysParam);
  947. SharedHandle<List> list = List::g();
  948. const RequestGroupList& groups = e->getRequestGroupMan()->getRequestGroups();
  949. for(RequestGroupList::const_iterator i = groups.begin(),
  950. eoi = groups.end(); i != eoi; ++i) {
  951. SharedHandle<Dict> entryDict = Dict::g();
  952. if(requested_key(keys, KEY_STATUS)) {
  953. entryDict->put(KEY_STATUS, VLB_ACTIVE);
  954. }
  955. gatherProgress(entryDict, *i, e, keys);
  956. list->append(entryDict);
  957. }
  958. return list;
  959. }
  960. const RequestGroupList&
  961. TellWaitingRpcMethod::getItems(DownloadEngine* e) const
  962. {
  963. return e->getRequestGroupMan()->getReservedGroups();
  964. }
  965. void TellWaitingRpcMethod::createEntry
  966. (const SharedHandle<Dict>& entryDict,
  967. const SharedHandle<RequestGroup>& item,
  968. DownloadEngine* e,
  969. const std::vector<std::string>& keys) const
  970. {
  971. if(requested_key(keys, KEY_STATUS)) {
  972. if(item->isPauseRequested()) {
  973. entryDict->put(KEY_STATUS, VLB_PAUSED);
  974. } else {
  975. entryDict->put(KEY_STATUS, VLB_WAITING);
  976. }
  977. }
  978. gatherProgress(entryDict, item, e, keys);
  979. }
  980. const DownloadResultList&
  981. TellStoppedRpcMethod::getItems(DownloadEngine* e) const
  982. {
  983. return e->getRequestGroupMan()->getDownloadResults();
  984. }
  985. void TellStoppedRpcMethod::createEntry
  986. (const SharedHandle<Dict>& entryDict,
  987. const SharedHandle<DownloadResult>& item,
  988. DownloadEngine* e,
  989. const std::vector<std::string>& keys) const
  990. {
  991. gatherStoppedDownload(entryDict, item, keys);
  992. }
  993. SharedHandle<ValueBase> PurgeDownloadResultRpcMethod::process
  994. (const RpcRequest& req, DownloadEngine* e)
  995. {
  996. e->getRequestGroupMan()->purgeDownloadResult();
  997. return VLB_OK;
  998. }
  999. SharedHandle<ValueBase> RemoveDownloadResultRpcMethod::process
  1000. (const RpcRequest& req, DownloadEngine* e)
  1001. {
  1002. const String* gidParam = checkRequiredParam<String>(req, 0);
  1003. a2_gid_t gid = str2Gid(gidParam);
  1004. if(!e->getRequestGroupMan()->removeDownloadResult(gid)) {
  1005. throw DL_ABORT_EX(fmt("Could not remove download result of GID#%s",
  1006. GroupId::toHex(gid).c_str()));
  1007. }
  1008. return VLB_OK;
  1009. }
  1010. namespace {
  1011. void changeOption
  1012. (const SharedHandle<RequestGroup>& group,
  1013. const Option& option,
  1014. DownloadEngine* e)
  1015. {
  1016. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  1017. const SharedHandle<Option>& grOption = group->getOption();
  1018. grOption->merge(option);
  1019. if(option.defined(PREF_CHECKSUM)) {
  1020. const std::string& checksum = grOption->get(PREF_CHECKSUM);
  1021. std::pair<Scip, Scip> p;
  1022. util::divide(p, checksum.begin(), checksum.end(), '=');
  1023. std::string hashType(p.first.first, p.first.second);
  1024. util::lowercase(hashType);
  1025. dctx->setDigest(hashType, util::fromHex(p.second.first, p.second.second));
  1026. }
  1027. if(option.defined(PREF_SELECT_FILE)) {
  1028. SegList<int> sgl;
  1029. util::parseIntSegments(sgl, grOption->get(PREF_SELECT_FILE));
  1030. sgl.normalize();
  1031. dctx->setFileFilter(sgl);
  1032. }
  1033. if(option.defined(PREF_SPLIT)) {
  1034. group->setNumConcurrentCommand(grOption->getAsInt(PREF_SPLIT));
  1035. }
  1036. if(option.defined(PREF_MAX_CONNECTION_PER_SERVER)) {
  1037. int maxConn = grOption->getAsInt(PREF_MAX_CONNECTION_PER_SERVER);
  1038. const std::vector<SharedHandle<FileEntry> >& files = dctx->getFileEntries();
  1039. for(std::vector<SharedHandle<FileEntry> >::const_iterator i = files.begin(),
  1040. eoi = files.end(); i != eoi; ++i) {
  1041. (*i)->setMaxConnectionPerServer(maxConn);
  1042. }
  1043. }
  1044. if(option.defined(PREF_DIR) || option.defined(PREF_OUT)) {
  1045. if(dctx->getFileEntries().size() == 1
  1046. #ifdef ENABLE_BITTORRENT
  1047. && !dctx->hasAttribute(CTX_ATTR_BT)
  1048. #endif // ENABLE_BITTORRENT
  1049. ) {
  1050. dctx->getFirstFileEntry()->setPath
  1051. (grOption->blank(PREF_OUT) ? A2STR::NIL :
  1052. util::applyDir(grOption->get(PREF_DIR), grOption->get(PREF_OUT)));
  1053. }
  1054. }
  1055. #ifdef ENABLE_BITTORRENT
  1056. if(option.defined(PREF_DIR) || option.defined(PREF_INDEX_OUT)) {
  1057. if(dctx->hasAttribute(CTX_ATTR_BT)) {
  1058. std::istringstream indexOutIn(grOption->get(PREF_INDEX_OUT));
  1059. std::vector<std::pair<size_t, std::string> > indexPaths =
  1060. util::createIndexPaths(indexOutIn);
  1061. for(std::vector<std::pair<size_t, std::string> >::const_iterator i =
  1062. indexPaths.begin(), eoi = indexPaths.end(); i != eoi; ++i) {
  1063. dctx->setFilePathWithIndex
  1064. ((*i).first,
  1065. util::applyDir(grOption->get(PREF_DIR), (*i).second));
  1066. }
  1067. }
  1068. }
  1069. #endif // ENABLE_BITTORRENT
  1070. if(option.defined(PREF_MAX_DOWNLOAD_LIMIT)) {
  1071. group->setMaxDownloadSpeedLimit
  1072. (grOption->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
  1073. }
  1074. if(option.defined(PREF_MAX_UPLOAD_LIMIT)) {
  1075. group->setMaxUploadSpeedLimit(grOption->getAsInt(PREF_MAX_UPLOAD_LIMIT));
  1076. }
  1077. #ifdef ENABLE_BITTORRENT
  1078. const SharedHandle<BtObject>& btObject =
  1079. e->getBtRegistry()->get(group->getGID());
  1080. if(btObject) {
  1081. if(option.defined(PREF_BT_MAX_PEERS)) {
  1082. btObject->btRuntime->setMaxPeers(grOption->getAsInt(PREF_BT_MAX_PEERS));
  1083. }
  1084. }
  1085. #endif // ENABLE_BITTORRENT
  1086. }
  1087. } // namespace
  1088. SharedHandle<ValueBase> ChangeOptionRpcMethod::process
  1089. (const RpcRequest& req, DownloadEngine* e)
  1090. {
  1091. const String* gidParam = checkRequiredParam<String>(req, 0);
  1092. const Dict* optsParam = checkRequiredParam<Dict>(req, 1);
  1093. a2_gid_t gid = str2Gid(gidParam);
  1094. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  1095. Option option;
  1096. if(group) {
  1097. if(group->getState() == RequestGroup::STATE_ACTIVE) {
  1098. gatherChangeableOption(&option, optsParam);
  1099. } else {
  1100. gatherChangeableOptionForReserved(&option, optsParam);
  1101. }
  1102. changeOption(group, option, e);
  1103. } else {
  1104. throw DL_ABORT_EX(fmt("Cannot change option for GID#%s",
  1105. GroupId::toHex(gid).c_str()));
  1106. }
  1107. return VLB_OK;
  1108. }
  1109. SharedHandle<ValueBase> ChangeGlobalOptionRpcMethod::process
  1110. (const RpcRequest& req, DownloadEngine* e)
  1111. {
  1112. const Dict* optsParam = checkRequiredParam<Dict>(req, 0);
  1113. Option option;
  1114. gatherChangeableGlobalOption(&option, optsParam);
  1115. e->getOption()->merge(option);
  1116. if(option.defined(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)) {
  1117. e->getRequestGroupMan()->setMaxOverallDownloadSpeedLimit
  1118. (option.getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT));
  1119. }
  1120. if(option.defined(PREF_MAX_OVERALL_UPLOAD_LIMIT)) {
  1121. e->getRequestGroupMan()->setMaxOverallUploadSpeedLimit
  1122. (option.getAsInt(PREF_MAX_OVERALL_UPLOAD_LIMIT));
  1123. }
  1124. if(option.defined(PREF_MAX_CONCURRENT_DOWNLOADS)) {
  1125. e->getRequestGroupMan()->setMaxSimultaneousDownloads
  1126. (option.getAsInt(PREF_MAX_CONCURRENT_DOWNLOADS));
  1127. e->getRequestGroupMan()->requestQueueCheck();
  1128. }
  1129. if(option.defined(PREF_MAX_DOWNLOAD_RESULT)) {
  1130. e->getRequestGroupMan()->setMaxDownloadResult
  1131. (option.getAsInt(PREF_MAX_DOWNLOAD_RESULT));
  1132. }
  1133. if(option.defined(PREF_LOG_LEVEL)) {
  1134. LogFactory::setLogLevel(option.get(PREF_LOG_LEVEL));
  1135. }
  1136. if(option.defined(PREF_LOG)) {
  1137. LogFactory::setLogFile(option.get(PREF_LOG));
  1138. try {
  1139. LogFactory::reconfigure();
  1140. } catch(RecoverableException& e) {
  1141. // TODO no exception handling
  1142. }
  1143. }
  1144. return VLB_OK;
  1145. }
  1146. SharedHandle<ValueBase> GetVersionRpcMethod::process
  1147. (const RpcRequest& req, DownloadEngine* e)
  1148. {
  1149. SharedHandle<Dict> result = Dict::g();
  1150. result->put(KEY_VERSION, PACKAGE_VERSION);
  1151. SharedHandle<List> featureList = List::g();
  1152. for(int feat = 0; feat < MAX_FEATURE; ++feat) {
  1153. const char* name = strSupportedFeature(feat);
  1154. if(name) {
  1155. featureList->append(name);
  1156. }
  1157. }
  1158. result->put(KEY_ENABLED_FEATURES, featureList);
  1159. return result;
  1160. }
  1161. namespace {
  1162. void pushRequestOption
  1163. (const SharedHandle<Dict>& dict,
  1164. const SharedHandle<Option>& option,
  1165. const SharedHandle<OptionParser>& oparser)
  1166. {
  1167. for(size_t i = 1, len = option::countOption(); i < len; ++i) {
  1168. const Pref* pref = option::i2p(i);
  1169. const OptionHandler* h = oparser->find(pref);
  1170. if(h && h->getInitialOption() && option->defined(pref)) {
  1171. dict->put(pref->k, option->get(pref));
  1172. }
  1173. }
  1174. }
  1175. } // namespace
  1176. SharedHandle<ValueBase> GetOptionRpcMethod::process
  1177. (const RpcRequest& req, DownloadEngine* e)
  1178. {
  1179. const String* gidParam = checkRequiredParam<String>(req, 0);
  1180. a2_gid_t gid = str2Gid(gidParam);
  1181. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  1182. if(!group) {
  1183. throw DL_ABORT_EX(fmt("Cannot get option for GID#%s",
  1184. GroupId::toHex(gid).c_str()));
  1185. }
  1186. SharedHandle<Dict> result = Dict::g();
  1187. SharedHandle<Option> option = group->getOption();
  1188. pushRequestOption(result, option, getOptionParser());
  1189. return result;
  1190. }
  1191. SharedHandle<ValueBase> GetGlobalOptionRpcMethod::process
  1192. (const RpcRequest& req, DownloadEngine* e)
  1193. {
  1194. SharedHandle<Dict> result = Dict::g();
  1195. for(size_t i = 0, len = e->getOption()->getTable().size(); i < len; ++i) {
  1196. const Pref* pref = option::i2p(i);
  1197. if(!e->getOption()->defined(pref)) {
  1198. continue;
  1199. }
  1200. const OptionHandler* h = getOptionParser()->find(pref);
  1201. if(h) {
  1202. result->put(pref->k, e->getOption()->get(pref));
  1203. }
  1204. }
  1205. return result;
  1206. }
  1207. SharedHandle<ValueBase> ChangePositionRpcMethod::process
  1208. (const RpcRequest& req, DownloadEngine* e)
  1209. {
  1210. const String* gidParam = checkRequiredParam<String>(req, 0);
  1211. const Integer* posParam = checkRequiredParam<Integer>(req, 1);
  1212. const String* howParam = checkRequiredParam<String>(req, 2);
  1213. a2_gid_t gid = str2Gid(gidParam);
  1214. int pos = posParam->i();
  1215. const std::string& howStr = howParam->s();
  1216. A2_HOW how;
  1217. if(howStr == "POS_SET") {
  1218. how = A2_POS_SET;
  1219. } else if(howStr == "POS_CUR") {
  1220. how = A2_POS_CUR;
  1221. } else if(howStr == "POS_END") {
  1222. how = A2_POS_END;
  1223. } else {
  1224. throw DL_ABORT_EX("Illegal argument.");
  1225. }
  1226. size_t destPos =
  1227. e->getRequestGroupMan()->changeReservedGroupPosition(gid, pos, how);
  1228. SharedHandle<Integer> result = Integer::g(destPos);
  1229. return result;
  1230. }
  1231. SharedHandle<ValueBase> GetSessionInfoRpcMethod::process
  1232. (const RpcRequest& req, DownloadEngine* e)
  1233. {
  1234. SharedHandle<Dict> result = Dict::g();
  1235. result->put(KEY_SESSION_ID, util::toHex(e->getSessionId()));
  1236. return result;
  1237. }
  1238. SharedHandle<ValueBase> GetServersRpcMethod::process
  1239. (const RpcRequest& req, DownloadEngine* e)
  1240. {
  1241. const String* gidParam = checkRequiredParam<String>(req, 0);
  1242. a2_gid_t gid = str2Gid(gidParam);
  1243. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  1244. if(!group || group->getState() != RequestGroup::STATE_ACTIVE) {
  1245. throw DL_ABORT_EX(fmt("No active download for GID#%s",
  1246. GroupId::toHex(gid).c_str()));
  1247. }
  1248. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  1249. const std::vector<SharedHandle<FileEntry> >& files = dctx->getFileEntries();
  1250. SharedHandle<List> result = List::g();
  1251. size_t index = 1;
  1252. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi = files.begin(),
  1253. eoi = files.end(); fi != eoi; ++fi, ++index) {
  1254. SharedHandle<Dict> fileEntry = Dict::g();
  1255. fileEntry->put(KEY_INDEX, util::uitos(index));
  1256. SharedHandle<List> servers = List::g();
  1257. const FileEntry::InFlightRequestSet& requests =
  1258. (*fi)->getInFlightRequests();
  1259. for(FileEntry::InFlightRequestSet::iterator ri =requests.begin(),
  1260. eoi = requests.end(); ri != eoi; ++ri) {
  1261. SharedHandle<PeerStat> ps = (*ri)->getPeerStat();
  1262. if(ps) {
  1263. SharedHandle<Dict> serverEntry = Dict::g();
  1264. serverEntry->put(KEY_URI, (*ri)->getUri());
  1265. serverEntry->put(KEY_CURRENT_URI, (*ri)->getCurrentUri());
  1266. serverEntry->put(KEY_DOWNLOAD_SPEED,
  1267. util::itos(ps->calculateDownloadSpeed()));
  1268. servers->append(serverEntry);
  1269. }
  1270. }
  1271. fileEntry->put(KEY_SERVERS, servers);
  1272. result->append(fileEntry);
  1273. }
  1274. return result;
  1275. }
  1276. SharedHandle<ValueBase> ChangeUriRpcMethod::process
  1277. (const RpcRequest& req, DownloadEngine* e)
  1278. {
  1279. const String* gidParam = checkRequiredParam<String>(req, 0);
  1280. const Integer* indexParam = checkRequiredInteger(req, 1, IntegerGE(1));
  1281. const List* delUrisParam = checkRequiredParam<List>(req, 2);
  1282. const List* addUrisParam = checkRequiredParam<List>(req, 3);
  1283. const Integer* posParam = checkParam<Integer>(req, 4);
  1284. a2_gid_t gid = str2Gid(gidParam);
  1285. bool posGiven = checkPosParam(posParam);
  1286. size_t pos = posGiven ? posParam->i() : 0;
  1287. size_t index = indexParam->i()-1;
  1288. SharedHandle<RequestGroup> group = e->getRequestGroupMan()->findGroup(gid);
  1289. if(!group) {
  1290. throw DL_ABORT_EX(fmt("Cannot remove URIs from GID#%s",
  1291. GroupId::toHex(gid).c_str()));
  1292. }
  1293. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  1294. const std::vector<SharedHandle<FileEntry> >& files = dctx->getFileEntries();
  1295. if(files.size() <= index) {
  1296. throw DL_ABORT_EX(fmt("fileIndex is out of range"));
  1297. }
  1298. SharedHandle<FileEntry> s = files[index];
  1299. size_t delcount = 0;
  1300. for(List::ValueType::const_iterator i = delUrisParam->begin(),
  1301. eoi = delUrisParam->end(); i != eoi; ++i) {
  1302. const String* uri = downcast<String>(*i);
  1303. if(uri && s->removeUri(uri->s())) {
  1304. ++delcount;
  1305. }
  1306. }
  1307. size_t addcount = 0;
  1308. if(posGiven) {
  1309. for(List::ValueType::const_iterator i = addUrisParam->begin(),
  1310. eoi = addUrisParam->end(); i != eoi; ++i) {
  1311. const String* uri = downcast<String>(*i);
  1312. if(uri && s->insertUri(uri->s(), pos)) {
  1313. ++addcount;
  1314. ++pos;
  1315. }
  1316. }
  1317. } else {
  1318. for(List::ValueType::const_iterator i = addUrisParam->begin(),
  1319. eoi = addUrisParam->end(); i != eoi; ++i) {
  1320. const String* uri = downcast<String>(*i);
  1321. if(uri && s->addUri(uri->s())) {
  1322. ++addcount;
  1323. }
  1324. }
  1325. }
  1326. if(addcount && group->getPieceStorage()) {
  1327. std::vector<Command*> commands;
  1328. group->createNextCommand(commands, e);
  1329. e->addCommand(commands);
  1330. group->getSegmentMan()->recognizeSegmentFor(s);
  1331. }
  1332. SharedHandle<List> res = List::g();
  1333. res->append(Integer::g(delcount));
  1334. res->append(Integer::g(addcount));
  1335. return res;
  1336. }
  1337. namespace {
  1338. SharedHandle<ValueBase> goingShutdown
  1339. (const RpcRequest& req, DownloadEngine* e, bool forceHalt)
  1340. {
  1341. // Schedule shutdown after 3seconds to give time to client to
  1342. // receive RPC response.
  1343. e->addRoutineCommand(new TimedHaltCommand(e->newCUID(), e, 3, forceHalt));
  1344. A2_LOG_INFO("Scheduled shutdown in 3 seconds.");
  1345. return VLB_OK;
  1346. }
  1347. } // namespace
  1348. SharedHandle<ValueBase> ShutdownRpcMethod::process
  1349. (const RpcRequest& req, DownloadEngine* e)
  1350. {
  1351. return goingShutdown(req, e, false);
  1352. }
  1353. SharedHandle<ValueBase> ForceShutdownRpcMethod::process
  1354. (const RpcRequest& req, DownloadEngine* e)
  1355. {
  1356. return goingShutdown(req, e, true);
  1357. }
  1358. SharedHandle<ValueBase> GetGlobalStatRpcMethod::process
  1359. (const RpcRequest& req, DownloadEngine* e)
  1360. {
  1361. const SharedHandle<RequestGroupMan>& rgman = e->getRequestGroupMan();
  1362. TransferStat ts = rgman->calculateStat();
  1363. SharedHandle<Dict> res = Dict::g();
  1364. res->put(KEY_DOWNLOAD_SPEED, util::itos(ts.downloadSpeed));
  1365. res->put(KEY_UPLOAD_SPEED, util::itos(ts.uploadSpeed));
  1366. res->put(KEY_NUM_WAITING, util::uitos(rgman->getReservedGroups().size()));
  1367. res->put(KEY_NUM_STOPPED, util::uitos(rgman->getDownloadResults().size()));
  1368. res->put(KEY_NUM_ACTIVE, util::uitos(rgman->getRequestGroups().size()));
  1369. return res;
  1370. }
  1371. SharedHandle<ValueBase> SystemMulticallRpcMethod::process
  1372. (const RpcRequest& req, DownloadEngine* e)
  1373. {
  1374. const List* methodSpecs = checkRequiredParam<List>(req, 0);
  1375. SharedHandle<List> list = List::g();
  1376. for(List::ValueType::const_iterator i = methodSpecs->begin(),
  1377. eoi = methodSpecs->end(); i != eoi; ++i) {
  1378. const Dict* methodDict = downcast<Dict>(*i);
  1379. if(!methodDict) {
  1380. list->append(createErrorResponse
  1381. (DL_ABORT_EX("system.multicall expected struct."), req));
  1382. continue;
  1383. }
  1384. const String* methodName = downcast<String>(methodDict->get(KEY_METHOD_NAME));
  1385. if(!methodName) {
  1386. list->append(createErrorResponse
  1387. (DL_ABORT_EX("Missing methodName."), req));
  1388. continue;
  1389. }
  1390. if(methodName->s() == getMethodName()) {
  1391. list->append(createErrorResponse
  1392. (DL_ABORT_EX("Recursive system.multicall forbidden."), req));
  1393. continue;
  1394. }
  1395. const SharedHandle<ValueBase>& tempParamsList = methodDict->get(KEY_PARAMS);
  1396. SharedHandle<List> paramsList;
  1397. if(downcast<List>(tempParamsList)) {
  1398. paramsList = static_pointer_cast<List>(tempParamsList);
  1399. } else {
  1400. paramsList = List::g();
  1401. }
  1402. SharedHandle<RpcMethod> method = RpcMethodFactory::create(methodName->s());
  1403. RpcRequest innerReq(methodName->s(), paramsList);
  1404. innerReq.jsonRpc = req.jsonRpc;
  1405. RpcResponse res = method->execute(innerReq, e);
  1406. if(res.code == 0) {
  1407. SharedHandle<List> l = List::g();
  1408. l->append(res.param);
  1409. list->append(l);
  1410. } else {
  1411. list->append(res.param);
  1412. }
  1413. }
  1414. return list;
  1415. }
  1416. SharedHandle<ValueBase> NoSuchMethodRpcMethod::process
  1417. (const RpcRequest& req, DownloadEngine* e)
  1418. {
  1419. throw DL_ABORT_EX(fmt("No such method: %s", req.methodName.c_str()));
  1420. }
  1421. } // namespace rpc
  1422. bool pauseRequestGroup
  1423. (const SharedHandle<RequestGroup>& group, bool reserved, bool forcePause)
  1424. {
  1425. if((reserved && !group->isPauseRequested()) ||
  1426. (!reserved &&
  1427. !group->isForceHaltRequested() &&
  1428. ((forcePause && group->isHaltRequested() && group->isPauseRequested()) ||
  1429. (!group->isHaltRequested() && !group->isPauseRequested())))) {
  1430. if(!reserved) {
  1431. // Call setHaltRequested before setPauseRequested because
  1432. // setHaltRequested calls setPauseRequested(false) internally.
  1433. if(forcePause) {
  1434. group->setForceHaltRequested(true, RequestGroup::NONE);
  1435. } else {
  1436. group->setHaltRequested(true, RequestGroup::NONE);
  1437. }
  1438. }
  1439. group->setPauseRequested(true);
  1440. return true;
  1441. } else {
  1442. return false;
  1443. }
  1444. }
  1445. } // namespace aria2