RpcMethodImpl.cc 49 KB

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