HttpRequest.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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 "HttpRequest.h"
  36. #include <cassert>
  37. #include <numeric>
  38. #include <vector>
  39. #include "Segment.h"
  40. #include "Range.h"
  41. #include "CookieStorage.h"
  42. #include "Option.h"
  43. #include "util.h"
  44. #include "base64.h"
  45. #include "prefs.h"
  46. #include "AuthConfigFactory.h"
  47. #include "AuthConfig.h"
  48. #include "a2functional.h"
  49. #include "TimeA2.h"
  50. #include "array_fun.h"
  51. #include "Request.h"
  52. #include "DownloadHandlerConstants.h"
  53. #include "MessageDigest.h"
  54. namespace aria2 {
  55. const std::string HttpRequest::USER_AGENT("aria2");
  56. HttpRequest::HttpRequest()
  57. : cookieStorage_(nullptr),
  58. authConfigFactory_(nullptr),
  59. option_(nullptr),
  60. endOffsetOverride_(0),
  61. userAgent_(USER_AGENT),
  62. contentEncodingEnabled_(true),
  63. acceptMetalink_(false),
  64. noCache_(true),
  65. acceptGzip_(false),
  66. noWantDigest_(false)
  67. {
  68. }
  69. HttpRequest::~HttpRequest() {}
  70. void HttpRequest::setSegment(std::shared_ptr<Segment> segment)
  71. {
  72. segment_ = std::move(segment);
  73. }
  74. void HttpRequest::setRequest(std::shared_ptr<Request> request)
  75. {
  76. request_ = std::move(request);
  77. }
  78. int64_t HttpRequest::getStartByte() const
  79. {
  80. if (!segment_) {
  81. return 0;
  82. }
  83. return fileEntry_->gtoloff(segment_->getPositionToWrite());
  84. }
  85. int64_t HttpRequest::getEndByte() const
  86. {
  87. if (!segment_ || !request_) {
  88. return 0;
  89. }
  90. if (request_->isPipeliningEnabled()) {
  91. auto endByte = fileEntry_->gtoloff(segment_->getPosition() +
  92. segment_->getLength() - 1);
  93. return std::min(endByte, fileEntry_->getLength() - 1);
  94. }
  95. if (endOffsetOverride_ > 0) {
  96. return endOffsetOverride_ - 1;
  97. }
  98. return 0;
  99. }
  100. Range HttpRequest::getRange() const
  101. {
  102. // content-length is always 0
  103. if (!segment_) {
  104. return Range();
  105. }
  106. return Range(getStartByte(), getEndByte(), fileEntry_->getLength());
  107. }
  108. bool HttpRequest::isRangeSatisfied(const Range& range) const
  109. {
  110. if (!segment_) {
  111. return true;
  112. }
  113. return getStartByte() == range.startByte &&
  114. (getEndByte() == 0 || getEndByte() == range.endByte) &&
  115. (fileEntry_->getLength() == 0 ||
  116. fileEntry_->getLength() == range.entityLength);
  117. }
  118. namespace {
  119. std::string getHostText(const std::string& host, uint16_t port)
  120. {
  121. auto hosttext = host;
  122. if (!(port == 80 || port == 443)) {
  123. hosttext += ':';
  124. hosttext += util::uitos(port);
  125. }
  126. return hosttext;
  127. }
  128. } // namespace
  129. std::string HttpRequest::createRequest()
  130. {
  131. authConfig_ = authConfigFactory_->createAuthConfig(request_, option_);
  132. auto requestLine = request_->getMethod();
  133. requestLine += ' ';
  134. if (proxyRequest_) {
  135. if (getProtocol() == "ftp" && request_->getUsername().empty() &&
  136. authConfig_) {
  137. // Insert user into URI, like ftp://USER@host/
  138. auto uri = getCurrentURI();
  139. assert(uri.size() >= 6);
  140. uri.insert(6, util::percentEncode(authConfig_->getUser()) + '@');
  141. requestLine += uri;
  142. }
  143. else {
  144. requestLine += getCurrentURI();
  145. }
  146. }
  147. else {
  148. requestLine += getDir();
  149. requestLine += getFile();
  150. requestLine += getQuery();
  151. }
  152. requestLine += " HTTP/1.1\r\n";
  153. std::vector<std::pair<std::string, std::string>> builtinHds;
  154. builtinHds.reserve(20);
  155. builtinHds.emplace_back("User-Agent:", userAgent_);
  156. std::string acceptTypes = "*/*";
  157. if (acceptMetalink_) {
  158. // The mime types of Metalink are used for "transparent metalink".
  159. const auto metalinkTypes = getMetalinkContentTypes();
  160. for (size_t i = 0; metalinkTypes[i]; ++i) {
  161. acceptTypes += ',';
  162. acceptTypes += metalinkTypes[i];
  163. }
  164. }
  165. builtinHds.emplace_back("Accept:", acceptTypes);
  166. if (contentEncodingEnabled_) {
  167. std::string acceptableEncodings;
  168. #ifdef HAVE_ZLIB
  169. if (acceptGzip_) {
  170. acceptableEncodings += "deflate, gzip";
  171. }
  172. #endif // HAVE_ZLIB
  173. if (!acceptableEncodings.empty()) {
  174. builtinHds.emplace_back("Accept-Encoding:", acceptableEncodings);
  175. }
  176. }
  177. builtinHds.emplace_back("Host:", getHostText(getURIHost(), getPort()));
  178. if (noCache_) {
  179. builtinHds.emplace_back("Pragma:", "no-cache");
  180. builtinHds.emplace_back("Cache-Control:", "no-cache");
  181. }
  182. if (!request_->isKeepAliveEnabled() && !request_->isPipeliningEnabled()) {
  183. builtinHds.emplace_back("Connection:", "close");
  184. }
  185. if (segment_ && segment_->getLength() > 0 &&
  186. (request_->isPipeliningEnabled() || getStartByte() > 0 ||
  187. getEndByte() > 0)) {
  188. std::string rangeHeader = "bytes=";
  189. rangeHeader += util::uitos(getStartByte());
  190. rangeHeader += '-';
  191. if (request_->isPipeliningEnabled() || getEndByte() > 0) {
  192. // FTP via http proxy does not support endbytes, but in that
  193. // case, request_->isPipeliningEnabled() is false and
  194. // getEndByte() is 0.
  195. rangeHeader += util::itos(getEndByte());
  196. }
  197. builtinHds.emplace_back("Range:", rangeHeader);
  198. }
  199. if (proxyRequest_) {
  200. if (request_->isKeepAliveEnabled() || request_->isPipeliningEnabled()) {
  201. builtinHds.emplace_back("Connection:", "Keep-Alive");
  202. }
  203. }
  204. if (proxyRequest_ && !proxyRequest_->getUsername().empty()) {
  205. builtinHds.push_back(getProxyAuthString());
  206. }
  207. if (authConfig_) {
  208. auto authText = authConfig_->getAuthText();
  209. std::string val = "Basic ";
  210. val += base64::encode(std::begin(authText), std::end(authText));
  211. builtinHds.emplace_back("Authorization:", val);
  212. }
  213. if (!request_->getReferer().empty()) {
  214. builtinHds.emplace_back("Referer:", request_->getReferer());
  215. }
  216. if (cookieStorage_) {
  217. std::string cookiesValue;
  218. auto path = getDir();
  219. path += getFile();
  220. auto cookies = cookieStorage_->criteriaFind(
  221. getHost(), path, Time().getTimeFromEpoch(), getProtocol() == "https");
  222. for (auto c : cookies) {
  223. cookiesValue += c->toString();
  224. cookiesValue += ';';
  225. }
  226. if (!cookiesValue.empty()) {
  227. builtinHds.emplace_back("Cookie:", cookiesValue);
  228. }
  229. }
  230. if (!ifModSinceHeader_.empty()) {
  231. builtinHds.emplace_back("If-Modified-Since:", ifModSinceHeader_);
  232. }
  233. if (!noWantDigest_) {
  234. // Send Want-Digest header field with only limited hash algorithms:
  235. // SHA-512, SHA-256, and SHA-1.
  236. std::string wantDigest;
  237. if (MessageDigest::supports("sha-512")) {
  238. wantDigest += "SHA-512;q=1, ";
  239. }
  240. if (MessageDigest::supports("sha-256")) {
  241. wantDigest += "SHA-256;q=1, ";
  242. }
  243. if (MessageDigest::supports("sha-1")) {
  244. wantDigest += "SHA;q=0.1, ";
  245. }
  246. if (!wantDigest.empty()) {
  247. wantDigest.erase(wantDigest.size() - 2);
  248. builtinHds.emplace_back("Want-Digest:", wantDigest);
  249. }
  250. }
  251. for (const auto& builtinHd : builtinHds) {
  252. auto it = std::find_if(std::begin(headers_), std::end(headers_),
  253. [&builtinHd](const std::string& hd) {
  254. return util::istartsWith(hd, builtinHd.first);
  255. });
  256. if (it == std::end(headers_)) {
  257. requestLine += builtinHd.first;
  258. requestLine += ' ';
  259. requestLine += builtinHd.second;
  260. requestLine += "\r\n";
  261. }
  262. }
  263. // append additional headers given by user.
  264. for (const auto& hd : headers_) {
  265. requestLine += hd;
  266. requestLine += "\r\n";
  267. }
  268. requestLine += "\r\n";
  269. return requestLine;
  270. }
  271. std::string HttpRequest::createProxyRequest() const
  272. {
  273. assert(proxyRequest_);
  274. std::string requestLine = "CONNECT ";
  275. requestLine += getURIHost();
  276. requestLine += ':';
  277. requestLine += util::uitos(getPort());
  278. requestLine += " HTTP/1.1\r\nUser-Agent: ";
  279. requestLine += userAgent_;
  280. requestLine += "\r\nHost: ";
  281. requestLine += getURIHost();
  282. requestLine += ':';
  283. requestLine += util::uitos(getPort());
  284. requestLine += "\r\n";
  285. if (!proxyRequest_->getUsername().empty()) {
  286. auto auth = getProxyAuthString();
  287. requestLine += auth.first;
  288. requestLine += ' ';
  289. requestLine += auth.second;
  290. requestLine += "\r\n";
  291. }
  292. requestLine += "\r\n";
  293. return requestLine;
  294. }
  295. std::pair<std::string, std::string> HttpRequest::getProxyAuthString() const
  296. {
  297. auto authText = proxyRequest_->getUsername();
  298. authText += ':';
  299. authText += proxyRequest_->getPassword();
  300. std::string val = "Basic ";
  301. val += base64::encode(std::begin(authText), std::end(authText));
  302. return std::make_pair("Proxy-Authorization:", val);
  303. }
  304. void HttpRequest::enableContentEncoding() { contentEncodingEnabled_ = true; }
  305. void HttpRequest::disableContentEncoding() { contentEncodingEnabled_ = false; }
  306. void HttpRequest::addHeader(const std::string& headersString)
  307. {
  308. util::split(std::begin(headersString), std::end(headersString),
  309. std::back_inserter(headers_), '\n', true);
  310. }
  311. void HttpRequest::clearHeader() { headers_.clear(); }
  312. void HttpRequest::setCookieStorage(CookieStorage* cookieStorage)
  313. {
  314. cookieStorage_ = cookieStorage;
  315. }
  316. CookieStorage* HttpRequest::getCookieStorage() const { return cookieStorage_; }
  317. void HttpRequest::setAuthConfigFactory(AuthConfigFactory* factory)
  318. {
  319. authConfigFactory_ = factory;
  320. }
  321. void HttpRequest::setOption(const Option* option) { option_ = option; }
  322. void HttpRequest::setProxyRequest(std::shared_ptr<Request> proxyRequest)
  323. {
  324. proxyRequest_ = std::move(proxyRequest);
  325. }
  326. bool HttpRequest::isProxyRequestSet() const { return proxyRequest_.get(); }
  327. bool HttpRequest::authenticationUsed() const { return authConfig_.get(); }
  328. const std::unique_ptr<AuthConfig>& HttpRequest::getAuthConfig() const
  329. {
  330. return authConfig_;
  331. }
  332. int64_t HttpRequest::getEntityLength() const
  333. {
  334. assert(fileEntry_);
  335. return fileEntry_->getLength();
  336. }
  337. const std::string& HttpRequest::getHost() const { return request_->getHost(); }
  338. uint16_t HttpRequest::getPort() const { return request_->getPort(); }
  339. const std::string& HttpRequest::getMethod() const
  340. {
  341. return request_->getMethod();
  342. }
  343. const std::string& HttpRequest::getProtocol() const
  344. {
  345. return request_->getProtocol();
  346. }
  347. const std::string& HttpRequest::getCurrentURI() const
  348. {
  349. return request_->getCurrentUri();
  350. }
  351. const std::string& HttpRequest::getDir() const { return request_->getDir(); }
  352. const std::string& HttpRequest::getFile() const { return request_->getFile(); }
  353. const std::string& HttpRequest::getQuery() const
  354. {
  355. return request_->getQuery();
  356. }
  357. std::string HttpRequest::getURIHost() const { return request_->getURIHost(); }
  358. void HttpRequest::setUserAgent(std::string userAgent)
  359. {
  360. userAgent_ = std::move(userAgent);
  361. }
  362. void HttpRequest::setFileEntry(std::shared_ptr<FileEntry> fileEntry)
  363. {
  364. fileEntry_ = std::move(fileEntry);
  365. }
  366. void HttpRequest::setIfModifiedSinceHeader(std::string value)
  367. {
  368. ifModSinceHeader_ = std::move(value);
  369. }
  370. bool HttpRequest::conditionalRequest() const
  371. {
  372. if (!ifModSinceHeader_.empty()) {
  373. return true;
  374. }
  375. for (auto& h : headers_) {
  376. if (util::istartsWith(h, "if-modified-since") ||
  377. util::istartsWith(h, "if-none-match")) {
  378. return true;
  379. }
  380. }
  381. return false;
  382. }
  383. } // namespace aria2