RpcMethodImpl.cc 50 KB

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