RpcMethodImpl.cc 49 KB

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