RpcMethodImpl.cc 55 KB

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