MultiUrlRequestInfo.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. // TODO init mask_
  108. {
  109. requestGroups_.swap(requestGroups);
  110. }
  111. MultiUrlRequestInfo::~MultiUrlRequestInfo() {}
  112. void MultiUrlRequestInfo::printMessageForContinue()
  113. {
  114. summaryOut_->printf
  115. ("\n%s\n%s\n",
  116. _("aria2 will resume download if the transfer is restarted."),
  117. _("If there are any errors, then see the log file. See '-l' option in help/man page for details."));
  118. }
  119. int MultiUrlRequestInfo::prepare()
  120. {
  121. try {
  122. SharedHandle<rpc::WebSocketSessionMan> wsSessionMan;
  123. if(option_->getAsBool(PREF_ENABLE_RPC)) {
  124. wsSessionMan.reset(new rpc::WebSocketSessionMan());
  125. }
  126. SharedHandle<Notifier> notifier(new Notifier(wsSessionMan));
  127. SingletonHolder<Notifier>::instance(notifier);
  128. #ifdef ENABLE_SSL
  129. if(option_->getAsBool(PREF_ENABLE_RPC) &&
  130. option_->getAsBool(PREF_RPC_SECURE)) {
  131. if(!option_->blank(PREF_RPC_CERTIFICATE)
  132. #ifndef HAVE_APPLETLS
  133. && !option_->blank(PREF_RPC_PRIVATE_KEY)
  134. #endif // HAVE_APPLETLS
  135. ) {
  136. // We set server TLS context to the SocketCore before creating
  137. // DownloadEngine instance.
  138. SharedHandle<TLSContext> svTlsContext(TLSContext::make(TLS_SERVER));
  139. svTlsContext->addCredentialFile(option_->get(PREF_RPC_CERTIFICATE),
  140. option_->get(PREF_RPC_PRIVATE_KEY));
  141. SocketCore::setServerTLSContext(svTlsContext);
  142. } else {
  143. throw DL_ABORT_EX("Specify --rpc-certificate and --rpc-private-key "
  144. "options in order to use secure RPC.");
  145. }
  146. }
  147. #endif // ENABLE_SSL
  148. e_ = DownloadEngineFactory().newDownloadEngine(option_.get(),
  149. requestGroups_);
  150. // Avoid keeping RequestGroups alive longer than necessary
  151. requestGroups_.clear();
  152. if(!option_->blank(PREF_LOAD_COOKIES)) {
  153. File cookieFile(option_->get(PREF_LOAD_COOKIES));
  154. if(cookieFile.isFile() &&
  155. e_->getCookieStorage()->load(cookieFile.getPath(),
  156. Time().getTime())) {
  157. A2_LOG_INFO(fmt("Loaded cookies from '%s'.",
  158. cookieFile.getPath().c_str()));
  159. } else {
  160. A2_LOG_ERROR(fmt(MSG_LOADING_COOKIE_FAILED,
  161. cookieFile.getPath().c_str()));
  162. }
  163. }
  164. SharedHandle<AuthConfigFactory> authConfigFactory(new AuthConfigFactory());
  165. File netrccf(option_->get(PREF_NETRC_PATH));
  166. if(!option_->getAsBool(PREF_NO_NETRC) && netrccf.isFile()) {
  167. #ifdef __MINGW32__
  168. // Windows OS does not have permission, so set it to 0.
  169. mode_t mode = 0;
  170. #else // !__MINGW32__
  171. mode_t mode = netrccf.mode();
  172. #endif // !__MINGW32__
  173. if(mode&(S_IRWXG|S_IRWXO)) {
  174. A2_LOG_NOTICE(fmt(MSG_INCORRECT_NETRC_PERMISSION,
  175. option_->get(PREF_NETRC_PATH).c_str()));
  176. } else {
  177. SharedHandle<Netrc> netrc(new Netrc());
  178. netrc->parse(option_->get(PREF_NETRC_PATH));
  179. authConfigFactory->setNetrc(netrc);
  180. }
  181. }
  182. e_->setAuthConfigFactory(authConfigFactory);
  183. #ifdef ENABLE_SSL
  184. SharedHandle<TLSContext> clTlsContext(TLSContext::make(TLS_CLIENT));
  185. if(!option_->blank(PREF_CERTIFICATE) &&
  186. !option_->blank(PREF_PRIVATE_KEY)) {
  187. clTlsContext->addCredentialFile(option_->get(PREF_CERTIFICATE),
  188. option_->get(PREF_PRIVATE_KEY));
  189. }
  190. if(!option_->blank(PREF_CA_CERTIFICATE)) {
  191. if(!clTlsContext->addTrustedCACertFile
  192. (option_->get(PREF_CA_CERTIFICATE))) {
  193. A2_LOG_INFO(MSG_WARN_NO_CA_CERT);
  194. }
  195. } else if(option_->getAsBool(PREF_CHECK_CERTIFICATE)) {
  196. if(!clTlsContext->addSystemTrustedCACerts()) {
  197. A2_LOG_INFO(MSG_WARN_NO_CA_CERT);
  198. }
  199. }
  200. clTlsContext->setVerifyPeer(option_->getAsBool(PREF_CHECK_CERTIFICATE));
  201. SocketCore::setClientTLSContext(clTlsContext);
  202. #endif
  203. #ifdef HAVE_ARES_ADDR_NODE
  204. ares_addr_node* asyncDNSServers =
  205. parseAsyncDNSServers(option_->get(PREF_ASYNC_DNS_SERVER));
  206. e_->setAsyncDNSServers(asyncDNSServers);
  207. #endif // HAVE_ARES_ADDR_NODE
  208. if(!Timer::monotonicClock()) {
  209. A2_LOG_WARN("Don't change system time while aria2c is running."
  210. " Doing this may make aria2c hang for long time.");
  211. }
  212. std::string serverStatIf = option_->get(PREF_SERVER_STAT_IF);
  213. if(!serverStatIf.empty()) {
  214. e_->getRequestGroupMan()->loadServerStat(serverStatIf);
  215. e_->getRequestGroupMan()->removeStaleServerStat
  216. (option_->getAsInt(PREF_SERVER_STAT_TIMEOUT));
  217. }
  218. e_->setStatCalc(statCalc_);
  219. if(uriListParser_) {
  220. e_->getRequestGroupMan()->setUriListParser(uriListParser_);
  221. }
  222. #ifdef HAVE_SIGACTION
  223. sigemptyset(&mask_);
  224. sigaddset(&mask_, SIGINT);
  225. sigaddset(&mask_, SIGTERM);
  226. #ifdef SIGHUP
  227. sigaddset(&mask_, SIGHUP);
  228. #endif // SIGHUP
  229. #else // !HAVE_SIGACTION
  230. mask_ = 0;
  231. #endif // !HAVE_SIGACTION
  232. #ifdef SIGHUP
  233. util::setGlobalSignalHandler(SIGHUP, &mask_, handler, 0);
  234. #endif // SIGHUP
  235. util::setGlobalSignalHandler(SIGINT, &mask_, handler, 0);
  236. util::setGlobalSignalHandler(SIGTERM, &mask_, handler, 0);
  237. e_->getRequestGroupMan()->getNetStat().downloadStart();
  238. } catch(RecoverableException& e) {
  239. SingletonHolder<Notifier>::clear();
  240. resetSignalHandlers();
  241. return -1;
  242. }
  243. return 0;
  244. }
  245. error_code::Value MultiUrlRequestInfo::getResult()
  246. {
  247. error_code::Value returnValue = error_code::FINISHED;
  248. if(!option_->blank(PREF_SAVE_COOKIES)) {
  249. e_->getCookieStorage()->saveNsFormat(option_->get(PREF_SAVE_COOKIES));
  250. }
  251. const std::string& serverStatOf = option_->get(PREF_SERVER_STAT_OF);
  252. if(!serverStatOf.empty()) {
  253. e_->getRequestGroupMan()->saveServerStat(serverStatOf);
  254. }
  255. e_->getRequestGroupMan()->showDownloadResults
  256. (*summaryOut_, option_->get(PREF_DOWNLOAD_RESULT) == A2_V_FULL);
  257. summaryOut_->flush();
  258. RequestGroupMan::DownloadStat s =
  259. e_->getRequestGroupMan()->getDownloadStat();
  260. if(!s.allCompleted()) {
  261. printMessageForContinue();
  262. if(s.getLastErrorResult() == error_code::FINISHED &&
  263. s.getInProgress() > 0) {
  264. returnValue = error_code::IN_PROGRESS;
  265. } else {
  266. returnValue = s.getLastErrorResult();
  267. }
  268. }
  269. SessionSerializer sessionSerializer(e_->getRequestGroupMan());
  270. // TODO Add option: --save-session-status=error,inprogress,waiting
  271. if(!option_->blank(PREF_SAVE_SESSION)) {
  272. const std::string& filename = option_->get(PREF_SAVE_SESSION);
  273. if(sessionSerializer.save(filename)) {
  274. A2_LOG_NOTICE(fmt(_("Serialized session to '%s' successfully."),
  275. filename.c_str()));
  276. } else {
  277. A2_LOG_NOTICE(fmt(_("Failed to serialize session to '%s'."),
  278. filename.c_str()));
  279. }
  280. }
  281. SingletonHolder<Notifier>::clear();
  282. return returnValue;
  283. }
  284. error_code::Value MultiUrlRequestInfo::execute()
  285. {
  286. if(prepare() != 0) {
  287. return error_code::UNKNOWN_ERROR;
  288. }
  289. // TODO Enclosed in try..catch block for just in case. Really need
  290. // this?
  291. try {
  292. e_->run();
  293. } catch(RecoverableException& e) {
  294. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  295. }
  296. error_code::Value returnValue = getResult();
  297. resetSignalHandlers();
  298. return returnValue;
  299. }
  300. void MultiUrlRequestInfo::resetSignalHandlers()
  301. {
  302. #ifdef HAVE_SIGACTION
  303. sigemptyset(&mask_);
  304. #endif // HAVE_SIGACTION
  305. #ifdef SIGHUP
  306. util::setGlobalSignalHandler(SIGHUP, &mask_, SIG_DFL, 0);
  307. #endif // SIGHUP
  308. util::setGlobalSignalHandler(SIGINT, &mask_, SIG_DFL, 0);
  309. util::setGlobalSignalHandler(SIGTERM, &mask_, SIG_DFL, 0);
  310. }
  311. const SharedHandle<DownloadEngine>&
  312. MultiUrlRequestInfo::getDownloadEngine() const
  313. {
  314. return e_;
  315. }
  316. } // namespace aria2