RpcMethodImpl.cc 48 KB

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