RpcMethodImpl.cc 49 KB

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