RpcMethodImpl.cc 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410
  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 "Logger.h"
  39. #include "LogFactory.h"
  40. #include "DlAbortEx.h"
  41. #include "Option.h"
  42. #include "OptionParser.h"
  43. #include "OptionHandler.h"
  44. #include "DownloadEngine.h"
  45. #include "RequestGroup.h"
  46. #include "download_helper.h"
  47. #include "util.h"
  48. #include "RequestGroupMan.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. #ifdef ENABLE_BITTORRENT
  66. # include "bittorrent_helper.h"
  67. # include "BtRegistry.h"
  68. # include "PeerStorage.h"
  69. # include "Peer.h"
  70. # include "BtRuntime.h"
  71. # include "BtAnnounce.h"
  72. # include "MessageDigest.h"
  73. # include "message_digest_helper.h"
  74. #endif // ENABLE_BITTORRENT
  75. namespace aria2 {
  76. namespace rpc {
  77. namespace {
  78. const SharedHandle<String> VLB_TRUE = String::g("true");
  79. const SharedHandle<String> VLB_FALSE = String::g("false");
  80. const SharedHandle<String> VLB_OK = String::g("OK");
  81. const SharedHandle<String> VLB_ACTIVE = String::g("active");
  82. const SharedHandle<String> VLB_WAITING = String::g("waiting");
  83. const SharedHandle<String> VLB_PAUSED = String::g("paused");
  84. const SharedHandle<String> VLB_REMOVED = String::g("removed");
  85. const SharedHandle<String> VLB_ERROR = String::g("error");
  86. const SharedHandle<String> VLB_COMPLETE = String::g("complete");
  87. const SharedHandle<String> VLB_USED = String::g("used");
  88. const SharedHandle<String> VLB_ZERO = String::g("0");
  89. const std::string KEY_GID = "gid";
  90. const std::string KEY_ERROR_CODE = "errorCode";
  91. const std::string KEY_STATUS = "status";
  92. const std::string KEY_TOTAL_LENGTH = "totalLength";
  93. const std::string KEY_COMPLETED_LENGTH = "completedLength";
  94. const std::string KEY_DOWNLOAD_SPEED = "downloadSpeed";
  95. const std::string KEY_UPLOAD_SPEED = "uploadSpeed";
  96. const std::string KEY_UPLOAD_LENGTH = "uploadLength";
  97. const std::string KEY_CONNECTIONS = "connections";
  98. const std::string KEY_BITFIELD = "bitfield";
  99. const std::string KEY_PIECE_LENGTH = "pieceLength";
  100. const std::string KEY_NUM_PIECES = "numPieces";
  101. const std::string KEY_FOLLOWED_BY = "followedBy";
  102. const std::string KEY_BELONGS_TO = "belongsTo";
  103. const std::string KEY_INFO_HASH = "infoHash";
  104. const std::string KEY_NUM_SEEDERS = "numSeeders";
  105. const std::string KEY_PEER_ID = "peerId";
  106. const std::string KEY_IP = "ip";
  107. const std::string KEY_PORT = "port";
  108. const std::string KEY_AM_CHOKING = "amChoking";
  109. const std::string KEY_PEER_CHOKING = "peerChoking";
  110. const std::string KEY_SEEDER = "seeder";
  111. const std::string KEY_INDEX = "index";
  112. const std::string KEY_PATH = "path";
  113. const std::string KEY_SELECTED = "selected";
  114. const std::string KEY_LENGTH = "length";
  115. const std::string KEY_URI = "uri";
  116. const std::string KEY_CURRENT_URI = "currentUri";
  117. const std::string KEY_VERSION = "version";
  118. const std::string KEY_ENABLED_FEATURES = "enabledFeatures";
  119. const std::string KEY_METHOD_NAME = "methodName";
  120. const std::string KEY_PARAMS = "params";
  121. const std::string KEY_SESSION_ID = "sessionId";
  122. const std::string KEY_FILES = "files";
  123. const std::string KEY_DIR = "dir";
  124. const std::string KEY_URIS = "uris";
  125. const std::string KEY_BITTORRENT = "bittorrent";
  126. const std::string KEY_INFO = "info";
  127. const std::string KEY_NAME = "name";
  128. const std::string KEY_ANNOUNCE_LIST = "announceList";
  129. const std::string KEY_COMMENT = "comment";
  130. const std::string KEY_CREATION_DATE = "creationDate";
  131. const std::string KEY_MODE = "mode";
  132. const std::string KEY_SERVERS = "servers";
  133. } // namespace
  134. namespace {
  135. SharedHandle<ValueBase> createGIDResponse(gid_t gid)
  136. {
  137. return String::g(util::itos(gid));
  138. }
  139. } // namespace
  140. namespace {
  141. SharedHandle<ValueBase>
  142. addRequestGroup(const SharedHandle<RequestGroup>& group,
  143. DownloadEngine* e,
  144. bool posGiven, int pos)
  145. {
  146. if(posGiven) {
  147. e->getRequestGroupMan()->insertReservedGroup(pos, group);
  148. } else {
  149. e->getRequestGroupMan()->addReservedGroup(group);
  150. }
  151. return createGIDResponse(group->getGID());
  152. }
  153. } // namespace
  154. namespace {
  155. SharedHandle<RequestGroup>
  156. findRequestGroup(const SharedHandle<RequestGroupMan>& rgman, gid_t gid)
  157. {
  158. SharedHandle<RequestGroup> group = rgman->findRequestGroup(gid);
  159. if(!group) {
  160. group = rgman->findReservedGroup(gid);
  161. }
  162. return group;
  163. }
  164. } // namespace
  165. namespace {
  166. void getPosParam(const RpcRequest& req, size_t posParamIndex,
  167. bool& posGiven, size_t& pos)
  168. {
  169. const Integer* p = req.getIntegerParam(posParamIndex);
  170. if(p) {
  171. if(p->i() >= 0) {
  172. pos = p->i();
  173. posGiven = true;
  174. return;
  175. } else {
  176. throw DL_ABORT_EX("Position must be greater than or equal to 0.");
  177. }
  178. }
  179. posGiven = false;
  180. }
  181. } // namespace
  182. namespace {
  183. gid_t getRequiredGidParam
  184. (const RpcRequest& req, size_t posParamIndex)
  185. {
  186. const String* gidParam = req.getStringParam(posParamIndex);
  187. if(gidParam) {
  188. return util::parseLLInt(gidParam->s());
  189. } else {
  190. throw DL_ABORT_EX(MSG_GID_NOT_PROVIDED);
  191. }
  192. }
  193. } // namespace
  194. namespace {
  195. template<typename OutputIterator>
  196. void extractUris(OutputIterator out, const List* src)
  197. {
  198. if(src) {
  199. for(List::ValueType::const_iterator i = src->begin(), eoi = src->end();
  200. i != eoi; ++i) {
  201. const String* uri = asString(*i);
  202. if(uri) {
  203. out++ = uri->s();
  204. }
  205. }
  206. }
  207. }
  208. } // namespace
  209. SharedHandle<ValueBase> AddUriRpcMethod::process
  210. (const RpcRequest& req, DownloadEngine* e)
  211. {
  212. std::vector<std::string> uris;
  213. extractUris(std::back_inserter(uris), req.getListParam(0));
  214. if(uris.empty()) {
  215. throw DL_ABORT_EX("URI is not provided.");
  216. }
  217. SharedHandle<Option> requestOption(new Option(*e->getOption()));
  218. gatherRequestOption(requestOption, req.getDictParam(1));
  219. size_t pos = 0;
  220. bool posGiven = false;
  221. getPosParam(req, 2, posGiven, pos);
  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. namespace {
  233. std::string getHexSha1(const std::string& s)
  234. {
  235. unsigned char hash[20];
  236. message_digest::digest(hash, sizeof(hash), MessageDigest::sha1(),
  237. s.data(), s.size());
  238. return util::toHex(hash, sizeof(hash));
  239. }
  240. } // namespace
  241. #ifdef ENABLE_BITTORRENT
  242. SharedHandle<ValueBase> AddTorrentRpcMethod::process
  243. (const RpcRequest& req, DownloadEngine* e)
  244. {
  245. const String* torrentParam = req.getStringParam(0);
  246. if(!torrentParam) {
  247. throw DL_ABORT_EX("Torrent data is not provided.");
  248. }
  249. SharedHandle<String> tempTorrentParam;
  250. if(getJsonRpc()) {
  251. tempTorrentParam = String::g(Base64::decode(torrentParam->s()));
  252. torrentParam = tempTorrentParam.get();
  253. }
  254. std::vector<std::string> uris;
  255. extractUris(std::back_inserter(uris), req.getListParam(1));
  256. SharedHandle<Option> requestOption(new Option(*e->getOption()));
  257. gatherRequestOption(requestOption, req.getDictParam(2));
  258. size_t pos = 0;
  259. bool posGiven = false;
  260. getPosParam(req, 3, posGiven, pos);
  261. std::string filename = util::applyDir
  262. (requestOption->get(PREF_DIR), getHexSha1(torrentParam->s())+".torrent");
  263. std::vector<SharedHandle<RequestGroup> > result;
  264. // Save uploaded data in order to save this download in
  265. // --save-session file.
  266. if(util::saveAs(filename, torrentParam->s(), true)) {
  267. A2_LOG_INFO(fmt("Uploaded torrent data was saved as %s", filename.c_str()));
  268. requestOption->put(PREF_TORRENT_FILE, filename);
  269. createRequestGroupForBitTorrent(result, requestOption, uris);
  270. } else {
  271. A2_LOG_INFO(fmt("Uploaded torrent data was not saved."
  272. " Failed to write file %s", filename.c_str()));
  273. createRequestGroupForBitTorrent(result, requestOption,
  274. uris, torrentParam->s());
  275. }
  276. if(!result.empty()) {
  277. return addRequestGroup(result.front(), e, posGiven, pos);
  278. } else {
  279. throw DL_ABORT_EX("No Torrent to download.");
  280. }
  281. }
  282. #endif // ENABLE_BITTORRENT
  283. #ifdef ENABLE_METALINK
  284. SharedHandle<ValueBase> AddMetalinkRpcMethod::process
  285. (const RpcRequest& req, DownloadEngine* e)
  286. {
  287. const String* metalinkParam = req.getStringParam(0);
  288. if(!metalinkParam) {
  289. throw DL_ABORT_EX("Metalink data is not provided.");
  290. }
  291. SharedHandle<String> tempMetalinkParam;
  292. if(getJsonRpc()) {
  293. tempMetalinkParam = String::g(Base64::decode(metalinkParam->s()));
  294. metalinkParam = tempMetalinkParam.get();
  295. }
  296. SharedHandle<Option> requestOption(new Option(*e->getOption()));
  297. gatherRequestOption(requestOption, req.getDictParam(1));
  298. size_t pos = 0;
  299. bool posGiven = false;
  300. getPosParam(req, 2, posGiven, pos);
  301. // TODO RFC5854 Metalink has the extension .meta4. We use .metalink
  302. // for both v3 and RFC5854 Metalink. aria2 can detect which of which
  303. // by reading content rather than extension.
  304. std::string filename = util::applyDir
  305. (requestOption->get(PREF_DIR), getHexSha1(metalinkParam->s())+".metalink");
  306. std::vector<SharedHandle<RequestGroup> > result;
  307. // Save uploaded data in order to save this download in
  308. // --save-session file.
  309. if(util::saveAs(filename, metalinkParam->s(), true)) {
  310. A2_LOG_INFO(fmt("Uploaded metalink data was saved as %s",
  311. filename.c_str()));
  312. requestOption->put(PREF_METALINK_FILE, filename);
  313. createRequestGroupForMetalink(result, requestOption);
  314. } else {
  315. A2_LOG_INFO(fmt("Uploaded metalink data was not saved."
  316. " Failed to write file %s", filename.c_str()));
  317. createRequestGroupForMetalink(result, requestOption, metalinkParam->s());
  318. }
  319. SharedHandle<List> gids = List::g();
  320. if(!result.empty()) {
  321. if(posGiven) {
  322. e->getRequestGroupMan()->insertReservedGroup(pos, result);
  323. } else {
  324. e->getRequestGroupMan()->addReservedGroup(result);
  325. }
  326. for(std::vector<SharedHandle<RequestGroup> >::const_iterator i =
  327. result.begin(), eoi = result.end(); i != eoi; ++i) {
  328. gids->append(util::itos((*i)->getGID()));
  329. }
  330. }
  331. return gids;
  332. }
  333. #endif // ENABLE_METALINK
  334. namespace {
  335. SharedHandle<ValueBase> removeDownload
  336. (const RpcRequest& req, DownloadEngine* e, bool forceRemove)
  337. {
  338. gid_t gid = getRequiredGidParam(req, 0);
  339. SharedHandle<RequestGroup> group =
  340. e->getRequestGroupMan()->findRequestGroup(gid);
  341. if(!group) {
  342. group = e->getRequestGroupMan()->findReservedGroup(gid);
  343. if(!group) {
  344. throw DL_ABORT_EX
  345. (fmt("Active Download not found for GID#%s",
  346. util::itos(gid).c_str()));
  347. }
  348. if(group->isDependencyResolved()) {
  349. e->getRequestGroupMan()->removeReservedGroup(gid);
  350. } else {
  351. throw DL_ABORT_EX
  352. (fmt("GID#%s cannot be removed now",
  353. util::itos(gid).c_str()));
  354. }
  355. } else {
  356. if(forceRemove) {
  357. group->setForceHaltRequested(true, RequestGroup::USER_REQUEST);
  358. } else {
  359. group->setHaltRequested(true, RequestGroup::USER_REQUEST);
  360. }
  361. }
  362. return createGIDResponse(gid);
  363. }
  364. } // namespace
  365. SharedHandle<ValueBase> RemoveRpcMethod::process
  366. (const RpcRequest& req, DownloadEngine* e)
  367. {
  368. return removeDownload(req, e, false);
  369. }
  370. SharedHandle<ValueBase> ForceRemoveRpcMethod::process
  371. (const RpcRequest& req, DownloadEngine* e)
  372. {
  373. return removeDownload(req, e, true);
  374. }
  375. namespace {
  376. bool pauseRequestGroup
  377. (const SharedHandle<RequestGroup>& group, bool reserved, bool forcePause)
  378. {
  379. if((reserved && !group->isPauseRequested()) ||
  380. (!reserved &&
  381. !group->isForceHaltRequested() &&
  382. ((forcePause && group->isHaltRequested() && group->isPauseRequested()) ||
  383. (!group->isHaltRequested() && !group->isPauseRequested())))) {
  384. if(!reserved) {
  385. // Call setHaltRequested before setPauseRequested because
  386. // setHaltRequested calls setPauseRequested(false) internally.
  387. if(forcePause) {
  388. group->setForceHaltRequested(true, RequestGroup::NONE);
  389. } else {
  390. group->setHaltRequested(true, RequestGroup::NONE);
  391. }
  392. }
  393. group->setPauseRequested(true);
  394. return true;
  395. } else {
  396. return false;
  397. }
  398. }
  399. } // namespace
  400. namespace {
  401. SharedHandle<ValueBase> pauseDownload
  402. (const RpcRequest& req, DownloadEngine* e, bool forcePause)
  403. {
  404. gid_t gid = getRequiredGidParam(req, 0);
  405. bool reserved = false;
  406. SharedHandle<RequestGroup> group =
  407. e->getRequestGroupMan()->findRequestGroup(gid);
  408. if(!group) {
  409. reserved = true;
  410. group = e->getRequestGroupMan()->findReservedGroup(gid);
  411. }
  412. if(group && pauseRequestGroup(group, reserved, forcePause)) {
  413. return createGIDResponse(gid);
  414. } else {
  415. throw DL_ABORT_EX
  416. (fmt("GID#%s cannot be paused now",
  417. util::itos(gid).c_str()));
  418. }
  419. }
  420. } // namespace
  421. SharedHandle<ValueBase> PauseRpcMethod::process
  422. (const RpcRequest& req, DownloadEngine* e)
  423. {
  424. return pauseDownload(req, e, false);
  425. }
  426. SharedHandle<ValueBase> ForcePauseRpcMethod::process
  427. (const RpcRequest& req, DownloadEngine* e)
  428. {
  429. return pauseDownload(req, e, true);
  430. }
  431. namespace {
  432. template<typename InputIterator>
  433. void pauseRequestGroups
  434. (InputIterator first, InputIterator last, bool reserved, bool forcePause)
  435. {
  436. for(; first != last; ++first) {
  437. pauseRequestGroup(*first, reserved, forcePause);
  438. }
  439. }
  440. } // namespace
  441. namespace {
  442. SharedHandle<ValueBase> pauseAllDownloads
  443. (const RpcRequest& req, DownloadEngine* e, bool forcePause)
  444. {
  445. const std::deque<SharedHandle<RequestGroup> >& groups =
  446. e->getRequestGroupMan()->getRequestGroups();
  447. pauseRequestGroups(groups.begin(), groups.end(), false, forcePause);
  448. const std::deque<SharedHandle<RequestGroup> >& reservedGroups =
  449. e->getRequestGroupMan()->getReservedGroups();
  450. pauseRequestGroups(reservedGroups.begin(), reservedGroups.end(),
  451. true, forcePause);
  452. return VLB_OK;
  453. }
  454. } // namespace
  455. SharedHandle<ValueBase> PauseAllRpcMethod::process
  456. (const RpcRequest& req, DownloadEngine* e)
  457. {
  458. return pauseAllDownloads(req, e, false);
  459. }
  460. SharedHandle<ValueBase> ForcePauseAllRpcMethod::process
  461. (const RpcRequest& req, DownloadEngine* e)
  462. {
  463. return pauseAllDownloads(req, e, true);
  464. }
  465. SharedHandle<ValueBase> UnpauseRpcMethod::process
  466. (const RpcRequest& req, DownloadEngine* e)
  467. {
  468. gid_t gid = getRequiredGidParam(req, 0);
  469. SharedHandle<RequestGroup> group =
  470. e->getRequestGroupMan()->findReservedGroup(gid);
  471. if(!group || !group->isPauseRequested()) {
  472. throw DL_ABORT_EX
  473. (fmt("GID#%s cannot be unpaused now",
  474. util::itos(gid).c_str()));
  475. } else {
  476. group->setPauseRequested(false);
  477. e->getRequestGroupMan()->requestQueueCheck();
  478. }
  479. return createGIDResponse(gid);
  480. }
  481. SharedHandle<ValueBase> UnpauseAllRpcMethod::process
  482. (const RpcRequest& req, DownloadEngine* e)
  483. {
  484. const std::deque<SharedHandle<RequestGroup> >& groups =
  485. e->getRequestGroupMan()->getReservedGroups();
  486. std::for_each(groups.begin(), groups.end(),
  487. std::bind2nd(mem_fun_sh(&RequestGroup::setPauseRequested),
  488. false));
  489. e->getRequestGroupMan()->requestQueueCheck();
  490. return VLB_OK;
  491. }
  492. namespace {
  493. template<typename InputIterator>
  494. void createUriEntry
  495. (const SharedHandle<List>& uriList,
  496. InputIterator first, InputIterator last,
  497. const SharedHandle<String>& status)
  498. {
  499. for(; first != last; ++first) {
  500. SharedHandle<Dict> entry = Dict::g();
  501. entry->put(KEY_URI, *first);
  502. entry->put(KEY_STATUS, status);
  503. uriList->append(entry);
  504. }
  505. }
  506. } // namespace
  507. namespace {
  508. void createUriEntry
  509. (const SharedHandle<List>& uriList, const SharedHandle<FileEntry>& file)
  510. {
  511. createUriEntry(uriList,
  512. file->getSpentUris().begin(),
  513. file->getSpentUris().end(),
  514. VLB_USED);
  515. createUriEntry(uriList,
  516. file->getRemainingUris().begin(),
  517. file->getRemainingUris().end(),
  518. VLB_WAITING);
  519. }
  520. } // namespace
  521. namespace {
  522. template<typename InputIterator>
  523. void createFileEntry
  524. (const SharedHandle<List>& files, InputIterator first, InputIterator last)
  525. {
  526. size_t index = 1;
  527. for(; first != last; ++first, ++index) {
  528. SharedHandle<Dict> entry = Dict::g();
  529. entry->put(KEY_INDEX, util::uitos(index));
  530. entry->put(KEY_PATH, (*first)->getPath());
  531. entry->put(KEY_SELECTED, (*first)->isRequested()?VLB_TRUE:VLB_FALSE);
  532. entry->put(KEY_LENGTH, util::uitos((*first)->getLength()));
  533. SharedHandle<List> uriList = List::g();
  534. createUriEntry(uriList, *first);
  535. entry->put(KEY_URIS, uriList);
  536. files->append(entry);
  537. }
  538. }
  539. } // namespace
  540. namespace {
  541. bool requested_key
  542. (const std::vector<std::string>& keys, const std::string& k)
  543. {
  544. return keys.empty() || std::find(keys.begin(), keys.end(), k) != keys.end();
  545. }
  546. } // namespace
  547. void gatherProgressCommon
  548. (const SharedHandle<Dict>& entryDict,
  549. const SharedHandle<RequestGroup>& group,
  550. const std::vector<std::string>& keys)
  551. {
  552. if(requested_key(keys, KEY_GID)) {
  553. entryDict->put(KEY_GID, util::itos(group->getGID()));
  554. }
  555. if(requested_key(keys, KEY_TOTAL_LENGTH)) {
  556. // This is "filtered" total length if --select-file is used.
  557. entryDict->put(KEY_TOTAL_LENGTH, util::uitos(group->getTotalLength()));
  558. }
  559. if(requested_key(keys, KEY_COMPLETED_LENGTH)) {
  560. // This is "filtered" total length if --select-file is used.
  561. entryDict->put
  562. (KEY_COMPLETED_LENGTH,util::uitos(group->getCompletedLength()));
  563. }
  564. TransferStat stat = group->calculateStat();
  565. if(requested_key(keys, KEY_DOWNLOAD_SPEED)) {
  566. entryDict->put(KEY_DOWNLOAD_SPEED, util::uitos(stat.getDownloadSpeed()));
  567. }
  568. if(requested_key(keys, KEY_UPLOAD_SPEED)) {
  569. entryDict->put(KEY_UPLOAD_SPEED, util::uitos(stat.getUploadSpeed()));
  570. }
  571. if(requested_key(keys, KEY_UPLOAD_LENGTH)) {
  572. entryDict->put
  573. (KEY_UPLOAD_LENGTH, util::uitos(stat.getAllTimeUploadLength()));
  574. }
  575. if(requested_key(keys, KEY_CONNECTIONS)) {
  576. entryDict->put(KEY_CONNECTIONS, util::uitos(group->getNumConnection()));
  577. }
  578. if(requested_key(keys, KEY_BITFIELD)) {
  579. SharedHandle<PieceStorage> ps = group->getPieceStorage();
  580. if(ps) {
  581. if(ps->getBitfieldLength() > 0) {
  582. entryDict->put(KEY_BITFIELD,
  583. util::toHex(ps->getBitfield(), ps->getBitfieldLength()));
  584. }
  585. }
  586. }
  587. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  588. if(requested_key(keys, KEY_PIECE_LENGTH)) {
  589. entryDict->put(KEY_PIECE_LENGTH, util::uitos(dctx->getPieceLength()));
  590. }
  591. if(requested_key(keys, KEY_NUM_PIECES)) {
  592. entryDict->put(KEY_NUM_PIECES, util::uitos(dctx->getNumPieces()));
  593. }
  594. if(requested_key(keys, KEY_FOLLOWED_BY)) {
  595. if(!group->followedBy().empty()) {
  596. SharedHandle<List> list = List::g();
  597. // The element is GID.
  598. for(std::vector<gid_t>::const_iterator i = group->followedBy().begin(),
  599. eoi = group->followedBy().end(); i != eoi; ++i) {
  600. list->append(util::itos(*i));
  601. }
  602. entryDict->put(KEY_FOLLOWED_BY, list);
  603. }
  604. }
  605. if(requested_key(keys, KEY_BELONGS_TO)) {
  606. if(group->belongsTo()) {
  607. entryDict->put(KEY_BELONGS_TO, util::itos(group->belongsTo()));
  608. }
  609. }
  610. if(requested_key(keys, KEY_FILES)) {
  611. SharedHandle<List> files = List::g();
  612. createFileEntry
  613. (files, dctx->getFileEntries().begin(), dctx->getFileEntries().end());
  614. entryDict->put(KEY_FILES, files);
  615. }
  616. if(requested_key(keys, KEY_DIR)) {
  617. entryDict->put(KEY_DIR, group->getOption()->get(PREF_DIR));
  618. }
  619. }
  620. #ifdef ENABLE_BITTORRENT
  621. void gatherBitTorrentMetadata
  622. (const SharedHandle<Dict>& btDict,
  623. const SharedHandle<TorrentAttribute>& torrentAttrs)
  624. {
  625. if(!torrentAttrs->comment.empty()) {
  626. btDict->put(KEY_COMMENT, torrentAttrs->comment);
  627. }
  628. if(torrentAttrs->creationDate) {
  629. btDict->put(KEY_CREATION_DATE, Integer::g(torrentAttrs->creationDate));
  630. }
  631. if(!torrentAttrs->mode.empty()) {
  632. btDict->put(KEY_MODE, torrentAttrs->mode);
  633. }
  634. SharedHandle<List> destAnnounceList = List::g();
  635. for(std::vector<std::vector<std::string> >::const_iterator l =
  636. torrentAttrs->announceList.begin(),
  637. eoi = torrentAttrs->announceList.end(); l != eoi; ++l) {
  638. SharedHandle<List> destAnnounceTier = List::g();
  639. for(std::vector<std::string>::const_iterator t = (*l).begin(),
  640. eoi2 = (*l).end(); t != eoi2; ++t) {
  641. destAnnounceTier->append(*t);
  642. }
  643. destAnnounceList->append(destAnnounceTier);
  644. }
  645. btDict->put(KEY_ANNOUNCE_LIST, destAnnounceList);
  646. if(!torrentAttrs->metadata.empty()) {
  647. SharedHandle<Dict> infoDict = Dict::g();
  648. infoDict->put(KEY_NAME, torrentAttrs->name);
  649. btDict->put(KEY_INFO, infoDict);
  650. }
  651. }
  652. namespace {
  653. void gatherProgressBitTorrent
  654. (const SharedHandle<Dict>& entryDict,
  655. const SharedHandle<TorrentAttribute>& torrentAttrs,
  656. const BtObject& btObject,
  657. const std::vector<std::string>& keys)
  658. {
  659. if(requested_key(keys, KEY_INFO_HASH)) {
  660. entryDict->put(KEY_INFO_HASH, util::toHex(torrentAttrs->infoHash));
  661. }
  662. if(requested_key(keys, KEY_BITTORRENT)) {
  663. SharedHandle<Dict> btDict = Dict::g();
  664. gatherBitTorrentMetadata(btDict, torrentAttrs);
  665. entryDict->put(KEY_BITTORRENT, btDict);
  666. }
  667. if(requested_key(keys, KEY_NUM_SEEDERS)) {
  668. if(btObject.isNull()) {
  669. entryDict->put(KEY_NUM_SEEDERS, VLB_ZERO);
  670. } else {
  671. SharedHandle<PeerStorage> peerStorage = btObject.peerStorage_;
  672. assert(peerStorage);
  673. std::vector<SharedHandle<Peer> > peers;
  674. peerStorage->getActivePeers(peers);
  675. entryDict->put(KEY_NUM_SEEDERS,
  676. util::uitos(countSeeder(peers.begin(), peers.end())));
  677. }
  678. }
  679. }
  680. } // namespace
  681. namespace {
  682. void gatherPeer
  683. (const SharedHandle<List>& peers, const SharedHandle<PeerStorage>& ps)
  684. {
  685. std::vector<SharedHandle<Peer> > activePeers;
  686. ps->getActivePeers(activePeers);
  687. for(std::vector<SharedHandle<Peer> >::const_iterator i =
  688. activePeers.begin(), eoi = activePeers.end(); i != eoi; ++i) {
  689. SharedHandle<Dict> peerEntry = Dict::g();
  690. peerEntry->put(KEY_PEER_ID, util::torrentPercentEncode((*i)->getPeerId(),
  691. PEER_ID_LENGTH));
  692. peerEntry->put(KEY_IP, (*i)->getIPAddress());
  693. if((*i)->isIncomingPeer()) {
  694. peerEntry->put(KEY_PORT, VLB_ZERO);
  695. } else {
  696. peerEntry->put(KEY_PORT, util::uitos((*i)->getPort()));
  697. }
  698. peerEntry->put(KEY_BITFIELD,
  699. util::toHex((*i)->getBitfield(), (*i)->getBitfieldLength()));
  700. peerEntry->put(KEY_AM_CHOKING, (*i)->amChoking()?VLB_TRUE:VLB_FALSE);
  701. peerEntry->put(KEY_PEER_CHOKING, (*i)->peerChoking()?VLB_TRUE:VLB_FALSE);
  702. TransferStat stat = ps->getTransferStatFor(*i);
  703. peerEntry->put(KEY_DOWNLOAD_SPEED, util::uitos(stat.getDownloadSpeed()));
  704. peerEntry->put(KEY_UPLOAD_SPEED, util::uitos(stat.getUploadSpeed()));
  705. peerEntry->put(KEY_SEEDER, (*i)->isSeeder()?VLB_TRUE:VLB_FALSE);
  706. peers->append(peerEntry);
  707. }
  708. }
  709. } // namespace
  710. #endif // ENABLE_BITTORRENT
  711. namespace {
  712. void gatherProgress
  713. (const SharedHandle<Dict>& entryDict,
  714. const SharedHandle<RequestGroup>& group,
  715. DownloadEngine* e,
  716. const std::vector<std::string>& keys)
  717. {
  718. gatherProgressCommon(entryDict, group, keys);
  719. #ifdef ENABLE_BITTORRENT
  720. if(group->getDownloadContext()->hasAttribute(bittorrent::BITTORRENT)) {
  721. SharedHandle<TorrentAttribute> torrentAttrs =
  722. bittorrent::getTorrentAttrs(group->getDownloadContext());
  723. BtObject btObject = e->getBtRegistry()->get(group->getGID());
  724. gatherProgressBitTorrent(entryDict, torrentAttrs, btObject, keys);
  725. }
  726. #endif // ENABLE_BITTORRENT
  727. }
  728. } // namespace
  729. void gatherStoppedDownload
  730. (const SharedHandle<Dict>& entryDict, const SharedHandle<DownloadResult>& ds,
  731. const std::vector<std::string>& keys)
  732. {
  733. if(requested_key(keys, KEY_GID)) {
  734. entryDict->put(KEY_GID, util::itos(ds->gid));
  735. }
  736. if(requested_key(keys, KEY_ERROR_CODE)) {
  737. entryDict->put(KEY_ERROR_CODE, util::itos(static_cast<int>(ds->result)));
  738. }
  739. if(requested_key(keys, KEY_STATUS)) {
  740. if(ds->result == error_code::IN_PROGRESS) {
  741. entryDict->put(KEY_STATUS, VLB_REMOVED);
  742. } else if(ds->result == error_code::FINISHED) {
  743. entryDict->put(KEY_STATUS, VLB_COMPLETE);
  744. } else {
  745. entryDict->put(KEY_STATUS, VLB_ERROR);
  746. }
  747. }
  748. if(requested_key(keys, KEY_FOLLOWED_BY)) {
  749. if(!ds->followedBy.empty()) {
  750. SharedHandle<List> list = List::g();
  751. // The element is GID.
  752. for(std::vector<gid_t>::const_iterator i = ds->followedBy.begin(),
  753. eoi = ds->followedBy.end(); i != eoi; ++i) {
  754. list->append(util::itos(*i));
  755. }
  756. entryDict->put(KEY_FOLLOWED_BY, list);
  757. }
  758. }
  759. if(requested_key(keys, KEY_BELONGS_TO)) {
  760. if(ds->belongsTo) {
  761. entryDict->put(KEY_BELONGS_TO, util::itos(ds->belongsTo));
  762. }
  763. }
  764. if(requested_key(keys, KEY_FILES)) {
  765. SharedHandle<List> files = List::g();
  766. createFileEntry(files, ds->fileEntries.begin(), ds->fileEntries.end());
  767. entryDict->put(KEY_FILES, files);
  768. }
  769. if(requested_key(keys, KEY_TOTAL_LENGTH)) {
  770. entryDict->put(KEY_TOTAL_LENGTH, util::uitos(ds->totalLength));
  771. }
  772. if(requested_key(keys, KEY_COMPLETED_LENGTH)) {
  773. entryDict->put(KEY_COMPLETED_LENGTH, util::uitos(ds->completedLength));
  774. }
  775. if(requested_key(keys, KEY_UPLOAD_LENGTH)) {
  776. entryDict->put(KEY_UPLOAD_LENGTH, util::uitos(ds->uploadLength));
  777. }
  778. if(requested_key(keys, KEY_BITFIELD)) {
  779. if(!ds->bitfieldStr.empty()) {
  780. entryDict->put(KEY_BITFIELD, ds->bitfieldStr);
  781. }
  782. }
  783. if(requested_key(keys, KEY_DOWNLOAD_SPEED)) {
  784. entryDict->put(KEY_DOWNLOAD_SPEED, VLB_ZERO);
  785. }
  786. if(requested_key(keys, KEY_UPLOAD_SPEED)) {
  787. entryDict->put(KEY_UPLOAD_SPEED, VLB_ZERO);
  788. }
  789. if(!ds->infoHashStr.empty()) {
  790. if(requested_key(keys, KEY_INFO_HASH)) {
  791. entryDict->put(KEY_INFO_HASH, ds->infoHashStr);
  792. }
  793. if(requested_key(keys, KEY_NUM_SEEDERS)) {
  794. entryDict->put(KEY_NUM_SEEDERS, VLB_ZERO);
  795. }
  796. }
  797. if(requested_key(keys, KEY_PIECE_LENGTH)) {
  798. entryDict->put(KEY_PIECE_LENGTH, util::uitos(ds->pieceLength));
  799. }
  800. if(requested_key(keys, KEY_NUM_PIECES)) {
  801. entryDict->put(KEY_NUM_PIECES, util::uitos(ds->numPieces));
  802. }
  803. if(requested_key(keys, KEY_CONNECTIONS)) {
  804. entryDict->put(KEY_CONNECTIONS, VLB_ZERO);
  805. }
  806. if(requested_key(keys, KEY_DIR)) {
  807. entryDict->put(KEY_DIR, ds->dir);
  808. }
  809. }
  810. SharedHandle<ValueBase> GetFilesRpcMethod::process
  811. (const RpcRequest& req, DownloadEngine* e)
  812. {
  813. gid_t gid = getRequiredGidParam(req, 0);
  814. SharedHandle<List> files = List::g();
  815. SharedHandle<RequestGroup> group =
  816. findRequestGroup(e->getRequestGroupMan(), gid);
  817. if(!group) {
  818. SharedHandle<DownloadResult> dr =
  819. e->getRequestGroupMan()->findDownloadResult(gid);
  820. if(!dr) {
  821. throw DL_ABORT_EX
  822. (fmt("No file data is available for GID#%s",
  823. util::itos(gid).c_str()));
  824. } else {
  825. createFileEntry(files, dr->fileEntries.begin(), dr->fileEntries.end());
  826. }
  827. } else {
  828. createFileEntry(files,
  829. group->getDownloadContext()->getFileEntries().begin(),
  830. group->getDownloadContext()->getFileEntries().end());
  831. }
  832. return files;
  833. }
  834. SharedHandle<ValueBase> GetUrisRpcMethod::process
  835. (const RpcRequest& req, DownloadEngine* e)
  836. {
  837. gid_t gid = getRequiredGidParam(req, 0);
  838. SharedHandle<RequestGroup> group =
  839. findRequestGroup(e->getRequestGroupMan(), gid);
  840. if(!group) {
  841. throw DL_ABORT_EX
  842. (fmt("No URI data is available for GID#%s",
  843. util::itos(gid).c_str()));
  844. }
  845. SharedHandle<List> uriList = List::g();
  846. // TODO Current implementation just returns first FileEntry's URIs.
  847. if(!group->getDownloadContext()->getFileEntries().empty()) {
  848. createUriEntry(uriList, group->getDownloadContext()->getFirstFileEntry());
  849. }
  850. return uriList;
  851. }
  852. #ifdef ENABLE_BITTORRENT
  853. SharedHandle<ValueBase> GetPeersRpcMethod::process
  854. (const RpcRequest& req, DownloadEngine* e)
  855. {
  856. gid_t gid = getRequiredGidParam(req, 0);
  857. SharedHandle<RequestGroup> group =
  858. findRequestGroup(e->getRequestGroupMan(), gid);
  859. if(!group) {
  860. throw DL_ABORT_EX
  861. (fmt("No peer data is available for GID#%s",
  862. util::itos(gid).c_str()));
  863. }
  864. SharedHandle<List> peers = List::g();
  865. BtObject btObject = e->getBtRegistry()->get(group->getGID());
  866. if(!btObject.isNull()) {
  867. assert(btObject.peerStorage_);
  868. gatherPeer(peers, btObject.peerStorage_);
  869. }
  870. return peers;
  871. }
  872. #endif // ENABLE_BITTORRENT
  873. SharedHandle<ValueBase> TellStatusRpcMethod::process
  874. (const RpcRequest& req, DownloadEngine* e)
  875. {
  876. gid_t gid = getRequiredGidParam(req, 0);
  877. const List* keysParam = req.getListParam(1);
  878. std::vector<std::string> keys;
  879. toStringList(std::back_inserter(keys), keysParam);
  880. SharedHandle<RequestGroup> group =
  881. e->getRequestGroupMan()->findRequestGroup(gid);
  882. SharedHandle<Dict> entryDict = Dict::g();
  883. if(!group) {
  884. group = e->getRequestGroupMan()->findReservedGroup(gid);
  885. if(!group) {
  886. SharedHandle<DownloadResult> ds =
  887. e->getRequestGroupMan()->findDownloadResult(gid);
  888. if(!ds) {
  889. throw DL_ABORT_EX
  890. (fmt("No such download for GID#%s",
  891. util::itos(gid).c_str()));
  892. }
  893. gatherStoppedDownload(entryDict, ds, keys);
  894. } else {
  895. if(requested_key(keys, KEY_STATUS)) {
  896. if(group->isPauseRequested()) {
  897. entryDict->put(KEY_STATUS, VLB_PAUSED);
  898. } else {
  899. entryDict->put(KEY_STATUS, VLB_WAITING);
  900. }
  901. }
  902. gatherProgress(entryDict, group, e, keys);
  903. }
  904. } else {
  905. if(requested_key(keys, KEY_STATUS)) {
  906. entryDict->put(KEY_STATUS, VLB_ACTIVE);
  907. }
  908. gatherProgress(entryDict, group, e, keys);
  909. }
  910. return entryDict;
  911. }
  912. SharedHandle<ValueBase> TellActiveRpcMethod::process
  913. (const RpcRequest& req, DownloadEngine* e)
  914. {
  915. const List* keysParam = req.getListParam(0);
  916. std::vector<std::string> keys;
  917. toStringList(std::back_inserter(keys), keysParam);
  918. SharedHandle<List> list = List::g();
  919. const std::deque<SharedHandle<RequestGroup> >& groups =
  920. e->getRequestGroupMan()->getRequestGroups();
  921. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  922. groups.begin(), eoi = groups.end(); i != eoi; ++i) {
  923. SharedHandle<Dict> entryDict = Dict::g();
  924. if(requested_key(keys, KEY_STATUS)) {
  925. entryDict->put(KEY_STATUS, VLB_ACTIVE);
  926. }
  927. gatherProgress(entryDict, *i, e, keys);
  928. list->append(entryDict);
  929. }
  930. return list;
  931. }
  932. const std::deque<SharedHandle<RequestGroup> >&
  933. TellWaitingRpcMethod::getItems(DownloadEngine* e) const
  934. {
  935. return e->getRequestGroupMan()->getReservedGroups();
  936. }
  937. void TellWaitingRpcMethod::createEntry
  938. (const SharedHandle<Dict>& entryDict,
  939. const SharedHandle<RequestGroup>& item,
  940. DownloadEngine* e,
  941. const std::vector<std::string>& keys) const
  942. {
  943. if(requested_key(keys, KEY_STATUS)) {
  944. if(item->isPauseRequested()) {
  945. entryDict->put(KEY_STATUS, VLB_PAUSED);
  946. } else {
  947. entryDict->put(KEY_STATUS, VLB_WAITING);
  948. }
  949. }
  950. gatherProgress(entryDict, item, e, keys);
  951. }
  952. const std::deque<SharedHandle<DownloadResult> >&
  953. TellStoppedRpcMethod::getItems(DownloadEngine* e) const
  954. {
  955. return e->getRequestGroupMan()->getDownloadResults();
  956. }
  957. void TellStoppedRpcMethod::createEntry
  958. (const SharedHandle<Dict>& entryDict,
  959. const SharedHandle<DownloadResult>& item,
  960. DownloadEngine* e,
  961. const std::vector<std::string>& keys) const
  962. {
  963. gatherStoppedDownload(entryDict, item, keys);
  964. }
  965. SharedHandle<ValueBase> PurgeDownloadResultRpcMethod::process
  966. (const RpcRequest& req, DownloadEngine* e)
  967. {
  968. e->getRequestGroupMan()->purgeDownloadResult();
  969. return VLB_OK;
  970. }
  971. SharedHandle<ValueBase> RemoveDownloadResultRpcMethod::process
  972. (const RpcRequest& req, DownloadEngine* e)
  973. {
  974. gid_t gid = getRequiredGidParam(req, 0);
  975. if(!e->getRequestGroupMan()->removeDownloadResult(gid)) {
  976. throw DL_ABORT_EX
  977. (fmt("Could not remove download result of GID#%s",
  978. util::itos(gid).c_str()));
  979. }
  980. return VLB_OK;
  981. }
  982. SharedHandle<ValueBase> ChangeOptionRpcMethod::process
  983. (const RpcRequest& req, DownloadEngine* e)
  984. {
  985. gid_t gid = getRequiredGidParam(req, 0);
  986. SharedHandle<RequestGroup> group =
  987. findRequestGroup(e->getRequestGroupMan(), gid);
  988. if(!group) {
  989. throw DL_ABORT_EX
  990. (fmt("Cannot change option for GID#%s",
  991. util::itos(gid).c_str()));
  992. }
  993. SharedHandle<Option> option(new Option());
  994. const Dict* optionsParam = req.getDictParam(1);
  995. if(optionsParam) {
  996. gatherChangeableOption(option, optionsParam);
  997. applyChangeableOption(group->getOption().get(), option.get());
  998. if(option->defined(PREF_MAX_DOWNLOAD_LIMIT)) {
  999. group->setMaxDownloadSpeedLimit
  1000. (option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
  1001. }
  1002. if(option->defined(PREF_MAX_UPLOAD_LIMIT)) {
  1003. group->setMaxUploadSpeedLimit(option->getAsInt(PREF_MAX_UPLOAD_LIMIT));
  1004. }
  1005. #ifdef ENABLE_BITTORRENT
  1006. BtObject btObject = e->getBtRegistry()->get(group->getGID());
  1007. if(!btObject.isNull()) {
  1008. if(option->defined(PREF_BT_MAX_PEERS)) {
  1009. btObject.btRuntime_->setMaxPeers(option->getAsInt(PREF_BT_MAX_PEERS));
  1010. }
  1011. }
  1012. #endif // ENABLE_BITTORRENT
  1013. }
  1014. return VLB_OK;
  1015. }
  1016. SharedHandle<ValueBase> ChangeGlobalOptionRpcMethod::process
  1017. (const RpcRequest& req, DownloadEngine* e)
  1018. {
  1019. const Dict* optionsParam = req.getDictParam(0);
  1020. if(!optionsParam) {
  1021. return VLB_OK;
  1022. }
  1023. SharedHandle<Option> option(new Option());
  1024. gatherChangeableGlobalOption(option, optionsParam);
  1025. applyChangeableGlobalOption(e->getOption(), option.get());
  1026. if(option->defined(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)) {
  1027. e->getRequestGroupMan()->setMaxOverallDownloadSpeedLimit
  1028. (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT));
  1029. }
  1030. if(option->defined(PREF_MAX_OVERALL_UPLOAD_LIMIT)) {
  1031. e->getRequestGroupMan()->setMaxOverallUploadSpeedLimit
  1032. (option->getAsInt(PREF_MAX_OVERALL_UPLOAD_LIMIT));
  1033. }
  1034. if(option->defined(PREF_MAX_CONCURRENT_DOWNLOADS)) {
  1035. e->getRequestGroupMan()->setMaxSimultaneousDownloads
  1036. (option->getAsInt(PREF_MAX_CONCURRENT_DOWNLOADS));
  1037. e->getRequestGroupMan()->requestQueueCheck();
  1038. }
  1039. if(option->defined(PREF_LOG_LEVEL)) {
  1040. LogFactory::setLogLevel(option->get(PREF_LOG_LEVEL));
  1041. }
  1042. if(option->defined(PREF_LOG)) {
  1043. LogFactory::setLogFile(option->get(PREF_LOG));
  1044. try {
  1045. LogFactory::reconfigure();
  1046. } catch(RecoverableException& e) {
  1047. // TODO no exception handling
  1048. }
  1049. }
  1050. return VLB_OK;
  1051. }
  1052. SharedHandle<ValueBase> GetVersionRpcMethod::process
  1053. (const RpcRequest& req, DownloadEngine* e)
  1054. {
  1055. SharedHandle<Dict> result = Dict::g();
  1056. result->put(KEY_VERSION, PACKAGE_VERSION);
  1057. SharedHandle<List> featureList = List::g();
  1058. const FeatureMap& features = FeatureConfig::getInstance()->getFeatures();
  1059. for(FeatureMap::const_iterator i = features.begin(), eoi = features.end();
  1060. i != eoi;++i){
  1061. if((*i).second) {
  1062. featureList->append((*i).first);
  1063. }
  1064. }
  1065. result->put(KEY_ENABLED_FEATURES, featureList);
  1066. return result;
  1067. }
  1068. namespace {
  1069. template<typename InputIterator>
  1070. void pushRequestOption
  1071. (const SharedHandle<Dict>& dict,
  1072. InputIterator optionFirst, InputIterator optionLast)
  1073. {
  1074. const std::set<std::string>& requestOptions = listRequestOptions();
  1075. for(; optionFirst != optionLast; ++optionFirst) {
  1076. if(requestOptions.count((*optionFirst).first)) {
  1077. dict->put((*optionFirst).first, (*optionFirst).second);
  1078. }
  1079. }
  1080. }
  1081. } // namespace
  1082. SharedHandle<ValueBase> GetOptionRpcMethod::process
  1083. (const RpcRequest& req, DownloadEngine* e)
  1084. {
  1085. gid_t gid = getRequiredGidParam(req, 0);
  1086. SharedHandle<RequestGroup> group =
  1087. findRequestGroup(e->getRequestGroupMan(), gid);
  1088. if(!group) {
  1089. throw DL_ABORT_EX
  1090. (fmt("Cannot get option for GID#%s",
  1091. util::itos(gid).c_str()));
  1092. }
  1093. SharedHandle<Dict> result = Dict::g();
  1094. SharedHandle<Option> option = group->getOption();
  1095. pushRequestOption(result, option->begin(), option->end());
  1096. return result;
  1097. }
  1098. SharedHandle<ValueBase> GetGlobalOptionRpcMethod::process
  1099. (const RpcRequest& req, DownloadEngine* e)
  1100. {
  1101. SharedHandle<Dict> result = Dict::g();
  1102. for(std::map<std::string, std::string>::const_iterator i =
  1103. e->getOption()->begin(), eoi = e->getOption()->end(); i != eoi; ++i) {
  1104. SharedHandle<OptionHandler> h = getOptionParser()->findByName((*i).first);
  1105. if(h && !h->isHidden()) {
  1106. result->put((*i).first, (*i).second);
  1107. }
  1108. }
  1109. return result;
  1110. }
  1111. SharedHandle<ValueBase> ChangePositionRpcMethod::process
  1112. (const RpcRequest& req, DownloadEngine* e)
  1113. {
  1114. gid_t gid = getRequiredGidParam(req, 0);
  1115. const Integer* posParam = req.getIntegerParam(1);
  1116. const String* howParam = req.getStringParam(2);
  1117. if(!posParam || !howParam) {
  1118. throw DL_ABORT_EX("Illegal argument.");
  1119. }
  1120. int pos = posParam->i();
  1121. const std::string& howStr = howParam->s();
  1122. RequestGroupMan::HOW how;
  1123. if(howStr == "POS_SET") {
  1124. how = RequestGroupMan::POS_SET;
  1125. } else if(howStr == "POS_CUR") {
  1126. how = RequestGroupMan::POS_CUR;
  1127. } else if(howStr == "POS_END") {
  1128. how = RequestGroupMan::POS_END;
  1129. } else {
  1130. throw DL_ABORT_EX("Illegal argument.");
  1131. }
  1132. size_t destPos =
  1133. e->getRequestGroupMan()->changeReservedGroupPosition(gid, pos, how);
  1134. SharedHandle<Integer> result = Integer::g(destPos);
  1135. return result;
  1136. }
  1137. SharedHandle<ValueBase> GetSessionInfoRpcMethod::process
  1138. (const RpcRequest& req, DownloadEngine* e)
  1139. {
  1140. SharedHandle<Dict> result = Dict::g();
  1141. result->put(KEY_SESSION_ID, util::toHex(e->getSessionId()));
  1142. return result;
  1143. }
  1144. SharedHandle<ValueBase> GetServersRpcMethod::process
  1145. (const RpcRequest& req, DownloadEngine* e)
  1146. {
  1147. gid_t gid = getRequiredGidParam(req, 0);
  1148. SharedHandle<RequestGroup> group =
  1149. e->getRequestGroupMan()->findRequestGroup(gid);
  1150. if(!group) {
  1151. throw DL_ABORT_EX(fmt("No active download for GID#%s",
  1152. util::itos(gid).c_str()));
  1153. }
  1154. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  1155. const std::vector<SharedHandle<FileEntry> >& files = dctx->getFileEntries();
  1156. SharedHandle<List> result = List::g();
  1157. size_t index = 1;
  1158. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi = files.begin(),
  1159. eoi = files.end(); fi != eoi; ++fi, ++index) {
  1160. SharedHandle<Dict> fileEntry = Dict::g();
  1161. fileEntry->put(KEY_INDEX, util::uitos(index));
  1162. SharedHandle<List> servers = List::g();
  1163. const std::deque<SharedHandle<Request> >& requests =
  1164. (*fi)->getInFlightRequests();
  1165. for(std::deque<SharedHandle<Request> >::const_iterator ri =requests.begin(),
  1166. eoi = requests.end(); ri != eoi; ++ri) {
  1167. SharedHandle<PeerStat> ps = (*ri)->getPeerStat();
  1168. if(ps) {
  1169. SharedHandle<Dict> serverEntry = Dict::g();
  1170. serverEntry->put(KEY_URI, (*ri)->getUri());
  1171. serverEntry->put(KEY_CURRENT_URI, (*ri)->getCurrentUri());
  1172. serverEntry->put(KEY_DOWNLOAD_SPEED,
  1173. util::uitos(ps->calculateDownloadSpeed()));
  1174. servers->append(serverEntry);
  1175. }
  1176. }
  1177. fileEntry->put(KEY_SERVERS, servers);
  1178. result->append(fileEntry);
  1179. }
  1180. return result;
  1181. }
  1182. SharedHandle<ValueBase> ChangeUriRpcMethod::process
  1183. (const RpcRequest& req, DownloadEngine* e)
  1184. {
  1185. gid_t gid = getRequiredGidParam(req, 0);
  1186. const Integer* indexParam = req.getIntegerParam(1);
  1187. const List* delUrisParam = req.getListParam(2);
  1188. const List* addUrisParam = req.getListParam(3);
  1189. if(!indexParam || !delUrisParam || ! addUrisParam) {
  1190. throw DL_ABORT_EX("Bad request");
  1191. }
  1192. size_t pos = 0;
  1193. bool posGiven = false;
  1194. getPosParam(req, 4, posGiven, pos);
  1195. size_t index = indexParam->i()-1;
  1196. SharedHandle<RequestGroup> group =
  1197. findRequestGroup(e->getRequestGroupMan(), gid);
  1198. if(!group) {
  1199. throw DL_ABORT_EX
  1200. (fmt("Cannot remove URIs from GID#%s",
  1201. util::itos(gid).c_str()));
  1202. }
  1203. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  1204. const std::vector<SharedHandle<FileEntry> >& files = dctx->getFileEntries();
  1205. if(files.size() <= index) {
  1206. throw DL_ABORT_EX(fmt("fileIndex is out of range"));
  1207. }
  1208. SharedHandle<FileEntry> s = files[index];
  1209. size_t delcount = 0;
  1210. for(List::ValueType::const_iterator i = delUrisParam->begin(),
  1211. eoi = delUrisParam->end(); i != eoi; ++i) {
  1212. const String* uri = asString(*i);
  1213. if(uri && s->removeUri(uri->s())) {
  1214. ++delcount;
  1215. }
  1216. }
  1217. size_t addcount = 0;
  1218. if(posGiven) {
  1219. for(List::ValueType::const_iterator i = addUrisParam->begin(),
  1220. eoi = addUrisParam->end(); i != eoi; ++i) {
  1221. const String* uri = asString(*i);
  1222. if(uri && s->insertUri(uri->s(), pos)) {
  1223. ++addcount;
  1224. ++pos;
  1225. }
  1226. }
  1227. } else {
  1228. for(List::ValueType::const_iterator i = addUrisParam->begin(),
  1229. eoi = addUrisParam->end(); i != eoi; ++i) {
  1230. const String* uri = asString(*i);
  1231. if(uri && s->addUri(uri->s())) {
  1232. ++addcount;
  1233. }
  1234. }
  1235. }
  1236. if(addcount && group->getPieceStorage()) {
  1237. std::vector<Command*> commands;
  1238. group->createNextCommand(commands, e);
  1239. e->addCommand(commands);
  1240. group->getSegmentMan()->recognizeSegmentFor(s);
  1241. }
  1242. SharedHandle<List> res = List::g();
  1243. res->append(Integer::g(delcount));
  1244. res->append(Integer::g(addcount));
  1245. return res;
  1246. }
  1247. namespace {
  1248. SharedHandle<ValueBase> goingShutdown
  1249. (const RpcRequest& req, DownloadEngine* e, bool forceHalt)
  1250. {
  1251. // Schedule shutdown after 3seconds to give time to client to
  1252. // receive RPC response.
  1253. e->addRoutineCommand(new TimedHaltCommand(e->newCUID(), e, 3, forceHalt));
  1254. A2_LOG_INFO("Scheduled shutdown in 3 seconds.");
  1255. return VLB_OK;
  1256. }
  1257. } // namespace
  1258. SharedHandle<ValueBase> ShutdownRpcMethod::process
  1259. (const RpcRequest& req, DownloadEngine* e)
  1260. {
  1261. return goingShutdown(req, e, false);
  1262. }
  1263. SharedHandle<ValueBase> ForceShutdownRpcMethod::process
  1264. (const RpcRequest& req, DownloadEngine* e)
  1265. {
  1266. return goingShutdown(req, e, true);
  1267. }
  1268. SharedHandle<ValueBase> SystemMulticallRpcMethod::process
  1269. (const RpcRequest& req, DownloadEngine* e)
  1270. {
  1271. const List* methodSpecs = req.getListParam(0);
  1272. if(!methodSpecs) {
  1273. throw DL_ABORT_EX("Illegal argument. One item list is expected.");
  1274. }
  1275. SharedHandle<List> list = List::g();
  1276. for(List::ValueType::const_iterator i = methodSpecs->begin(),
  1277. eoi = methodSpecs->end(); i != eoi; ++i) {
  1278. const Dict* methodDict = asDict(*i);
  1279. if(!methodDict) {
  1280. list->append(createErrorResponse
  1281. (DL_ABORT_EX("system.multicall expected struct.")));
  1282. continue;
  1283. }
  1284. const String* methodName = asString(methodDict->get(KEY_METHOD_NAME));
  1285. const List* paramsList = asList(methodDict->get(KEY_PARAMS));
  1286. if(!methodName || !paramsList) {
  1287. list->append(createErrorResponse
  1288. (DL_ABORT_EX("Missing methodName or params.")));
  1289. continue;
  1290. }
  1291. if(methodName->s() == getMethodName()) {
  1292. list->append(createErrorResponse
  1293. (DL_ABORT_EX("Recursive system.multicall forbidden.")));
  1294. continue;
  1295. }
  1296. SharedHandle<RpcMethod> method = RpcMethodFactory::create(methodName->s());
  1297. method->setJsonRpc(getJsonRpc());
  1298. RpcRequest innerReq
  1299. (methodName->s(), static_pointer_cast<List>(methodDict->get(KEY_PARAMS)));
  1300. RpcResponse res = method->execute(innerReq, e);
  1301. if(res.code == 0) {
  1302. SharedHandle<List> l = List::g();
  1303. l->append(res.param);
  1304. list->append(l);
  1305. } else {
  1306. list->append(res.param);
  1307. }
  1308. }
  1309. return list;
  1310. }
  1311. SharedHandle<ValueBase> NoSuchMethodRpcMethod::process
  1312. (const RpcRequest& req, DownloadEngine* e)
  1313. {
  1314. throw DL_ABORT_EX(fmt("No such method: %s", req.methodName.c_str()));
  1315. }
  1316. } // namespace rpc
  1317. } // namespace aria2