MultiUrlRequestInfo.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 "StatCalc.h"
  51. #include "CookieStorage.h"
  52. #include "File.h"
  53. #include "Netrc.h"
  54. #include "AuthConfigFactory.h"
  55. #include "SessionSerializer.h"
  56. #include "TimeA2.h"
  57. #include "fmt.h"
  58. #include "SocketCore.h"
  59. #include "OutputFile.h"
  60. #include "UriListParser.h"
  61. #include "SingletonHolder.h"
  62. #include "Notifier.h"
  63. #ifdef ENABLE_WEBSOCKET
  64. # include "WebSocketSessionMan.h"
  65. #else // !ENABLE_WEBSOCKET
  66. # include "NullWebSocketSessionMan.h"
  67. #endif // !ENABLE_WEBSOCKET
  68. #ifdef ENABLE_SSL
  69. # include "TLSContext.h"
  70. #endif // ENABLE_SSL
  71. #ifdef ENABLE_ASYNC_DNS
  72. #include "AsyncNameResolver.h"
  73. #endif // ENABLE_ASYNC_DNS
  74. namespace aria2 {
  75. namespace global {
  76. extern volatile sig_atomic_t globalHaltRequested;
  77. } // namespace global
  78. namespace {
  79. void handler(int signal) {
  80. if(
  81. #ifdef SIGHUP
  82. signal == SIGHUP ||
  83. #endif // SIGHUP
  84. signal == SIGTERM) {
  85. if(global::globalHaltRequested == 0 || global::globalHaltRequested == 2) {
  86. global::globalHaltRequested = 3;
  87. }
  88. } else {
  89. if(global::globalHaltRequested == 0) {
  90. global::globalHaltRequested = 1;
  91. } else if(global::globalHaltRequested == 2) {
  92. global::globalHaltRequested = 3;
  93. }
  94. }
  95. }
  96. } // namespace
  97. MultiUrlRequestInfo::MultiUrlRequestInfo
  98. (std::vector<SharedHandle<RequestGroup> >& requestGroups,
  99. const SharedHandle<Option>& op,
  100. const SharedHandle<StatCalc>& statCalc,
  101. const SharedHandle<OutputFile>& summaryOut,
  102. const SharedHandle<UriListParser>& uriListParser)
  103. : option_(op),
  104. statCalc_(statCalc),
  105. summaryOut_(summaryOut),
  106. uriListParser_(uriListParser),
  107. useSignalHandler_(true)
  108. {
  109. #ifdef HAVE_SIGACTION
  110. sigemptyset(&mask_);
  111. #else // !HAVE_SIGACTION
  112. mask_ = 0;
  113. #endif // !HAVE_SIGACTION
  114. requestGroups_.swap(requestGroups);
  115. }
  116. MultiUrlRequestInfo::~MultiUrlRequestInfo() {}
  117. void MultiUrlRequestInfo::printMessageForContinue()
  118. {
  119. summaryOut_->printf
  120. ("\n%s\n%s\n",
  121. _("aria2 will resume download if the transfer is restarted."),
  122. _("If there are any errors, then see the log file. See '-l' option in help/man page for details."));
  123. }
  124. int MultiUrlRequestInfo::prepare()
  125. {
  126. global::globalHaltRequested = 0;
  127. try {
  128. SharedHandle<Notifier> notifier(new Notifier());
  129. SingletonHolder<Notifier>::instance(notifier);
  130. #ifdef ENABLE_SSL
  131. if(option_->getAsBool(PREF_ENABLE_RPC) &&
  132. option_->getAsBool(PREF_RPC_SECURE)) {
  133. if(!option_->blank(PREF_RPC_CERTIFICATE)
  134. #ifndef HAVE_APPLETLS
  135. && !option_->blank(PREF_RPC_PRIVATE_KEY)
  136. #endif // HAVE_APPLETLS
  137. ) {
  138. // We set server TLS context to the SocketCore before creating
  139. // DownloadEngine instance.
  140. SharedHandle<TLSContext> svTlsContext(TLSContext::make(TLS_SERVER));
  141. svTlsContext->addCredentialFile(option_->get(PREF_RPC_CERTIFICATE),
  142. option_->get(PREF_RPC_PRIVATE_KEY));
  143. SocketCore::setServerTLSContext(svTlsContext);
  144. } else {
  145. throw DL_ABORT_EX("Specify --rpc-certificate and --rpc-private-key "
  146. "options in order to use secure RPC.");
  147. }
  148. }
  149. #endif // ENABLE_SSL
  150. e_ = DownloadEngineFactory().newDownloadEngine(option_.get(),
  151. requestGroups_);
  152. // Avoid keeping RequestGroups alive longer than necessary
  153. requestGroups_.clear();
  154. #ifdef ENABLE_WEBSOCKET
  155. if(option_->getAsBool(PREF_ENABLE_RPC)) {
  156. SharedHandle<rpc::WebSocketSessionMan> wsSessionMan
  157. (new rpc::WebSocketSessionMan());
  158. e_->setWebSocketSessionMan(wsSessionMan);
  159. SingletonHolder<Notifier>::instance()->addDownloadEventListener
  160. (wsSessionMan);
  161. }
  162. #endif // ENABLE_WEBSOCKET
  163. if(!option_->blank(PREF_LOAD_COOKIES)) {
  164. File cookieFile(option_->get(PREF_LOAD_COOKIES));
  165. if(cookieFile.isFile() &&
  166. e_->getCookieStorage()->load(cookieFile.getPath(),
  167. Time().getTime())) {
  168. A2_LOG_INFO(fmt("Loaded cookies from '%s'.",
  169. cookieFile.getPath().c_str()));
  170. } else {
  171. A2_LOG_ERROR(fmt(MSG_LOADING_COOKIE_FAILED,
  172. cookieFile.getPath().c_str()));
  173. }
  174. }
  175. SharedHandle<AuthConfigFactory> authConfigFactory(new AuthConfigFactory());
  176. File netrccf(option_->get(PREF_NETRC_PATH));
  177. if(!option_->getAsBool(PREF_NO_NETRC) && netrccf.isFile()) {
  178. #ifdef __MINGW32__
  179. // Windows OS does not have permission, so set it to 0.
  180. mode_t mode = 0;
  181. #else // !__MINGW32__
  182. mode_t mode = netrccf.mode();
  183. #endif // !__MINGW32__
  184. if(mode&(S_IRWXG|S_IRWXO)) {
  185. A2_LOG_NOTICE(fmt(MSG_INCORRECT_NETRC_PERMISSION,
  186. option_->get(PREF_NETRC_PATH).c_str()));
  187. } else {
  188. SharedHandle<Netrc> netrc(new Netrc());
  189. netrc->parse(option_->get(PREF_NETRC_PATH));
  190. authConfigFactory->setNetrc(netrc);
  191. }
  192. }
  193. e_->setAuthConfigFactory(authConfigFactory);
  194. #ifdef ENABLE_SSL
  195. SharedHandle<TLSContext> clTlsContext(TLSContext::make(TLS_CLIENT));
  196. if(!option_->blank(PREF_CERTIFICATE) &&
  197. !option_->blank(PREF_PRIVATE_KEY)) {
  198. clTlsContext->addCredentialFile(option_->get(PREF_CERTIFICATE),
  199. option_->get(PREF_PRIVATE_KEY));
  200. }
  201. if(!option_->blank(PREF_CA_CERTIFICATE)) {
  202. if(!clTlsContext->addTrustedCACertFile
  203. (option_->get(PREF_CA_CERTIFICATE))) {
  204. A2_LOG_INFO(MSG_WARN_NO_CA_CERT);
  205. }
  206. } else if(option_->getAsBool(PREF_CHECK_CERTIFICATE)) {
  207. if(!clTlsContext->addSystemTrustedCACerts()) {
  208. A2_LOG_INFO(MSG_WARN_NO_CA_CERT);
  209. }
  210. }
  211. clTlsContext->setVerifyPeer(option_->getAsBool(PREF_CHECK_CERTIFICATE));
  212. SocketCore::setClientTLSContext(clTlsContext);
  213. #endif
  214. #ifdef HAVE_ARES_ADDR_NODE
  215. ares_addr_node* asyncDNSServers =
  216. parseAsyncDNSServers(option_->get(PREF_ASYNC_DNS_SERVER));
  217. e_->setAsyncDNSServers(asyncDNSServers);
  218. #endif // HAVE_ARES_ADDR_NODE
  219. if(!Timer::monotonicClock()) {
  220. A2_LOG_WARN("Don't change system time while aria2c is running."
  221. " Doing this may make aria2c hang for long time.");
  222. }
  223. std::string serverStatIf = option_->get(PREF_SERVER_STAT_IF);
  224. if(!serverStatIf.empty()) {
  225. e_->getRequestGroupMan()->loadServerStat(serverStatIf);
  226. e_->getRequestGroupMan()->removeStaleServerStat
  227. (option_->getAsInt(PREF_SERVER_STAT_TIMEOUT));
  228. }
  229. e_->setStatCalc(statCalc_);
  230. if(uriListParser_) {
  231. e_->getRequestGroupMan()->setUriListParser(uriListParser_);
  232. }
  233. if(useSignalHandler_) {
  234. setupSignalHandlers();
  235. }
  236. e_->getRequestGroupMan()->getNetStat().downloadStart();
  237. } catch(RecoverableException& e) {
  238. SingletonHolder<Notifier>::clear();
  239. if(useSignalHandler_) {
  240. resetSignalHandlers();
  241. }
  242. return -1;
  243. }
  244. return 0;
  245. }
  246. error_code::Value MultiUrlRequestInfo::getResult()
  247. {
  248. error_code::Value returnValue = error_code::FINISHED;
  249. if(!option_->blank(PREF_SAVE_COOKIES)) {
  250. e_->getCookieStorage()->saveNsFormat(option_->get(PREF_SAVE_COOKIES));
  251. }
  252. const std::string& serverStatOf = option_->get(PREF_SERVER_STAT_OF);
  253. if(!serverStatOf.empty()) {
  254. e_->getRequestGroupMan()->saveServerStat(serverStatOf);
  255. }
  256. e_->getRequestGroupMan()->showDownloadResults
  257. (*summaryOut_, option_->get(PREF_DOWNLOAD_RESULT) == A2_V_FULL);
  258. summaryOut_->flush();
  259. RequestGroupMan::DownloadStat s =
  260. e_->getRequestGroupMan()->getDownloadStat();
  261. if(!s.allCompleted()) {
  262. printMessageForContinue();
  263. if(s.getLastErrorResult() == error_code::FINISHED &&
  264. s.getInProgress() > 0) {
  265. returnValue = error_code::IN_PROGRESS;
  266. } else {
  267. returnValue = s.getLastErrorResult();
  268. }
  269. }
  270. SessionSerializer sessionSerializer(e_->getRequestGroupMan());
  271. // TODO Add option: --save-session-status=error,inprogress,waiting
  272. if(!option_->blank(PREF_SAVE_SESSION)) {
  273. const std::string& filename = option_->get(PREF_SAVE_SESSION);
  274. if(sessionSerializer.save(filename)) {
  275. A2_LOG_NOTICE(fmt(_("Serialized session to '%s' successfully."),
  276. filename.c_str()));
  277. } else {
  278. A2_LOG_NOTICE(fmt(_("Failed to serialize session to '%s'."),
  279. filename.c_str()));
  280. }
  281. }
  282. SingletonHolder<Notifier>::clear();
  283. return returnValue;
  284. }
  285. error_code::Value MultiUrlRequestInfo::execute()
  286. {
  287. if(prepare() != 0) {
  288. return error_code::UNKNOWN_ERROR;
  289. }
  290. // TODO Enclosed in try..catch block for just in case. Really need
  291. // this?
  292. try {
  293. e_->run();
  294. } catch(RecoverableException& e) {
  295. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  296. }
  297. error_code::Value returnValue = getResult();
  298. if(useSignalHandler_) {
  299. resetSignalHandlers();
  300. }
  301. return returnValue;
  302. }
  303. void MultiUrlRequestInfo::setupSignalHandlers()
  304. {
  305. #ifdef HAVE_SIGACTION
  306. sigemptyset(&mask_);
  307. #else // !HAVE_SIGACTION
  308. mask_ = 0;
  309. #endif // !HAVE_SIGACTION
  310. #ifdef SIGPIPE
  311. util::setGlobalSignalHandler(SIGPIPE, &mask_, SIG_IGN, 0);
  312. #endif // SIGPIPE
  313. #ifdef SIGCHLD
  314. // Avoid to create zombie process when forked child processes are
  315. // died.
  316. util::setGlobalSignalHandler(SIGCHLD, &mask_, SIG_IGN, 0);
  317. #endif // SIGCHILD
  318. #ifdef HAVE_SIGACTION
  319. sigaddset(&mask_, SIGINT);
  320. sigaddset(&mask_, SIGTERM);
  321. # ifdef SIGHUP
  322. sigaddset(&mask_, SIGHUP);
  323. # endif // SIGHUP
  324. #endif // HAVE_SIGACTION
  325. #ifdef SIGHUP
  326. util::setGlobalSignalHandler(SIGHUP, &mask_, handler, 0);
  327. #endif // SIGHUP
  328. util::setGlobalSignalHandler(SIGINT, &mask_, handler, 0);
  329. util::setGlobalSignalHandler(SIGTERM, &mask_, handler, 0);
  330. }
  331. void MultiUrlRequestInfo::resetSignalHandlers()
  332. {
  333. #ifdef HAVE_SIGACTION
  334. sigemptyset(&mask_);
  335. #endif // HAVE_SIGACTION
  336. #ifdef SIGHUP
  337. util::setGlobalSignalHandler(SIGHUP, &mask_, SIG_DFL, 0);
  338. #endif // SIGHUP
  339. util::setGlobalSignalHandler(SIGINT, &mask_, SIG_DFL, 0);
  340. util::setGlobalSignalHandler(SIGTERM, &mask_, SIG_DFL, 0);
  341. #ifdef SIGCHLD
  342. util::setGlobalSignalHandler(SIGCHLD, &mask_, SIG_DFL, 0);
  343. #endif // SIGCHILD
  344. #ifdef SIGPIPE
  345. util::setGlobalSignalHandler(SIGPIPE, &mask_, SIG_DFL, 0);
  346. #endif // SIGPIPE
  347. }
  348. const SharedHandle<DownloadEngine>&
  349. MultiUrlRequestInfo::getDownloadEngine() const
  350. {
  351. return e_;
  352. }
  353. } // namespace aria2