RpcMethodImpl.cc 49 KB

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