RpcMethodImpl.cc 50 KB

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