XmlRpcMethodImpl.cc 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  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 "XmlRpcMethodImpl.h"
  36. #include <cassert>
  37. #include <algorithm>
  38. #include "Logger.h"
  39. #include "LogFactory.h"
  40. #include "DlAbortEx.h"
  41. #include "Option.h"
  42. #include "OptionParser.h"
  43. #include "OptionHandler.h"
  44. #include "DownloadEngine.h"
  45. #include "RequestGroup.h"
  46. #include "download_helper.h"
  47. #include "util.h"
  48. #include "RequestGroupMan.h"
  49. #include "StringFormat.h"
  50. #include "XmlRpcRequest.h"
  51. #include "PieceStorage.h"
  52. #include "DownloadContext.h"
  53. #include "DiskAdaptor.h"
  54. #include "FileEntry.h"
  55. #include "BtProgressInfoFile.h"
  56. #include "prefs.h"
  57. #include "message.h"
  58. #include "FeatureConfig.h"
  59. #include "array_fun.h"
  60. #include "XmlRpcMethodFactory.h"
  61. #include "XmlRpcResponse.h"
  62. #include "SegmentMan.h"
  63. #include "TimedHaltCommand.h"
  64. #include "ServerStatMan.h"
  65. #include "FileAllocationEntry.h"
  66. #include "CheckIntegrityEntry.h"
  67. #include "Segment.h"
  68. #ifdef ENABLE_BITTORRENT
  69. # include "bittorrent_helper.h"
  70. # include "BtRegistry.h"
  71. # include "PeerStorage.h"
  72. # include "Peer.h"
  73. # include "BtRuntime.h"
  74. # include "BtAnnounce.h"
  75. #endif // ENABLE_BITTORRENT
  76. namespace aria2 {
  77. namespace xmlrpc {
  78. namespace {
  79. const SharedHandle<String> VLB_TRUE = String::g("true");
  80. const SharedHandle<String> VLB_FALSE = String::g("false");
  81. const SharedHandle<String> VLB_OK = String::g("OK");
  82. const SharedHandle<String> VLB_ACTIVE = String::g("active");
  83. const SharedHandle<String> VLB_WAITING = String::g("waiting");
  84. const SharedHandle<String> VLB_PAUSED = String::g("paused");
  85. const SharedHandle<String> VLB_REMOVED = String::g("removed");
  86. const SharedHandle<String> VLB_ERROR = String::g("error");
  87. const SharedHandle<String> VLB_COMPLETE = String::g("complete");
  88. const SharedHandle<String> VLB_USED = String::g("used");
  89. const SharedHandle<String> VLB_ZERO = String::g("0");
  90. const std::string KEY_GID = "gid";
  91. const std::string KEY_ERROR_CODE = "errorCode";
  92. const std::string KEY_STATUS = "status";
  93. const std::string KEY_TOTAL_LENGTH = "totalLength";
  94. const std::string KEY_COMPLETED_LENGTH = "completedLength";
  95. const std::string KEY_DOWNLOAD_SPEED = "downloadSpeed";
  96. const std::string KEY_UPLOAD_SPEED = "uploadSpeed";
  97. const std::string KEY_UPLOAD_LENGTH = "uploadLength";
  98. const std::string KEY_CONNECTIONS = "connections";
  99. const std::string KEY_BITFIELD = "bitfield";
  100. const std::string KEY_PIECE_LENGTH = "pieceLength";
  101. const std::string KEY_NUM_PIECES = "numPieces";
  102. const std::string KEY_FOLLOWED_BY = "followedBy";
  103. const std::string KEY_BELONGS_TO = "belongsTo";
  104. const std::string KEY_INFO_HASH = "infoHash";
  105. const std::string KEY_NUM_SEEDERS = "numSeeders";
  106. const std::string KEY_PEER_ID = "peerId";
  107. const std::string KEY_IP = "ip";
  108. const std::string KEY_PORT = "port";
  109. const std::string KEY_AM_CHOKING = "amChoking";
  110. const std::string KEY_PEER_CHOKING = "peerChoking";
  111. const std::string KEY_SEEDER = "seeder";
  112. const std::string KEY_INDEX = "index";
  113. const std::string KEY_PATH = "path";
  114. const std::string KEY_SELECTED = "selected";
  115. const std::string KEY_LENGTH = "length";
  116. const std::string KEY_URI = "uri";
  117. const std::string KEY_CURRENT_URI = "currentUri";
  118. const std::string KEY_VERSION = "version";
  119. const std::string KEY_ENABLED_FEATURES = "enabledFeatures";
  120. const std::string KEY_METHOD_NAME = "methodName";
  121. const std::string KEY_PARAMS = "params";
  122. const std::string KEY_SESSION_ID = "sessionId";
  123. const std::string KEY_FILES = "files";
  124. const std::string KEY_DIR = "dir";
  125. const std::string KEY_URIS = "uris";
  126. const std::string KEY_BITTORRENT = "bittorrent";
  127. const std::string KEY_INFO = "info";
  128. const std::string KEY_NAME = "name";
  129. const std::string KEY_ANNOUNCE_LIST = "announceList";
  130. const std::string KEY_COMMENT = "comment";
  131. const std::string KEY_CREATION_DATE = "creationDate";
  132. const std::string KEY_MODE = "mode";
  133. const std::string KEY_SERVERS = "servers";
  134. }
  135. static SharedHandle<ValueBase> createGIDResponse(gid_t gid)
  136. {
  137. return String::g(util::itos(gid));
  138. }
  139. static SharedHandle<ValueBase>
  140. addRequestGroup(const SharedHandle<RequestGroup>& group,
  141. DownloadEngine* e,
  142. bool posGiven, int pos)
  143. {
  144. if(posGiven) {
  145. e->getRequestGroupMan()->insertReservedGroup(pos, group);
  146. } else {
  147. e->getRequestGroupMan()->addReservedGroup(group);
  148. }
  149. return createGIDResponse(group->getGID());
  150. }
  151. static
  152. SharedHandle<RequestGroup>
  153. findRequestGroup(const SharedHandle<RequestGroupMan>& rgman, gid_t gid)
  154. {
  155. SharedHandle<RequestGroup> group = rgman->findRequestGroup(gid);
  156. if(group.isNull()) {
  157. group = rgman->findReservedGroup(gid);
  158. }
  159. return group;
  160. }
  161. static const String* getStringParam
  162. (const SharedHandle<List>& params, size_t index)
  163. {
  164. const String* stringParam = 0;
  165. if(params->size() > index) {
  166. stringParam = asString(params->get(index));
  167. }
  168. return stringParam;
  169. }
  170. static const Integer* getIntegerParam
  171. (const SharedHandle<List>& params, size_t index)
  172. {
  173. const Integer* integerParam = 0;
  174. if(params->size() > index) {
  175. integerParam = asInteger(params->get(index));
  176. }
  177. return integerParam;
  178. }
  179. static const List* getListParam(const SharedHandle<List>& params, size_t index)
  180. {
  181. const List* listParam = 0;
  182. if(params->size() > index) {
  183. listParam = asList(params->get(index));
  184. }
  185. return listParam;
  186. }
  187. static const Dict* getDictParam(const SharedHandle<List>& params, size_t index)
  188. {
  189. const Dict* dictParam = 0;
  190. if(params->size() > index) {
  191. dictParam = asDict(params->get(index));
  192. }
  193. return dictParam;
  194. }
  195. static void getPosParam(const SharedHandle<List>& params, size_t posParamIndex,
  196. bool& posGiven, size_t& pos)
  197. {
  198. if(params->size() > posParamIndex) {
  199. const Integer* p = asInteger(params->get(posParamIndex));
  200. if(p) {
  201. if(p->i() >= 0) {
  202. pos = p->i();
  203. posGiven = true;
  204. return;
  205. } else {
  206. throw DL_ABORT_EX("Position must be greater than or equal to 0.");
  207. }
  208. }
  209. }
  210. posGiven = false;
  211. }
  212. static gid_t getRequiredGidParam
  213. (const SharedHandle<List>& params, size_t posParamIndex)
  214. {
  215. const String* gidParam = getStringParam(params, posParamIndex);
  216. if(gidParam) {
  217. return util::parseLLInt(gidParam->s());
  218. } else {
  219. throw DL_ABORT_EX(MSG_GID_NOT_PROVIDED);
  220. }
  221. }
  222. template<typename OutputIterator>
  223. static void extractUris(OutputIterator out, const List* src)
  224. {
  225. if(src) {
  226. for(List::ValueType::const_iterator i = src->begin(), eoi = src->end();
  227. i != eoi; ++i) {
  228. const String* uri = asString(*i);
  229. if(uri) {
  230. out++ = uri->s();
  231. }
  232. }
  233. }
  234. }
  235. SharedHandle<ValueBase> AddUriXmlRpcMethod::process
  236. (const XmlRpcRequest& req, DownloadEngine* e)
  237. {
  238. const SharedHandle<List>& params = req.params;
  239. std::vector<std::string> uris;
  240. extractUris(std::back_inserter(uris), getListParam(params, 0));
  241. if(uris.empty()) {
  242. throw DL_ABORT_EX("URI is not provided.");
  243. }
  244. SharedHandle<Option> requestOption(new Option(*e->getOption()));
  245. gatherRequestOption(requestOption, getDictParam(params, 1));
  246. size_t pos = 0;
  247. bool posGiven = false;
  248. getPosParam(params, 2, posGiven, pos);
  249. std::vector<SharedHandle<RequestGroup> > result;
  250. createRequestGroupForUri(result, requestOption, uris,
  251. /* ignoreForceSeq = */ true,
  252. /* ignoreLocalPath = */ true);
  253. if(!result.empty()) {
  254. return addRequestGroup(result.front(), e, posGiven, pos);
  255. } else {
  256. throw DL_ABORT_EX("No URI to download.");
  257. }
  258. }
  259. #ifdef ENABLE_BITTORRENT
  260. SharedHandle<ValueBase> AddTorrentXmlRpcMethod::process
  261. (const XmlRpcRequest& req, DownloadEngine* e)
  262. {
  263. const SharedHandle<List>& params = req.params;
  264. const String* torrentParam = getStringParam(params, 0);
  265. if(!torrentParam) {
  266. throw DL_ABORT_EX("Torrent data is not provided.");
  267. }
  268. std::vector<std::string> uris;
  269. extractUris(std::back_inserter(uris), getListParam(params, 1));
  270. SharedHandle<Option> requestOption(new Option(*e->getOption()));
  271. gatherRequestOption(requestOption, getDictParam(params, 2));
  272. size_t pos = 0;
  273. bool posGiven = false;
  274. getPosParam(params, 3, posGiven, pos);
  275. std::vector<SharedHandle<RequestGroup> > result;
  276. createRequestGroupForBitTorrent(result, requestOption,
  277. uris, torrentParam->s());
  278. if(!result.empty()) {
  279. return addRequestGroup(result.front(), e, posGiven, pos);
  280. } else {
  281. throw DL_ABORT_EX("No Torrent to download.");
  282. }
  283. }
  284. #endif // ENABLE_BITTORRENT
  285. #ifdef ENABLE_METALINK
  286. SharedHandle<ValueBase> AddMetalinkXmlRpcMethod::process
  287. (const XmlRpcRequest& req, DownloadEngine* e)
  288. {
  289. const SharedHandle<List>& params = req.params;
  290. const String* metalinkParam = getStringParam(params, 0);
  291. if(!metalinkParam) {
  292. throw DL_ABORT_EX("Metalink data is not provided.");
  293. }
  294. SharedHandle<Option> requestOption(new Option(*e->getOption()));
  295. gatherRequestOption(requestOption, getDictParam(params, 1));
  296. size_t pos = 0;
  297. bool posGiven = false;
  298. getPosParam(params, 2, posGiven, pos);
  299. std::vector<SharedHandle<RequestGroup> > result;
  300. createRequestGroupForMetalink(result, requestOption, metalinkParam->s());
  301. SharedHandle<List> gids = List::g();
  302. if(!result.empty()) {
  303. if(posGiven) {
  304. e->getRequestGroupMan()->insertReservedGroup(pos, result);
  305. } else {
  306. e->getRequestGroupMan()->addReservedGroup(result);
  307. }
  308. for(std::vector<SharedHandle<RequestGroup> >::const_iterator i =
  309. result.begin(), eoi = result.end(); i != eoi; ++i) {
  310. gids->append(util::itos((*i)->getGID()));
  311. }
  312. }
  313. return gids;
  314. }
  315. #endif // ENABLE_METALINK
  316. static SharedHandle<ValueBase> removeDownload
  317. (const XmlRpcRequest& req, DownloadEngine* e, bool forceRemove)
  318. {
  319. const SharedHandle<List>& params = req.params;
  320. gid_t gid = getRequiredGidParam(params, 0);
  321. SharedHandle<RequestGroup> group =
  322. e->getRequestGroupMan()->findRequestGroup(gid);
  323. if(group.isNull()) {
  324. group = e->getRequestGroupMan()->findReservedGroup(gid);
  325. if(group.isNull()) {
  326. throw DL_ABORT_EX
  327. (StringFormat("Active Download not found for GID#%s",
  328. util::itos(gid).c_str()).str());
  329. }
  330. if(group->isDependencyResolved()) {
  331. e->getRequestGroupMan()->removeReservedGroup(gid);
  332. } else {
  333. throw DL_ABORT_EX
  334. (StringFormat("GID#%s cannot be removed now",
  335. util::itos(gid).c_str()).str());
  336. }
  337. } else {
  338. if(forceRemove) {
  339. group->setForceHaltRequested(true, RequestGroup::USER_REQUEST);
  340. } else {
  341. group->setHaltRequested(true, RequestGroup::USER_REQUEST);
  342. }
  343. }
  344. return createGIDResponse(gid);
  345. }
  346. SharedHandle<ValueBase> RemoveXmlRpcMethod::process
  347. (const XmlRpcRequest& req, DownloadEngine* e)
  348. {
  349. return removeDownload(req, e, false);
  350. }
  351. SharedHandle<ValueBase> ForceRemoveXmlRpcMethod::process
  352. (const XmlRpcRequest& req, DownloadEngine* e)
  353. {
  354. return removeDownload(req, e, true);
  355. }
  356. static bool pauseRequestGroup
  357. (const SharedHandle<RequestGroup>& group, bool reserved, bool forcePause)
  358. {
  359. if((reserved && !group->isPauseRequested()) ||
  360. (!reserved &&
  361. !group->isForceHaltRequested() &&
  362. ((forcePause && group->isHaltRequested() && group->isPauseRequested()) ||
  363. (!group->isHaltRequested() && !group->isPauseRequested())))) {
  364. if(!reserved) {
  365. // Call setHaltRequested before setPauseRequested because
  366. // setHaltRequested calls setPauseRequested(false) internally.
  367. if(forcePause) {
  368. group->setForceHaltRequested(true, RequestGroup::NONE);
  369. } else {
  370. group->setHaltRequested(true, RequestGroup::NONE);
  371. }
  372. }
  373. group->setPauseRequested(true);
  374. return true;
  375. } else {
  376. return false;
  377. }
  378. }
  379. static SharedHandle<ValueBase> pauseDownload
  380. (const XmlRpcRequest& req, DownloadEngine* e, bool forcePause)
  381. {
  382. const SharedHandle<List>& params = req.params;
  383. gid_t gid = getRequiredGidParam(params, 0);
  384. bool reserved = false;
  385. SharedHandle<RequestGroup> group =
  386. e->getRequestGroupMan()->findRequestGroup(gid);
  387. if(group.isNull()) {
  388. reserved = true;
  389. group = e->getRequestGroupMan()->findReservedGroup(gid);
  390. }
  391. if(!group.isNull() && pauseRequestGroup(group, reserved, forcePause)) {
  392. return createGIDResponse(gid);
  393. } else {
  394. throw DL_ABORT_EX
  395. (StringFormat("GID#%s cannot be paused now",
  396. util::itos(gid).c_str()).str());
  397. }
  398. }
  399. SharedHandle<ValueBase> PauseXmlRpcMethod::process
  400. (const XmlRpcRequest& req, DownloadEngine* e)
  401. {
  402. return pauseDownload(req, e, false);
  403. }
  404. SharedHandle<ValueBase> ForcePauseXmlRpcMethod::process
  405. (const XmlRpcRequest& req, DownloadEngine* e)
  406. {
  407. return pauseDownload(req, e, true);
  408. }
  409. template<typename InputIterator>
  410. static void pauseRequestGroups
  411. (InputIterator first, InputIterator last, bool reserved, bool forcePause)
  412. {
  413. for(; first != last; ++first) {
  414. pauseRequestGroup(*first, reserved, forcePause);
  415. }
  416. }
  417. static SharedHandle<ValueBase> pauseAllDownloads
  418. (const XmlRpcRequest& req, DownloadEngine* e, bool forcePause)
  419. {
  420. const std::deque<SharedHandle<RequestGroup> >& groups =
  421. e->getRequestGroupMan()->getRequestGroups();
  422. pauseRequestGroups(groups.begin(), groups.end(), false, forcePause);
  423. const std::deque<SharedHandle<RequestGroup> >& reservedGroups =
  424. e->getRequestGroupMan()->getReservedGroups();
  425. pauseRequestGroups(reservedGroups.begin(), reservedGroups.end(),
  426. true, forcePause);
  427. return VLB_OK;
  428. }
  429. SharedHandle<ValueBase> PauseAllXmlRpcMethod::process
  430. (const XmlRpcRequest& req, DownloadEngine* e)
  431. {
  432. return pauseAllDownloads(req, e, false);
  433. }
  434. SharedHandle<ValueBase> ForcePauseAllXmlRpcMethod::process
  435. (const XmlRpcRequest& req, DownloadEngine* e)
  436. {
  437. return pauseAllDownloads(req, e, true);
  438. }
  439. SharedHandle<ValueBase> UnpauseXmlRpcMethod::process
  440. (const XmlRpcRequest& req, DownloadEngine* e)
  441. {
  442. const SharedHandle<List>& params = req.params;
  443. gid_t gid = getRequiredGidParam(params, 0);
  444. SharedHandle<RequestGroup> group =
  445. e->getRequestGroupMan()->findReservedGroup(gid);
  446. if(group.isNull() || !group->isPauseRequested()) {
  447. throw DL_ABORT_EX
  448. (StringFormat("GID#%s cannot be unpaused now",
  449. util::itos(gid).c_str()).str());
  450. } else {
  451. group->setPauseRequested(false);
  452. e->getRequestGroupMan()->requestQueueCheck();
  453. }
  454. return createGIDResponse(gid);
  455. }
  456. SharedHandle<ValueBase> UnpauseAllXmlRpcMethod::process
  457. (const XmlRpcRequest& req, DownloadEngine* e)
  458. {
  459. const std::deque<SharedHandle<RequestGroup> >& groups =
  460. e->getRequestGroupMan()->getReservedGroups();
  461. std::for_each(groups.begin(), groups.end(),
  462. std::bind2nd(mem_fun_sh(&RequestGroup::setPauseRequested),
  463. false));
  464. e->getRequestGroupMan()->requestQueueCheck();
  465. return VLB_OK;
  466. }
  467. template<typename InputIterator>
  468. static void createUriEntry
  469. (const SharedHandle<List>& uriList,
  470. InputIterator first, InputIterator last,
  471. const SharedHandle<String>& status)
  472. {
  473. for(; first != last; ++first) {
  474. SharedHandle<Dict> entry = Dict::g();
  475. entry->put(KEY_URI, *first);
  476. entry->put(KEY_STATUS, status);
  477. uriList->append(entry);
  478. }
  479. }
  480. static void createUriEntry
  481. (const SharedHandle<List>& uriList, const SharedHandle<FileEntry>& file)
  482. {
  483. createUriEntry(uriList,
  484. file->getSpentUris().begin(),
  485. file->getSpentUris().end(),
  486. VLB_USED);
  487. createUriEntry(uriList,
  488. file->getRemainingUris().begin(),
  489. file->getRemainingUris().end(),
  490. VLB_WAITING);
  491. }
  492. template<typename InputIterator>
  493. static void createFileEntry
  494. (const SharedHandle<List>& files, InputIterator first, InputIterator last)
  495. {
  496. size_t index = 1;
  497. for(; first != last; ++first, ++index) {
  498. SharedHandle<Dict> entry = Dict::g();
  499. entry->put(KEY_INDEX, util::uitos(index));
  500. entry->put(KEY_PATH, (*first)->getPath());
  501. entry->put(KEY_SELECTED, (*first)->isRequested()?VLB_TRUE:VLB_FALSE);
  502. entry->put(KEY_LENGTH, util::uitos((*first)->getLength()));
  503. SharedHandle<List> uriList = List::g();
  504. createUriEntry(uriList, *first);
  505. entry->put(KEY_URIS, uriList);
  506. files->append(entry);
  507. }
  508. }
  509. void gatherProgressCommon
  510. (const SharedHandle<Dict>& entryDict, const SharedHandle<RequestGroup>& group)
  511. {
  512. entryDict->put(KEY_GID, util::itos(group->getGID()));
  513. // This is "filtered" total length if --select-file is used.
  514. entryDict->put(KEY_TOTAL_LENGTH, util::uitos(group->getTotalLength()));
  515. // This is "filtered" total length if --select-file is used.
  516. entryDict->put(KEY_COMPLETED_LENGTH,util::uitos(group->getCompletedLength()));
  517. TransferStat stat = group->calculateStat();
  518. entryDict->put(KEY_DOWNLOAD_SPEED, util::uitos(stat.getDownloadSpeed()));
  519. entryDict->put(KEY_UPLOAD_SPEED, util::uitos(stat.getUploadSpeed()));
  520. entryDict->put(KEY_UPLOAD_LENGTH, util::uitos(stat.getAllTimeUploadLength()));
  521. entryDict->put(KEY_CONNECTIONS, util::uitos(group->getNumConnection()));
  522. SharedHandle<PieceStorage> ps = group->getPieceStorage();
  523. if(!ps.isNull()) {
  524. if(ps->getBitfieldLength() > 0) {
  525. entryDict->put(KEY_BITFIELD,
  526. util::toHex(ps->getBitfield(), ps->getBitfieldLength()));
  527. }
  528. }
  529. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  530. entryDict->put(KEY_PIECE_LENGTH, util::uitos(dctx->getPieceLength()));
  531. entryDict->put(KEY_NUM_PIECES, util::uitos(dctx->getNumPieces()));
  532. if(!group->followedBy().empty()) {
  533. SharedHandle<List> list = List::g();
  534. // The element is GID.
  535. for(std::vector<gid_t>::const_iterator i = group->followedBy().begin(),
  536. eoi = group->followedBy().end(); i != eoi; ++i) {
  537. list->append(util::itos(*i));
  538. }
  539. entryDict->put(KEY_FOLLOWED_BY, list);
  540. }
  541. if(group->belongsTo()) {
  542. entryDict->put(KEY_BELONGS_TO, util::itos(group->belongsTo()));
  543. }
  544. SharedHandle<List> files = List::g();
  545. createFileEntry
  546. (files, dctx->getFileEntries().begin(), dctx->getFileEntries().end());
  547. entryDict->put(KEY_FILES, files);
  548. entryDict->put(KEY_DIR, dctx->getDir());
  549. }
  550. #ifdef ENABLE_BITTORRENT
  551. void gatherBitTorrentMetadata
  552. (const SharedHandle<Dict>& btDict,
  553. const SharedHandle<TorrentAttribute>& torrentAttrs)
  554. {
  555. if(!torrentAttrs->comment.empty()) {
  556. btDict->put(KEY_COMMENT, torrentAttrs->comment);
  557. }
  558. if(torrentAttrs->creationDate) {
  559. btDict->put(KEY_CREATION_DATE, Integer::g(torrentAttrs->creationDate));
  560. }
  561. if(!torrentAttrs->mode.empty()) {
  562. btDict->put(KEY_MODE, torrentAttrs->mode);
  563. }
  564. SharedHandle<List> destAnnounceList = List::g();
  565. for(std::vector<std::vector<std::string> >::const_iterator l =
  566. torrentAttrs->announceList.begin(),
  567. eoi = torrentAttrs->announceList.end(); l != eoi; ++l) {
  568. SharedHandle<List> destAnnounceTier = List::g();
  569. for(std::vector<std::string>::const_iterator t = (*l).begin(),
  570. eoi2 = (*l).end(); t != eoi2; ++t) {
  571. destAnnounceTier->append(*t);
  572. }
  573. destAnnounceList->append(destAnnounceTier);
  574. }
  575. btDict->put(KEY_ANNOUNCE_LIST, destAnnounceList);
  576. if(!torrentAttrs->metadata.empty()) {
  577. SharedHandle<Dict> infoDict = Dict::g();
  578. infoDict->put(KEY_NAME, torrentAttrs->name);
  579. btDict->put(KEY_INFO, infoDict);
  580. }
  581. }
  582. static void gatherProgressBitTorrent
  583. (const SharedHandle<Dict>& entryDict,
  584. const SharedHandle<TorrentAttribute>& torrentAttrs,
  585. const BtObject& btObject)
  586. {
  587. entryDict->put(KEY_INFO_HASH, util::toHex(torrentAttrs->infoHash));
  588. SharedHandle<Dict> btDict = Dict::g();
  589. gatherBitTorrentMetadata(btDict, torrentAttrs);
  590. entryDict->put(KEY_BITTORRENT, btDict);
  591. if(btObject.isNull()) {
  592. entryDict->put(KEY_NUM_SEEDERS, VLB_ZERO);
  593. } else {
  594. SharedHandle<PeerStorage> peerStorage = btObject._peerStorage;
  595. assert(!peerStorage.isNull());
  596. std::vector<SharedHandle<Peer> > peers;
  597. peerStorage->getActivePeers(peers);
  598. entryDict->put(KEY_NUM_SEEDERS,
  599. util::uitos(countSeeder(peers.begin(), peers.end())));
  600. }
  601. }
  602. static void gatherPeer
  603. (const SharedHandle<List>& peers, const SharedHandle<PeerStorage>& ps)
  604. {
  605. std::vector<SharedHandle<Peer> > activePeers;
  606. ps->getActivePeers(activePeers);
  607. for(std::vector<SharedHandle<Peer> >::const_iterator i =
  608. activePeers.begin(), eoi = activePeers.end(); i != eoi; ++i) {
  609. SharedHandle<Dict> peerEntry = Dict::g();
  610. peerEntry->put(KEY_PEER_ID, util::torrentPercentEncode((*i)->getPeerId(),
  611. PEER_ID_LENGTH));
  612. peerEntry->put(KEY_IP, (*i)->getIPAddress());
  613. if((*i)->isIncomingPeer()) {
  614. peerEntry->put(KEY_PORT, VLB_ZERO);
  615. } else {
  616. peerEntry->put(KEY_PORT, util::uitos((*i)->getPort()));
  617. }
  618. peerEntry->put(KEY_BITFIELD,
  619. util::toHex((*i)->getBitfield(), (*i)->getBitfieldLength()));
  620. peerEntry->put(KEY_AM_CHOKING, (*i)->amChoking()?VLB_TRUE:VLB_FALSE);
  621. peerEntry->put(KEY_PEER_CHOKING, (*i)->peerChoking()?VLB_TRUE:VLB_FALSE);
  622. TransferStat stat = ps->getTransferStatFor(*i);
  623. peerEntry->put(KEY_DOWNLOAD_SPEED, util::uitos(stat.getDownloadSpeed()));
  624. peerEntry->put(KEY_UPLOAD_SPEED, util::uitos(stat.getUploadSpeed()));
  625. peerEntry->put(KEY_SEEDER, (*i)->isSeeder()?VLB_TRUE:VLB_FALSE);
  626. peers->append(peerEntry);
  627. }
  628. }
  629. #endif // ENABLE_BITTORRENT
  630. static void gatherProgress
  631. (const SharedHandle<Dict>& entryDict,
  632. const SharedHandle<RequestGroup>& group, DownloadEngine* e)
  633. {
  634. gatherProgressCommon(entryDict, group);
  635. #ifdef ENABLE_BITTORRENT
  636. if(group->getDownloadContext()->hasAttribute(bittorrent::BITTORRENT)) {
  637. SharedHandle<TorrentAttribute> torrentAttrs =
  638. bittorrent::getTorrentAttrs(group->getDownloadContext());
  639. BtObject btObject = e->getBtRegistry()->get(group->getGID());
  640. gatherProgressBitTorrent(entryDict, torrentAttrs, btObject);
  641. }
  642. #endif // ENABLE_BITTORRENT
  643. }
  644. void gatherStoppedDownload
  645. (const SharedHandle<Dict>& entryDict, const SharedHandle<DownloadResult>& ds)
  646. {
  647. entryDict->put(KEY_GID, util::itos(ds->gid));
  648. entryDict->put(KEY_ERROR_CODE, util::itos(static_cast<int>(ds->result)));
  649. if(ds->result == downloadresultcode::IN_PROGRESS) {
  650. entryDict->put(KEY_STATUS, VLB_REMOVED);
  651. } else if(ds->result == downloadresultcode::FINISHED) {
  652. entryDict->put(KEY_STATUS, VLB_COMPLETE);
  653. } else {
  654. entryDict->put(KEY_STATUS, VLB_ERROR);
  655. }
  656. if(!ds->followedBy.empty()) {
  657. SharedHandle<List> list = List::g();
  658. // The element is GID.
  659. for(std::vector<gid_t>::const_iterator i = ds->followedBy.begin(),
  660. eoi = ds->followedBy.end(); i != eoi; ++i) {
  661. list->append(util::itos(*i));
  662. }
  663. entryDict->put(KEY_FOLLOWED_BY, list);
  664. }
  665. if(ds->belongsTo) {
  666. entryDict->put(KEY_BELONGS_TO, util::itos(ds->belongsTo));
  667. }
  668. SharedHandle<List> files = List::g();
  669. createFileEntry(files, ds->fileEntries.begin(), ds->fileEntries.end());
  670. entryDict->put(KEY_FILES, files);
  671. entryDict->put(KEY_TOTAL_LENGTH, util::uitos(ds->totalLength));
  672. entryDict->put(KEY_COMPLETED_LENGTH, util::uitos(ds->completedLength));
  673. entryDict->put(KEY_UPLOAD_LENGTH, util::uitos(ds->uploadLength));
  674. if(!ds->bitfieldStr.empty()) {
  675. entryDict->put(KEY_BITFIELD, ds->bitfieldStr);
  676. }
  677. entryDict->put(KEY_DOWNLOAD_SPEED, VLB_ZERO);
  678. entryDict->put(KEY_UPLOAD_SPEED, VLB_ZERO);
  679. if(!ds->infoHashStr.empty()) {
  680. entryDict->put(KEY_INFO_HASH, ds->infoHashStr);
  681. entryDict->put(KEY_NUM_SEEDERS, VLB_ZERO);
  682. }
  683. entryDict->put(KEY_PIECE_LENGTH, util::uitos(ds->pieceLength));
  684. entryDict->put(KEY_NUM_PIECES, util::uitos(ds->numPieces));
  685. entryDict->put(KEY_CONNECTIONS, VLB_ZERO);
  686. entryDict->put(KEY_DIR, ds->dir);
  687. }
  688. SharedHandle<ValueBase> GetFilesXmlRpcMethod::process
  689. (const XmlRpcRequest& req, DownloadEngine* e)
  690. {
  691. const SharedHandle<List>& params = req.params;
  692. gid_t gid = getRequiredGidParam(params, 0);
  693. SharedHandle<List> files = List::g();
  694. SharedHandle<RequestGroup> group =
  695. findRequestGroup(e->getRequestGroupMan(), gid);
  696. if(group.isNull()) {
  697. SharedHandle<DownloadResult> dr =
  698. e->getRequestGroupMan()->findDownloadResult(gid);
  699. if(dr.isNull()) {
  700. throw DL_ABORT_EX
  701. (StringFormat("No file data is available for GID#%s",
  702. util::itos(gid).c_str()).str());
  703. } else {
  704. createFileEntry(files, dr->fileEntries.begin(), dr->fileEntries.end());
  705. }
  706. } else {
  707. createFileEntry(files,
  708. group->getDownloadContext()->getFileEntries().begin(),
  709. group->getDownloadContext()->getFileEntries().end());
  710. }
  711. return files;
  712. }
  713. SharedHandle<ValueBase> GetUrisXmlRpcMethod::process
  714. (const XmlRpcRequest& req, DownloadEngine* e)
  715. {
  716. const SharedHandle<List>& params = req.params;
  717. gid_t gid = getRequiredGidParam(params, 0);
  718. SharedHandle<RequestGroup> group =
  719. findRequestGroup(e->getRequestGroupMan(), gid);
  720. if(group.isNull()) {
  721. throw DL_ABORT_EX
  722. (StringFormat("No URI data is available for GID#%s",
  723. util::itos(gid).c_str()).str());
  724. }
  725. SharedHandle<List> uriList = List::g();
  726. // TODO Current implementation just returns first FileEntry's URIs.
  727. if(!group->getDownloadContext()->getFileEntries().empty()) {
  728. createUriEntry(uriList, group->getDownloadContext()->getFirstFileEntry());
  729. }
  730. return uriList;
  731. }
  732. #ifdef ENABLE_BITTORRENT
  733. SharedHandle<ValueBase> GetPeersXmlRpcMethod::process
  734. (const XmlRpcRequest& req, DownloadEngine* e)
  735. {
  736. const SharedHandle<List>& params = req.params;
  737. gid_t gid = getRequiredGidParam(params, 0);
  738. SharedHandle<RequestGroup> group =
  739. findRequestGroup(e->getRequestGroupMan(), gid);
  740. if(group.isNull()) {
  741. throw DL_ABORT_EX
  742. (StringFormat("No peer data is available for GID#%s",
  743. util::itos(gid).c_str()).str());
  744. }
  745. SharedHandle<List> peers = List::g();
  746. BtObject btObject = e->getBtRegistry()->get(group->getGID());
  747. if(!btObject.isNull()) {
  748. assert(!btObject._peerStorage.isNull());
  749. gatherPeer(peers, btObject._peerStorage);
  750. }
  751. return peers;
  752. }
  753. #endif // ENABLE_BITTORRENT
  754. SharedHandle<ValueBase> TellStatusXmlRpcMethod::process
  755. (const XmlRpcRequest& req, DownloadEngine* e)
  756. {
  757. const SharedHandle<List>& params = req.params;
  758. gid_t gid = getRequiredGidParam(params, 0);
  759. SharedHandle<RequestGroup> group =
  760. e->getRequestGroupMan()->findRequestGroup(gid);
  761. SharedHandle<Dict> entryDict = Dict::g();
  762. if(group.isNull()) {
  763. group = e->getRequestGroupMan()->findReservedGroup(gid);
  764. if(group.isNull()) {
  765. SharedHandle<DownloadResult> ds =
  766. e->getRequestGroupMan()->findDownloadResult(gid);
  767. if(ds.isNull()) {
  768. throw DL_ABORT_EX
  769. (StringFormat("No such download for GID#%s",
  770. util::itos(gid).c_str()).str());
  771. }
  772. gatherStoppedDownload(entryDict, ds);
  773. } else {
  774. if(group->isPauseRequested()) {
  775. entryDict->put(KEY_STATUS, VLB_PAUSED);
  776. } else {
  777. entryDict->put(KEY_STATUS, VLB_WAITING);
  778. }
  779. gatherProgress(entryDict, group, e);
  780. }
  781. } else {
  782. entryDict->put(KEY_STATUS, VLB_ACTIVE);
  783. gatherProgress(entryDict, group, e);
  784. }
  785. return entryDict;
  786. }
  787. SharedHandle<ValueBase> TellActiveXmlRpcMethod::process
  788. (const XmlRpcRequest& req, DownloadEngine* e)
  789. {
  790. SharedHandle<List> list = List::g();
  791. const std::deque<SharedHandle<RequestGroup> >& groups =
  792. e->getRequestGroupMan()->getRequestGroups();
  793. for(std::deque<SharedHandle<RequestGroup> >::const_iterator i =
  794. groups.begin(), eoi = groups.end(); i != eoi; ++i) {
  795. SharedHandle<Dict> entryDict = Dict::g();
  796. entryDict->put(KEY_STATUS, VLB_ACTIVE);
  797. gatherProgress(entryDict, *i, e);
  798. list->append(entryDict);
  799. }
  800. return list;
  801. }
  802. const std::deque<SharedHandle<RequestGroup> >&
  803. TellWaitingXmlRpcMethod::getItems(DownloadEngine* e) const
  804. {
  805. return e->getRequestGroupMan()->getReservedGroups();
  806. }
  807. void TellWaitingXmlRpcMethod::createEntry
  808. (const SharedHandle<Dict>& entryDict, const SharedHandle<RequestGroup>& item,
  809. DownloadEngine* e) const
  810. {
  811. if(item->isPauseRequested()) {
  812. entryDict->put(KEY_STATUS, VLB_PAUSED);
  813. } else {
  814. entryDict->put(KEY_STATUS, VLB_WAITING);
  815. }
  816. gatherProgress(entryDict, item, e);
  817. }
  818. const std::deque<SharedHandle<DownloadResult> >&
  819. TellStoppedXmlRpcMethod::getItems(DownloadEngine* e) const
  820. {
  821. return e->getRequestGroupMan()->getDownloadResults();
  822. }
  823. void TellStoppedXmlRpcMethod::createEntry
  824. (const SharedHandle<Dict>& entryDict, const SharedHandle<DownloadResult>& item,
  825. DownloadEngine* e) const
  826. {
  827. gatherStoppedDownload(entryDict, item);
  828. }
  829. SharedHandle<ValueBase> PurgeDownloadResultXmlRpcMethod::process
  830. (const XmlRpcRequest& req, DownloadEngine* e)
  831. {
  832. e->getRequestGroupMan()->purgeDownloadResult();
  833. return VLB_OK;
  834. }
  835. SharedHandle<ValueBase> ChangeOptionXmlRpcMethod::process
  836. (const XmlRpcRequest& req, DownloadEngine* e)
  837. {
  838. const SharedHandle<List>& params = req.params;
  839. gid_t gid = getRequiredGidParam(params, 0);
  840. SharedHandle<RequestGroup> group =
  841. findRequestGroup(e->getRequestGroupMan(), gid);
  842. if(group.isNull()) {
  843. throw DL_ABORT_EX
  844. (StringFormat("Cannot change option for GID#%s",
  845. util::itos(gid).c_str()).str());
  846. }
  847. SharedHandle<Option> option(new Option());
  848. const Dict* optionsParam = getDictParam(params, 1);
  849. if(optionsParam) {
  850. gatherChangeableOption(option, optionsParam);
  851. applyChangeableOption(group->getOption().get(), option.get());
  852. if(option->defined(PREF_MAX_DOWNLOAD_LIMIT)) {
  853. group->setMaxDownloadSpeedLimit
  854. (option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
  855. }
  856. if(option->defined(PREF_MAX_UPLOAD_LIMIT)) {
  857. group->setMaxUploadSpeedLimit(option->getAsInt(PREF_MAX_UPLOAD_LIMIT));
  858. }
  859. #ifdef ENABLE_BITTORRENT
  860. BtObject btObject = e->getBtRegistry()->get(group->getGID());
  861. if(!btObject.isNull()) {
  862. if(option->defined(PREF_BT_MAX_PEERS)) {
  863. btObject._btRuntime->setMaxPeers(option->getAsInt(PREF_BT_MAX_PEERS));
  864. }
  865. }
  866. #endif // ENABLE_BITTORRENT
  867. }
  868. return VLB_OK;
  869. }
  870. SharedHandle<ValueBase> ChangeGlobalOptionXmlRpcMethod::process
  871. (const XmlRpcRequest& req, DownloadEngine* e)
  872. {
  873. const SharedHandle<List>& params = req.params;
  874. const Dict* optionsParam = getDictParam(params, 0);
  875. if(!optionsParam) {
  876. return VLB_OK;
  877. }
  878. SharedHandle<Option> option(new Option());
  879. gatherChangeableGlobalOption(option, optionsParam);
  880. applyChangeableGlobalOption(e->getOption(), option.get());
  881. if(option->defined(PREF_MAX_OVERALL_DOWNLOAD_LIMIT)) {
  882. e->getRequestGroupMan()->setMaxOverallDownloadSpeedLimit
  883. (option->getAsInt(PREF_MAX_OVERALL_DOWNLOAD_LIMIT));
  884. }
  885. if(option->defined(PREF_MAX_OVERALL_UPLOAD_LIMIT)) {
  886. e->getRequestGroupMan()->setMaxOverallUploadSpeedLimit
  887. (option->getAsInt(PREF_MAX_OVERALL_UPLOAD_LIMIT));
  888. }
  889. if(option->defined(PREF_MAX_CONCURRENT_DOWNLOADS)) {
  890. e->getRequestGroupMan()->setMaxSimultaneousDownloads
  891. (option->getAsInt(PREF_MAX_CONCURRENT_DOWNLOADS));
  892. e->getRequestGroupMan()->requestQueueCheck();
  893. }
  894. return VLB_OK;
  895. }
  896. SharedHandle<ValueBase> GetVersionXmlRpcMethod::process
  897. (const XmlRpcRequest& req, DownloadEngine* e)
  898. {
  899. SharedHandle<Dict> result = Dict::g();
  900. result->put(KEY_VERSION, PACKAGE_VERSION);
  901. SharedHandle<List> featureList = List::g();
  902. const FeatureMap& features = FeatureConfig::getInstance()->getFeatures();
  903. for(FeatureMap::const_iterator i = features.begin(), eoi = features.end();
  904. i != eoi;++i){
  905. if((*i).second) {
  906. featureList->append((*i).first);
  907. }
  908. }
  909. result->put(KEY_ENABLED_FEATURES, featureList);
  910. return result;
  911. }
  912. template<typename InputIterator>
  913. static void pushRequestOption
  914. (const SharedHandle<Dict>& dict,
  915. InputIterator optionFirst, InputIterator optionLast)
  916. {
  917. const std::set<std::string>& requestOptions = listRequestOptions();
  918. for(; optionFirst != optionLast; ++optionFirst) {
  919. if(requestOptions.count((*optionFirst).first)) {
  920. dict->put((*optionFirst).first, (*optionFirst).second);
  921. }
  922. }
  923. }
  924. SharedHandle<ValueBase> GetOptionXmlRpcMethod::process
  925. (const XmlRpcRequest& req, DownloadEngine* e)
  926. {
  927. const SharedHandle<List>& params = req.params;
  928. gid_t gid = getRequiredGidParam(params, 0);
  929. SharedHandle<RequestGroup> group =
  930. findRequestGroup(e->getRequestGroupMan(), gid);
  931. if(group.isNull()) {
  932. throw DL_ABORT_EX
  933. (StringFormat("Cannot get option for GID#%s",
  934. util::itos(gid).c_str()).str());
  935. }
  936. SharedHandle<Dict> result = Dict::g();
  937. SharedHandle<Option> option = group->getOption();
  938. pushRequestOption(result, option->begin(), option->end());
  939. return result;
  940. }
  941. SharedHandle<ValueBase> GetGlobalOptionXmlRpcMethod::process
  942. (const XmlRpcRequest& req, DownloadEngine* e)
  943. {
  944. SharedHandle<Dict> result = Dict::g();
  945. for(std::map<std::string, std::string>::const_iterator i =
  946. e->getOption()->begin(), eoi = e->getOption()->end(); i != eoi; ++i) {
  947. SharedHandle<OptionHandler> h = getOptionParser()->findByName((*i).first);
  948. if(!h.isNull() && !h->isHidden()) {
  949. result->put((*i).first, (*i).second);
  950. }
  951. }
  952. return result;
  953. }
  954. SharedHandle<ValueBase> ChangePositionXmlRpcMethod::process
  955. (const XmlRpcRequest& req, DownloadEngine* e)
  956. {
  957. const SharedHandle<List>& params = req.params;
  958. gid_t gid = getRequiredGidParam(params, 0);
  959. const Integer* posParam = getIntegerParam(params, 1);
  960. const String* howParam = getStringParam(params, 2);
  961. if(!posParam || !howParam) {
  962. throw DL_ABORT_EX("Illegal argument.");
  963. }
  964. int pos = posParam->i();
  965. const std::string& howStr = howParam->s();
  966. RequestGroupMan::HOW how;
  967. if(howStr == "POS_SET") {
  968. how = RequestGroupMan::POS_SET;
  969. } else if(howStr == "POS_CUR") {
  970. how = RequestGroupMan::POS_CUR;
  971. } else if(howStr == "POS_END") {
  972. how = RequestGroupMan::POS_END;
  973. } else {
  974. throw DL_ABORT_EX("Illegal argument.");
  975. }
  976. size_t destPos =
  977. e->getRequestGroupMan()->changeReservedGroupPosition(gid, pos, how);
  978. SharedHandle<Integer> result = Integer::g(destPos);
  979. return result;
  980. }
  981. SharedHandle<ValueBase> GetSessionInfoXmlRpcMethod::process
  982. (const XmlRpcRequest& req, DownloadEngine* e)
  983. {
  984. SharedHandle<Dict> result = Dict::g();
  985. result->put(KEY_SESSION_ID, util::toHex(e->getSessionId()));
  986. return result;
  987. }
  988. SharedHandle<ValueBase> GetServersXmlRpcMethod::process
  989. (const XmlRpcRequest& req, DownloadEngine* e)
  990. {
  991. const SharedHandle<List>& params = req.params;
  992. gid_t gid = getRequiredGidParam(params, 0);
  993. SharedHandle<RequestGroup> group =
  994. e->getRequestGroupMan()->findRequestGroup(gid);
  995. if(group.isNull()) {
  996. throw DL_ABORT_EX(StringFormat("No active download for GID#%s",
  997. util::itos(gid).c_str()).str());
  998. }
  999. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  1000. const std::vector<SharedHandle<FileEntry> >& files = dctx->getFileEntries();
  1001. SharedHandle<List> result = List::g();
  1002. size_t index = 1;
  1003. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi = files.begin(),
  1004. eoi = files.end(); fi != eoi; ++fi, ++index) {
  1005. SharedHandle<Dict> fileEntry = Dict::g();
  1006. fileEntry->put(KEY_INDEX, util::uitos(index));
  1007. SharedHandle<List> servers = List::g();
  1008. const std::deque<SharedHandle<Request> >& requests =
  1009. (*fi)->getInFlightRequests();
  1010. for(std::deque<SharedHandle<Request> >::const_iterator ri =requests.begin(),
  1011. eoi = requests.end(); ri != eoi; ++ri) {
  1012. SharedHandle<PeerStat> ps = (*ri)->getPeerStat();
  1013. if(!ps.isNull()) {
  1014. SharedHandle<Dict> serverEntry = Dict::g();
  1015. serverEntry->put(KEY_URI, (*ri)->getUri());
  1016. serverEntry->put(KEY_CURRENT_URI, (*ri)->getCurrentUri());
  1017. serverEntry->put(KEY_DOWNLOAD_SPEED,
  1018. util::uitos(ps->calculateDownloadSpeed()));
  1019. servers->append(serverEntry);
  1020. }
  1021. }
  1022. fileEntry->put(KEY_SERVERS, servers);
  1023. result->append(fileEntry);
  1024. }
  1025. return result;
  1026. }
  1027. SharedHandle<ValueBase> ChangeUriXmlRpcMethod::process
  1028. (const XmlRpcRequest& req, DownloadEngine* e)
  1029. {
  1030. const SharedHandle<List>& params = req.params;
  1031. gid_t gid = getRequiredGidParam(params, 0);
  1032. const Integer* indexParam = getIntegerParam(params, 1);
  1033. const List* delUrisParam = getListParam(params, 2);
  1034. const List* addUrisParam = getListParam(params, 3);
  1035. if(!indexParam || !delUrisParam || ! addUrisParam) {
  1036. throw DL_ABORT_EX("Bad request");
  1037. }
  1038. size_t pos = 0;
  1039. bool posGiven = false;
  1040. getPosParam(params, 4, posGiven, pos);
  1041. size_t index = indexParam->i()-1;
  1042. SharedHandle<RequestGroup> group =
  1043. findRequestGroup(e->getRequestGroupMan(), gid);
  1044. if(group.isNull()) {
  1045. throw DL_ABORT_EX
  1046. (StringFormat("Cannot remove URIs from GID#%s",
  1047. util::itos(gid).c_str()).str());
  1048. }
  1049. const SharedHandle<DownloadContext>& dctx = group->getDownloadContext();
  1050. const std::vector<SharedHandle<FileEntry> >& files = dctx->getFileEntries();
  1051. if(files.size() <= index) {
  1052. throw DL_ABORT_EX(StringFormat("fileIndex is out of range").str());
  1053. }
  1054. SharedHandle<FileEntry> s = files[index];
  1055. size_t delcount = 0;
  1056. for(List::ValueType::const_iterator i = delUrisParam->begin(),
  1057. eoi = delUrisParam->end(); i != eoi; ++i) {
  1058. const String* uri = asString(*i);
  1059. if(uri && s->removeUri(uri->s())) {
  1060. ++delcount;
  1061. }
  1062. }
  1063. size_t addcount = 0;
  1064. if(posGiven) {
  1065. for(List::ValueType::const_iterator i = addUrisParam->begin(),
  1066. eoi = addUrisParam->end(); i != eoi; ++i) {
  1067. const String* uri = asString(*i);
  1068. if(uri && s->insertUri(uri->s(), pos)) {
  1069. ++addcount;
  1070. ++pos;
  1071. }
  1072. }
  1073. } else {
  1074. for(List::ValueType::const_iterator i = addUrisParam->begin(),
  1075. eoi = addUrisParam->end(); i != eoi; ++i) {
  1076. const String* uri = asString(*i);
  1077. if(uri && s->addUri(uri->s())) {
  1078. ++addcount;
  1079. }
  1080. }
  1081. }
  1082. if(addcount && !group->getPieceStorage().isNull()) {
  1083. std::vector<Command*> commands;
  1084. group->createNextCommand(commands, e);
  1085. e->addCommand(commands);
  1086. group->getSegmentMan()->recognizeSegmentFor(s);
  1087. }
  1088. SharedHandle<List> res = List::g();
  1089. res->append(Integer::g(delcount));
  1090. res->append(Integer::g(addcount));
  1091. return res;
  1092. }
  1093. static SharedHandle<ValueBase> goingShutdown
  1094. (const XmlRpcRequest& req, DownloadEngine* e, bool forceHalt)
  1095. {
  1096. // Schedule shutdown after 3seconds to give time to client to
  1097. // receive XML-RPC response.
  1098. e->addRoutineCommand(new TimedHaltCommand(e->newCUID(), e, 3, forceHalt));
  1099. LogFactory::getInstance()->info("Scheduled shutdown in 3 seconds.");
  1100. return VLB_OK;
  1101. }
  1102. SharedHandle<ValueBase> ShutdownXmlRpcMethod::process
  1103. (const XmlRpcRequest& req, DownloadEngine* e)
  1104. {
  1105. return goingShutdown(req, e, false);
  1106. }
  1107. SharedHandle<ValueBase> ForceShutdownXmlRpcMethod::process
  1108. (const XmlRpcRequest& req, DownloadEngine* e)
  1109. {
  1110. return goingShutdown(req, e, true);
  1111. }
  1112. SharedHandle<ValueBase> SystemMulticallXmlRpcMethod::process
  1113. (const XmlRpcRequest& req, DownloadEngine* e)
  1114. {
  1115. const SharedHandle<List>& params = req.params;
  1116. const List* methodSpecs = getListParam(params, 0);
  1117. if(!methodSpecs) {
  1118. throw DL_ABORT_EX("Illegal argument. One item list is expected.");
  1119. }
  1120. SharedHandle<List> list = List::g();
  1121. for(List::ValueType::const_iterator i = methodSpecs->begin(),
  1122. eoi = methodSpecs->end(); i != eoi; ++i) {
  1123. const Dict* methodDict = asDict(*i);
  1124. if(!methodDict) {
  1125. list->append(createErrorResponse
  1126. (DL_ABORT_EX("system.multicall expected struct.")));
  1127. continue;
  1128. }
  1129. const String* methodName = asString(methodDict->get(KEY_METHOD_NAME));
  1130. const List* paramsList = asList(methodDict->get(KEY_PARAMS));
  1131. if(!methodName || !paramsList) {
  1132. list->append(createErrorResponse
  1133. (DL_ABORT_EX("Missing methodName or params.")));
  1134. continue;
  1135. }
  1136. if(methodName->s() == getMethodName()) {
  1137. list->append(createErrorResponse
  1138. (DL_ABORT_EX("Recursive system.multicall forbidden.")));
  1139. continue;
  1140. }
  1141. SharedHandle<XmlRpcMethod> method =
  1142. XmlRpcMethodFactory::create(methodName->s());
  1143. XmlRpcRequest innerReq
  1144. (methodName->s(), static_pointer_cast<List>(methodDict->get(KEY_PARAMS)));
  1145. XmlRpcResponse res = method->execute(innerReq, e);
  1146. if(res.code == 0) {
  1147. SharedHandle<List> l = List::g();
  1148. l->append(res.param);
  1149. list->append(l);
  1150. } else {
  1151. list->append(res.param);
  1152. }
  1153. }
  1154. return list;
  1155. }
  1156. SharedHandle<ValueBase> NoSuchMethodXmlRpcMethod::process
  1157. (const XmlRpcRequest& req, DownloadEngine* e)
  1158. {
  1159. throw DL_ABORT_EX
  1160. (StringFormat("No such method: %s", req.methodName.c_str()).str());
  1161. }
  1162. } // namespace xmlrpc
  1163. } // namespace aria2