MultiUrlRequestInfo.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 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 "MultiUrlRequestInfo.h"
  36. #include <signal.h>
  37. #include <cstring>
  38. #include <ostream>
  39. #include "RequestGroupMan.h"
  40. #include "DownloadEngine.h"
  41. #include "LogFactory.h"
  42. #include "Logger.h"
  43. #include "RequestGroup.h"
  44. #include "prefs.h"
  45. #include "DownloadEngineFactory.h"
  46. #include "RecoverableException.h"
  47. #include "message.h"
  48. #include "util.h"
  49. #include "Option.h"
  50. #include "ConsoleStatCalc.h"
  51. #include "NullStatCalc.h"
  52. #include "CookieStorage.h"
  53. #include "File.h"
  54. #include "Netrc.h"
  55. #include "AuthConfigFactory.h"
  56. #include "SessionSerializer.h"
  57. #include "TimeA2.h"
  58. #include "fmt.h"
  59. #include "SocketCore.h"
  60. #include "NullOutputFile.h"
  61. #include "UriListParser.h"
  62. #include "SingletonHolder.h"
  63. #include "Notifier.h"
  64. #include "console.h"
  65. #ifdef ENABLE_WEBSOCKET
  66. #include "WebSocketSessionMan.h"
  67. #else // !ENABLE_WEBSOCKET
  68. #include "NullWebSocketSessionMan.h"
  69. #endif // !ENABLE_WEBSOCKET
  70. #ifdef ENABLE_SSL
  71. #include "TLSContext.h"
  72. #endif // ENABLE_SSL
  73. #ifdef ENABLE_ASYNC_DNS
  74. #include "AsyncNameResolver.h"
  75. #endif // ENABLE_ASYNC_DNS
  76. namespace aria2 {
  77. namespace global {
  78. extern volatile sig_atomic_t globalHaltRequested;
  79. } // namespace global
  80. namespace {
  81. #ifdef _WIN32
  82. static const DWORD mainThread = GetCurrentThreadId();
  83. #endif
  84. static void handler(int signal)
  85. {
  86. if (
  87. #ifdef SIGHUP
  88. signal == SIGHUP ||
  89. #endif // SIGHUP
  90. signal == SIGTERM) {
  91. if (global::globalHaltRequested <= 2) {
  92. global::globalHaltRequested = 3;
  93. }
  94. #ifdef _WIN32
  95. if (::GetCurrentThreadId() != mainThread) {
  96. // SIGTERM may arrive on another thread (via SetConsoleCtrlHandler), and
  97. // the process will be forcefully terminated as soon as that thread is
  98. // done. So better make sure it isn't done prematurely. ;)
  99. while (global::globalHaltRequested != 5) {
  100. ::Sleep(100); // Yeah, semi-busy waiting for now.
  101. }
  102. }
  103. #endif
  104. return;
  105. }
  106. // SIGINT
  107. if (global::globalHaltRequested == 0) {
  108. global::globalHaltRequested = 1;
  109. return;
  110. }
  111. if (global::globalHaltRequested == 2) {
  112. global::globalHaltRequested = 3;
  113. return;
  114. }
  115. }
  116. } // namespace
  117. namespace {
  118. std::unique_ptr<StatCalc> getStatCalc(const std::shared_ptr<Option>& op)
  119. {
  120. if (op->getAsBool(PREF_QUIET)) {
  121. return make_unique<NullStatCalc>();
  122. }
  123. auto impl = make_unique<ConsoleStatCalc>(
  124. std::chrono::seconds(op->getAsInt(PREF_SUMMARY_INTERVAL)),
  125. op->getAsBool(PREF_ENABLE_COLOR), op->getAsBool(PREF_HUMAN_READABLE));
  126. impl->setReadoutVisibility(op->getAsBool(PREF_SHOW_CONSOLE_READOUT));
  127. impl->setTruncate(op->getAsBool(PREF_TRUNCATE_CONSOLE_READOUT));
  128. return std::move(impl);
  129. }
  130. } // namespace
  131. MultiUrlRequestInfo::MultiUrlRequestInfo(
  132. std::vector<std::shared_ptr<RequestGroup>> requestGroups,
  133. const std::shared_ptr<Option>& op,
  134. const std::shared_ptr<UriListParser>& uriListParser)
  135. : requestGroups_(std::move(requestGroups)),
  136. option_(op),
  137. uriListParser_(uriListParser),
  138. useSignalHandler_(true)
  139. {
  140. #ifdef HAVE_SIGACTION
  141. sigemptyset(&mask_);
  142. #else // !HAVE_SIGACTION
  143. mask_ = 0;
  144. #endif // !HAVE_SIGACTION
  145. }
  146. MultiUrlRequestInfo::~MultiUrlRequestInfo() = default;
  147. void MultiUrlRequestInfo::printMessageForContinue()
  148. {
  149. if (!option_->getAsBool(PREF_QUIET)) {
  150. global::cout()->printf(
  151. "\n%s\n%s\n",
  152. _("aria2 will resume download if the transfer is restarted."),
  153. _("If there are any errors, then see the log file. See '-l' option in "
  154. "help/man page for details."));
  155. }
  156. }
  157. int MultiUrlRequestInfo::prepare()
  158. {
  159. global::globalHaltRequested = 0;
  160. try {
  161. SingletonHolder<Notifier>::instance(make_unique<Notifier>());
  162. #ifdef ENABLE_SSL
  163. if (option_->getAsBool(PREF_ENABLE_RPC) &&
  164. option_->getAsBool(PREF_RPC_SECURE)) {
  165. if (option_->blank(PREF_RPC_CERTIFICATE)) {
  166. throw DL_ABORT_EX("Specify --rpc-certificate and --rpc-private-key "
  167. "options in order to use secure RPC.");
  168. }
  169. // We set server TLS context to the SocketCore before creating
  170. // DownloadEngine instance.
  171. auto minTLSVer = util::toTLSVersion(option_->get(PREF_MIN_TLS_VERSION));
  172. std::shared_ptr<TLSContext> svTlsContext(
  173. TLSContext::make(TLS_SERVER, minTLSVer));
  174. if (!svTlsContext->addCredentialFile(
  175. option_->get(PREF_RPC_CERTIFICATE),
  176. option_->get(PREF_RPC_PRIVATE_KEY))) {
  177. throw DL_ABORT_EX("Loading private key and/or certificate for secure "
  178. "RPC failed.");
  179. }
  180. SocketCore::setServerTLSContext(svTlsContext);
  181. }
  182. #endif // ENABLE_SSL
  183. // RequestGroups will be transferred to DownloadEngine
  184. e_ = DownloadEngineFactory().newDownloadEngine(option_.get(),
  185. std::move(requestGroups_));
  186. #ifdef ENABLE_WEBSOCKET
  187. if (option_->getAsBool(PREF_ENABLE_RPC)) {
  188. e_->setWebSocketSessionMan(make_unique<rpc::WebSocketSessionMan>());
  189. SingletonHolder<Notifier>::instance()->addDownloadEventListener(
  190. e_->getWebSocketSessionMan().get());
  191. }
  192. #endif // ENABLE_WEBSOCKET
  193. if (!option_->blank(PREF_LOAD_COOKIES)) {
  194. File cookieFile(option_->get(PREF_LOAD_COOKIES));
  195. if (cookieFile.isFile() &&
  196. e_->getCookieStorage()->load(cookieFile.getPath(),
  197. Time().getTimeFromEpoch())) {
  198. A2_LOG_INFO(
  199. fmt("Loaded cookies from '%s'.", cookieFile.getPath().c_str()));
  200. }
  201. else {
  202. A2_LOG_ERROR(
  203. fmt(MSG_LOADING_COOKIE_FAILED, cookieFile.getPath().c_str()));
  204. }
  205. }
  206. auto authConfigFactory = make_unique<AuthConfigFactory>();
  207. File netrccf(option_->get(PREF_NETRC_PATH));
  208. if (!option_->getAsBool(PREF_NO_NETRC) && netrccf.isFile()) {
  209. #ifdef __MINGW32__
  210. // Windows OS does not have permission, so set it to 0.
  211. mode_t mode = 0;
  212. #else // !__MINGW32__
  213. mode_t mode = netrccf.mode();
  214. #endif // !__MINGW32__
  215. if (mode & (S_IRWXG | S_IRWXO)) {
  216. A2_LOG_NOTICE(fmt(MSG_INCORRECT_NETRC_PERMISSION,
  217. option_->get(PREF_NETRC_PATH).c_str()));
  218. }
  219. else {
  220. auto netrc = make_unique<Netrc>();
  221. netrc->parse(option_->get(PREF_NETRC_PATH));
  222. authConfigFactory->setNetrc(std::move(netrc));
  223. }
  224. }
  225. e_->setAuthConfigFactory(std::move(authConfigFactory));
  226. #ifdef ENABLE_SSL
  227. auto minTLSVer = util::toTLSVersion(option_->get(PREF_MIN_TLS_VERSION));
  228. std::shared_ptr<TLSContext> clTlsContext(
  229. TLSContext::make(TLS_CLIENT, minTLSVer));
  230. if (!option_->blank(PREF_CERTIFICATE)) {
  231. clTlsContext->addCredentialFile(option_->get(PREF_CERTIFICATE),
  232. option_->get(PREF_PRIVATE_KEY));
  233. }
  234. if (!option_->blank(PREF_CA_CERTIFICATE)) {
  235. if (!clTlsContext->addTrustedCACertFile(
  236. option_->get(PREF_CA_CERTIFICATE))) {
  237. A2_LOG_INFO(MSG_WARN_NO_CA_CERT);
  238. }
  239. }
  240. else if (option_->getAsBool(PREF_CHECK_CERTIFICATE)) {
  241. if (!clTlsContext->addSystemTrustedCACerts()) {
  242. A2_LOG_INFO(MSG_WARN_NO_CA_CERT);
  243. }
  244. }
  245. clTlsContext->setVerifyPeer(option_->getAsBool(PREF_CHECK_CERTIFICATE));
  246. SocketCore::setClientTLSContext(clTlsContext);
  247. #endif
  248. #ifdef HAVE_ARES_ADDR_NODE
  249. ares_addr_node* asyncDNSServers =
  250. parseAsyncDNSServers(option_->get(PREF_ASYNC_DNS_SERVER));
  251. e_->setAsyncDNSServers(asyncDNSServers);
  252. #endif // HAVE_ARES_ADDR_NODE
  253. std::string serverStatIf = option_->get(PREF_SERVER_STAT_IF);
  254. if (!serverStatIf.empty()) {
  255. e_->getRequestGroupMan()->loadServerStat(serverStatIf);
  256. e_->getRequestGroupMan()->removeStaleServerStat(
  257. std::chrono::seconds(option_->getAsInt(PREF_SERVER_STAT_TIMEOUT)));
  258. }
  259. e_->setStatCalc(getStatCalc(option_));
  260. if (uriListParser_) {
  261. e_->getRequestGroupMan()->setUriListParser(uriListParser_);
  262. }
  263. if (useSignalHandler_) {
  264. setupSignalHandlers();
  265. }
  266. e_->getRequestGroupMan()->getNetStat().downloadStart();
  267. }
  268. catch (RecoverableException& e) {
  269. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  270. SingletonHolder<Notifier>::clear();
  271. if (useSignalHandler_) {
  272. resetSignalHandlers();
  273. }
  274. return -1;
  275. }
  276. return 0;
  277. }
  278. error_code::Value MultiUrlRequestInfo::getResult()
  279. {
  280. error_code::Value returnValue = error_code::FINISHED;
  281. if (!option_->blank(PREF_SAVE_COOKIES)) {
  282. e_->getCookieStorage()->saveNsFormat(option_->get(PREF_SAVE_COOKIES));
  283. }
  284. const std::string& serverStatOf = option_->get(PREF_SERVER_STAT_OF);
  285. if (!serverStatOf.empty()) {
  286. e_->getRequestGroupMan()->saveServerStat(serverStatOf);
  287. }
  288. if (!option_->getAsBool(PREF_QUIET) &&
  289. option_->get(PREF_DOWNLOAD_RESULT) != A2_V_HIDE) {
  290. e_->getRequestGroupMan()->showDownloadResults(
  291. *global::cout(), option_->get(PREF_DOWNLOAD_RESULT) == A2_V_FULL);
  292. global::cout()->flush();
  293. }
  294. RequestGroupMan::DownloadStat s = e_->getRequestGroupMan()->getDownloadStat();
  295. if (!s.allCompleted()) {
  296. printMessageForContinue();
  297. if (s.getLastErrorResult() == error_code::FINISHED &&
  298. s.getInProgress() > 0) {
  299. returnValue = error_code::IN_PROGRESS;
  300. }
  301. else {
  302. returnValue = s.getLastErrorResult();
  303. }
  304. }
  305. SessionSerializer sessionSerializer{e_->getRequestGroupMan().get()};
  306. // TODO Add option: --save-session-status=error,inprogress,waiting
  307. if (!option_->blank(PREF_SAVE_SESSION)) {
  308. const std::string& filename = option_->get(PREF_SAVE_SESSION);
  309. if (sessionSerializer.save(filename)) {
  310. A2_LOG_NOTICE(
  311. fmt(_("Serialized session to '%s' successfully."), filename.c_str()));
  312. }
  313. else {
  314. A2_LOG_NOTICE(
  315. fmt(_("Failed to serialize session to '%s'."), filename.c_str()));
  316. }
  317. }
  318. SingletonHolder<Notifier>::clear();
  319. return returnValue;
  320. }
  321. error_code::Value MultiUrlRequestInfo::execute()
  322. {
  323. if (prepare() != 0) {
  324. return error_code::UNKNOWN_ERROR;
  325. }
  326. // TODO Enclosed in try..catch block for just in case. Really need
  327. // this?
  328. try {
  329. e_->run();
  330. }
  331. catch (RecoverableException& e) {
  332. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  333. }
  334. error_code::Value returnValue = getResult();
  335. if (useSignalHandler_) {
  336. resetSignalHandlers();
  337. }
  338. return returnValue;
  339. }
  340. void MultiUrlRequestInfo::setupSignalHandlers()
  341. {
  342. #ifdef HAVE_SIGACTION
  343. sigemptyset(&mask_);
  344. #else // !HAVE_SIGACTION
  345. mask_ = 0;
  346. #endif // !HAVE_SIGACTION
  347. #ifdef SIGPIPE
  348. util::setGlobalSignalHandler(SIGPIPE, &mask_, SIG_IGN, 0);
  349. #endif // SIGPIPE
  350. #ifdef SIGCHLD
  351. // Avoid to create zombie process when forked child processes are
  352. // died.
  353. util::setGlobalSignalHandler(SIGCHLD, &mask_, SIG_IGN, 0);
  354. #endif // SIGCHILD
  355. #ifdef HAVE_SIGACTION
  356. sigaddset(&mask_, SIGINT);
  357. sigaddset(&mask_, SIGTERM);
  358. #ifdef SIGHUP
  359. sigaddset(&mask_, SIGHUP);
  360. #endif // SIGHUP
  361. #endif // HAVE_SIGACTION
  362. #ifdef SIGHUP
  363. util::setGlobalSignalHandler(SIGHUP, &mask_, handler, 0);
  364. #endif // SIGHUP
  365. util::setGlobalSignalHandler(SIGINT, &mask_, handler, 0);
  366. util::setGlobalSignalHandler(SIGTERM, &mask_, handler, 0);
  367. }
  368. void MultiUrlRequestInfo::resetSignalHandlers()
  369. {
  370. #ifdef HAVE_SIGACTION
  371. sigemptyset(&mask_);
  372. #endif // HAVE_SIGACTION
  373. #ifdef SIGHUP
  374. util::setGlobalSignalHandler(SIGHUP, &mask_, SIG_DFL, 0);
  375. #endif // SIGHUP
  376. util::setGlobalSignalHandler(SIGINT, &mask_, SIG_DFL, 0);
  377. util::setGlobalSignalHandler(SIGTERM, &mask_, SIG_DFL, 0);
  378. #ifdef SIGCHLD
  379. util::setGlobalSignalHandler(SIGCHLD, &mask_, SIG_DFL, 0);
  380. #endif // SIGCHILD
  381. #ifdef SIGPIPE
  382. util::setGlobalSignalHandler(SIGPIPE, &mask_, SIG_DFL, 0);
  383. #endif // SIGPIPE
  384. }
  385. const std::unique_ptr<DownloadEngine>&
  386. MultiUrlRequestInfo::getDownloadEngine() const
  387. {
  388. return e_;
  389. }
  390. } // namespace aria2