HttpConnection.cc 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - a simple utility for downloading files faster
  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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  20. */
  21. /* copyright --> */
  22. #include "HttpConnection.h"
  23. #include "DlRetryEx.h"
  24. #include "Util.h"
  25. #include "Base64.h"
  26. #include "message.h"
  27. #include "prefs.h"
  28. HttpConnection::HttpConnection(int cuid, const Socket* socket, const Request* req, const Option* op, const Logger* logger):
  29. cuid(cuid), socket(socket), req(req), option(op), logger(logger), headerBufLength(0) {}
  30. void HttpConnection::sendRequest(const Segment& segment) const {
  31. string request = createRequest(segment);
  32. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  33. socket->writeData(request.c_str(), request.size());
  34. }
  35. void HttpConnection::sendProxyRequest() const {
  36. string request =
  37. string("CONNECT ")+req->getHost()+":"+Util::llitos(req->getPort())+
  38. string(" HTTP/1.1\r\n")+
  39. "User-Agent: "+USER_AGENT+"\r\n"+
  40. "Proxy-Connection: close\r\n"+
  41. "Host: "+getHost(req->getHost(), req->getPort())+"\r\n";
  42. if(useProxyAuth()) {
  43. request += getProxyAuthString();
  44. }
  45. request += "\r\n";
  46. logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
  47. socket->writeData(request.c_str(), request.size());
  48. }
  49. string HttpConnection::getProxyAuthString() const {
  50. return "Proxy-Authorization: Basic "+
  51. Base64::encode(option->get(PREF_HTTP_PROXY_USER)+":"+
  52. option->get(PREF_HTTP_PROXY_PASSWD))+"\r\n";
  53. }
  54. string HttpConnection::getHost(const string& host, int port) const {
  55. return host+(port == 80 || port == 443 ? "" : ":"+Util::llitos(port));
  56. }
  57. string HttpConnection::createRequest(const Segment& segment) const {
  58. string request = string("GET ")+
  59. (req->getProtocol() == "ftp" || useProxy() && useProxyGet() ?
  60. req->getCurrentUrl() :
  61. ((req->getDir() == "/" ? "/" : req->getDir()+"/")+req->getFile()))+
  62. string(" HTTP/1.1\r\n")+
  63. "User-Agent: "+USER_AGENT+"\r\n"+
  64. "Connection: close\r\n"+
  65. "Accept: */*\r\n"+ /* */
  66. "Host: "+getHost(req->getHost(), req->getPort())+"\r\n"+
  67. "Pragma: no-cache\r\n"+
  68. "Cache-Control: no-cache\r\n";
  69. if(segment.sp+segment.ds > 0) {
  70. request += "Range: bytes="+
  71. Util::llitos(segment.sp+segment.ds)+"-"+Util::llitos(segment.ep)+"\r\n";
  72. }
  73. if(useProxy() && useProxyAuth() && useProxyGet()) {
  74. request += "Proxy-Connection: close\r\n";
  75. request += getProxyAuthString();
  76. }
  77. if(option->get(PREF_HTTP_AUTH_SCHEME) == V_BASIC) {
  78. request += "Authorization: Basic "+
  79. Base64::encode(option->get(PREF_HTTP_USER)+":"+
  80. option->get(PREF_HTTP_PASSWD))+"\r\n";
  81. }
  82. if(req->getPreviousUrl().size()) {
  83. request += "Referer: "+req->getPreviousUrl()+"\r\n";
  84. }
  85. string cookiesValue;
  86. vector<Cookie> cookies = req->cookieBox->criteriaFind(req->getHost(), req->getDir(), req->getProtocol() == "https" ? true : false);
  87. for(vector<Cookie>::const_iterator itr = cookies.begin(); itr != cookies.end(); itr++) {
  88. cookiesValue += (*itr).toString()+";";
  89. }
  90. if(cookiesValue.size()) {
  91. request += string("Cookie: ")+cookiesValue+"\r\n";
  92. }
  93. request += "\r\n";
  94. return request;
  95. }
  96. int HttpConnection::findEndOfHeader(const char* buf, const char* substr, int bufLength) const {
  97. const char* p = buf;
  98. while(bufLength > p-buf && bufLength-(p-buf) >= (int)strlen(substr)) {
  99. if(memcmp(p, substr, strlen(substr)) == 0) {
  100. return p-buf;
  101. }
  102. p++;
  103. }
  104. return -1;
  105. }
  106. int HttpConnection::receiveResponse(HttpHeader& headers) {
  107. //char buf[512];
  108. string header;
  109. int delimiterSwith = 0;
  110. char* delimiters[] = { "\r\n", "\n" };
  111. int size = HEADERBUF_SIZE-headerBufLength;
  112. if(size < 0) {
  113. // TODO too large header
  114. throw new DlRetryEx("too large header > 4096");
  115. }
  116. socket->peekData(headerBuf+headerBufLength, size);
  117. if(size == 0) {
  118. throw new DlRetryEx(EX_INVALID_RESPONSE);
  119. }
  120. //buf[size] = '\0';
  121. int hlenTemp = headerBufLength+size;
  122. //header += buf;
  123. //string::size_type p;
  124. int eohIndex;
  125. if((eohIndex = findEndOfHeader(headerBuf, "\r\n\r\n", hlenTemp)) == -1 &&
  126. (eohIndex = findEndOfHeader(headerBuf, "\n\n", hlenTemp)) == -1) {
  127. socket->readData(headerBuf+headerBufLength, size);
  128. } else {
  129. if(eohIndex[headerBuf] == '\n') {
  130. // for crapping non-standard HTTP server
  131. delimiterSwith = 1;
  132. } else {
  133. delimiterSwith = 0;
  134. }
  135. headerBuf[eohIndex+strlen(delimiters[delimiterSwith])*2] = '\0';
  136. header = headerBuf;
  137. size = eohIndex+strlen(delimiters[delimiterSwith])*2-headerBufLength;
  138. socket->readData(headerBuf+headerBufLength, size);
  139. }
  140. if(!Util::endsWith(header, "\r\n\r\n") && !Util::endsWith(header, "\n\n")) {
  141. return 0;
  142. }
  143. // OK, we got all headers.
  144. logger->info(MSG_RECEIVE_RESPONSE, cuid, header.c_str());
  145. string::size_type p, np;
  146. p = np = 0;
  147. np = header.find(delimiters[delimiterSwith], p);
  148. if(np == string::npos) {
  149. throw new DlRetryEx(EX_NO_STATUS_HEADER);
  150. }
  151. // check HTTP status value
  152. string status = header.substr(9, 3);
  153. p = np+2;
  154. // retreive status name-value pairs, then push these into map
  155. while((np = header.find(delimiters[delimiterSwith], p)) != string::npos && np != p) {
  156. string line = header.substr(p, np-p);
  157. p = np+2;
  158. pair<string, string> hp;
  159. Util::split(hp, line, ':');
  160. headers.put(hp.first, hp.second);
  161. }
  162. return (int)strtol(status.c_str(), NULL, 10);
  163. }
  164. bool HttpConnection::useProxy() const {
  165. return option->get(PREF_HTTP_PROXY_ENABLED) == V_TRUE;
  166. }
  167. bool HttpConnection::useProxyAuth() const {
  168. return option->get(PREF_HTTP_PROXY_AUTH_ENABLED) == V_TRUE;
  169. }
  170. bool HttpConnection::useProxyGet() const {
  171. return option->get(PREF_HTTP_PROXY_METHOD) == V_GET;
  172. }