XmlRpcMethodImpl.cc 42 KB

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