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