HttpRequest.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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. namespace aria2 {
  52. const std::string HttpRequest::USER_AGENT("aria2");
  53. HttpRequest::HttpRequest():contentEncodingEnabled_(true),
  54. userAgent_(USER_AGENT),
  55. noCache_(true),
  56. acceptGzip_(false),
  57. endOffsetOverride_(false)
  58. {}
  59. void HttpRequest::setSegment(const SharedHandle<Segment>& segment)
  60. {
  61. segment_ = segment;
  62. }
  63. void HttpRequest::setRequest(const SharedHandle<Request>& request)
  64. {
  65. request_ = request;
  66. }
  67. off_t HttpRequest::getStartByte() const
  68. {
  69. if(segment_.isNull()) {
  70. return 0;
  71. } else {
  72. return fileEntry_->gtoloff(segment_->getPositionToWrite());
  73. }
  74. }
  75. off_t HttpRequest::getEndByte() const
  76. {
  77. if(segment_.isNull() || request_.isNull()) {
  78. return 0;
  79. } else {
  80. if(request_->isPipeliningEnabled()) {
  81. off_t endByte =
  82. fileEntry_->gtoloff(segment_->getPosition()+segment_->getLength()-1);
  83. return std::min(endByte, static_cast<off_t>(fileEntry_->getLength()-1));
  84. } else {
  85. return 0;
  86. }
  87. }
  88. }
  89. RangeHandle HttpRequest::getRange() const
  90. {
  91. // content-length is always 0
  92. if(segment_.isNull()) {
  93. return SharedHandle<Range>(new Range());
  94. } else {
  95. return SharedHandle<Range>(new Range(getStartByte(), getEndByte(),
  96. fileEntry_->getLength()));
  97. }
  98. }
  99. bool HttpRequest::isRangeSatisfied(const RangeHandle& range) const
  100. {
  101. if(segment_.isNull()) {
  102. return true;
  103. }
  104. if((getStartByte() == range->getStartByte()) &&
  105. ((getEndByte() == 0) ||
  106. (getEndByte() == range->getEndByte())) &&
  107. ((fileEntry_->getLength() == 0) ||
  108. (fileEntry_->getLength() == range->getEntityLength()))) {
  109. return true;
  110. } else {
  111. return false;
  112. }
  113. }
  114. static std::string getHostText(const std::string& host, uint16_t port)
  115. {
  116. std::string hosttext = host;
  117. if(!(port == 80 || port == 443)) {
  118. strappend(hosttext, ":", util::uitos(port));
  119. }
  120. return hosttext;
  121. }
  122. std::string HttpRequest::createRequest()
  123. {
  124. authConfig_ = authConfigFactory_->createAuthConfig(request_, option_);
  125. std::string requestLine = request_->getMethod();
  126. requestLine += " ";
  127. if(!proxyRequest_.isNull()) {
  128. if(getProtocol() == Request::PROTO_FTP &&
  129. request_->getUsername().empty() && !authConfig_.isNull()) {
  130. // Insert user into URI, like ftp://USER@host/
  131. std::string uri = getCurrentURI();
  132. assert(uri.size() >= 6);
  133. uri.insert(6, util::percentEncode(authConfig_->getUser())+"@");
  134. requestLine += uri;
  135. } else {
  136. requestLine += getCurrentURI();
  137. }
  138. } else {
  139. if(getDir() == A2STR::SLASH_C) {
  140. requestLine += getDir();
  141. } else {
  142. requestLine += getDir();
  143. requestLine += A2STR::SLASH_C;
  144. }
  145. requestLine += getFile();
  146. requestLine += getQuery();
  147. }
  148. requestLine += " HTTP/1.1\r\n";
  149. std::vector<std::pair<std::string, std::string> > builtinHds;
  150. builtinHds.reserve(20);
  151. builtinHds.push_back(std::make_pair("User-Agent:", userAgent_));
  152. std::string acceptTypes = "*/*";
  153. for(std::vector<std::string>::const_iterator i = acceptTypes_.begin(),
  154. eoi = acceptTypes_.end(); i != eoi; ++i) {
  155. strappend(acceptTypes, ",", (*i));
  156. }
  157. builtinHds.push_back(std::make_pair("Accept:", acceptTypes));
  158. if(contentEncodingEnabled_) {
  159. std::string acceptableEncodings;
  160. #ifdef HAVE_LIBZ
  161. if(acceptGzip_) {
  162. acceptableEncodings += "deflate, gzip";
  163. }
  164. #endif // HAVE_LIBZ
  165. if(!acceptableEncodings.empty()) {
  166. builtinHds.push_back
  167. (std::make_pair("Accept-Encoding:", acceptableEncodings));
  168. }
  169. }
  170. builtinHds.push_back
  171. (std::make_pair("Host:", getHostText(getURIHost(), getPort())));
  172. if(noCache_) {
  173. builtinHds.push_back(std::make_pair("Pragma:", "no-cache"));
  174. builtinHds.push_back(std::make_pair("Cache-Control:", "no-cache"));
  175. }
  176. if(!request_->isKeepAliveEnabled() && !request_->isPipeliningEnabled()) {
  177. builtinHds.push_back(std::make_pair("Connection:", "close"));
  178. }
  179. if(!segment_.isNull() && segment_->getLength() > 0 &&
  180. (request_->isPipeliningEnabled() || getStartByte() > 0)) {
  181. std::string rangeHeader = "bytes=";
  182. rangeHeader += util::itos(getStartByte());
  183. rangeHeader += "-";
  184. if(request_->isPipeliningEnabled()) {
  185. rangeHeader += util::itos(getEndByte());
  186. } else if(getProtocol() != Request::PROTO_FTP && endOffsetOverride_ > 0) {
  187. // FTP via http proxy does not support endbytes
  188. rangeHeader += util::itos(endOffsetOverride_-1);
  189. }
  190. builtinHds.push_back(std::make_pair("Range:", rangeHeader));
  191. }
  192. if(!proxyRequest_.isNull()) {
  193. if(request_->isKeepAliveEnabled() || request_->isPipeliningEnabled()) {
  194. builtinHds.push_back(std::make_pair("Proxy-Connection:", "Keep-Alive"));
  195. } else {
  196. builtinHds.push_back(std::make_pair("Proxy-Connection:", "close"));
  197. }
  198. }
  199. if(!proxyRequest_.isNull() && !proxyRequest_->getUsername().empty()) {
  200. builtinHds.push_back(getProxyAuthString());
  201. }
  202. if(!authConfig_.isNull()) {
  203. builtinHds.push_back
  204. (std::make_pair("Authorization:",
  205. strconcat("Basic ",
  206. Base64::encode(authConfig_->getAuthText()))));
  207. }
  208. if(getPreviousURI().size()) {
  209. builtinHds.push_back(std::make_pair("Referer:", getPreviousURI()));
  210. }
  211. if(!cookieStorage_.isNull()) {
  212. std::string cookiesValue;
  213. std::vector<Cookie> cookies =
  214. cookieStorage_->criteriaFind(getHost(),
  215. getDir(),
  216. Time().getTime(),
  217. getProtocol() == Request::PROTO_HTTPS ?
  218. true : false);
  219. for(std::vector<Cookie>::const_iterator itr = cookies.begin(),
  220. eoi = cookies.end(); itr != eoi; ++itr) {
  221. strappend(cookiesValue, (*itr).toString(), ";");
  222. }
  223. if(!cookiesValue.empty()) {
  224. builtinHds.push_back(std::make_pair("Cookie:", cookiesValue));
  225. }
  226. }
  227. if(!ifModSinceHeader_.empty()) {
  228. builtinHds.push_back
  229. (std::make_pair("If-Modified-Since:", ifModSinceHeader_));
  230. }
  231. for(std::vector<std::pair<std::string, std::string> >::const_iterator i =
  232. builtinHds.begin(), eoi = builtinHds.end(); i != eoi; ++i) {
  233. std::vector<std::string>::const_iterator j = headers_.begin();
  234. std::vector<std::string>::const_iterator jend = headers_.end();
  235. for(; j != jend; ++j) {
  236. if(util::startsWith(*j, (*i).first)) {
  237. break;
  238. }
  239. }
  240. if(j == jend) {
  241. strappend(requestLine, (*i).first, " ", (*i).second, A2STR::CRLF);
  242. }
  243. }
  244. // append additional headers given by user.
  245. for(std::vector<std::string>::const_iterator i = headers_.begin(),
  246. eoi = headers_.end(); i != eoi; ++i) {
  247. strappend(requestLine, (*i), A2STR::CRLF);
  248. }
  249. requestLine += A2STR::CRLF;
  250. return requestLine;
  251. }
  252. std::string HttpRequest::createProxyRequest() const
  253. {
  254. assert(!proxyRequest_.isNull());
  255. std::string hostport = getURIHost();
  256. strappend(hostport, ":", util::uitos(getPort()));
  257. std::string requestLine = "CONNECT ";
  258. strappend(requestLine, hostport, " HTTP/1.1\r\n");
  259. strappend(requestLine, "User-Agent: ", userAgent_, "\r\n");
  260. strappend(requestLine, "Host: ", hostport, "\r\n");
  261. // TODO Is "Proxy-Connection" needed here?
  262. // if(request->isKeepAliveEnabled() || request->isPipeliningEnabled()) {
  263. // requestLine += "Proxy-Connection: Keep-Alive\r\n";
  264. // }else {
  265. // requestLine += "Proxy-Connection: close\r\n";
  266. // }
  267. if(!proxyRequest_->getUsername().empty()) {
  268. std::pair<std::string, std::string> auth = getProxyAuthString();
  269. strappend(requestLine, auth.first, " ", auth.second, A2STR::CRLF);
  270. }
  271. requestLine += A2STR::CRLF;
  272. return requestLine;
  273. }
  274. std::pair<std::string, std::string> HttpRequest::getProxyAuthString() const
  275. {
  276. return std::make_pair
  277. ("Proxy-Authorization:",
  278. strconcat("Basic ",
  279. Base64::encode(strconcat(proxyRequest_->getUsername(),
  280. ":",
  281. proxyRequest_->getPassword()))));
  282. }
  283. void HttpRequest::enableContentEncoding()
  284. {
  285. contentEncodingEnabled_ = true;
  286. }
  287. void HttpRequest::disableContentEncoding()
  288. {
  289. contentEncodingEnabled_ = false;
  290. }
  291. void HttpRequest::addHeader(const std::string& headersString)
  292. {
  293. std::vector<std::string> headers;
  294. util::split(headersString, std::back_inserter(headers), "\n", true);
  295. headers_.insert(headers_.end(), headers.begin(), headers.end());
  296. }
  297. void HttpRequest::addAcceptType(const std::string& type)
  298. {
  299. acceptTypes_.push_back(type);
  300. }
  301. void HttpRequest::setCookieStorage
  302. (const SharedHandle<CookieStorage>& cookieStorage)
  303. {
  304. cookieStorage_ = cookieStorage;
  305. }
  306. void HttpRequest::setAuthConfigFactory
  307. (const SharedHandle<AuthConfigFactory>& factory, const Option* option)
  308. {
  309. authConfigFactory_ = factory;
  310. option_ = option;
  311. }
  312. void HttpRequest::setProxyRequest(const SharedHandle<Request>& proxyRequest)
  313. {
  314. proxyRequest_ = proxyRequest;
  315. }
  316. bool HttpRequest::isProxyRequestSet() const
  317. {
  318. return !proxyRequest_.isNull();
  319. }
  320. bool HttpRequest::authenticationUsed() const
  321. {
  322. return !authConfig_.isNull();
  323. }
  324. const SharedHandle<AuthConfig>& HttpRequest::getAuthConfig() const
  325. {
  326. return authConfig_;
  327. }
  328. } // namespace aria2