HttpResponseCommand.cc 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 "HttpResponseCommand.h"
  36. #include "DlAbortEx.h"
  37. #include "DlRetryEx.h"
  38. #include "HttpDownloadCommand.h"
  39. #include "HttpInitiateConnectionCommand.h"
  40. #include "message.h"
  41. #include "Util.h"
  42. #include "prefs.h"
  43. #include "File.h"
  44. #include "FatalException.h"
  45. #include <sys/types.h>
  46. #include <unistd.h>
  47. HttpResponseCommand::HttpResponseCommand(int cuid,
  48. const RequestHandle req,
  49. DownloadEngine* e,
  50. const SocketHandle& s)
  51. :AbstractCommand(cuid, req, e, s) {
  52. http = new HttpConnection(cuid, socket, req, e->option);
  53. }
  54. HttpResponseCommand::~HttpResponseCommand() {
  55. delete http;
  56. }
  57. bool HttpResponseCommand::executeInternal(Segment& segment) {
  58. if(req->segment != segment) {
  59. logger->info(MSG_SEGMENT_CHANGED, cuid);
  60. return prepareForRetry(0);
  61. }
  62. HttpHeader headers;
  63. int status = http->receiveResponse(headers);
  64. if(status == 0) {
  65. // didn't receive header fully
  66. e->commands.push_back(this);
  67. return false;
  68. }
  69. // check HTTP status number
  70. checkResponse(status, segment);
  71. retrieveCookie(headers);
  72. // check whether the server supports persistent connections.
  73. if(Util::toLower(headers.getFirst("Connection")).find("close") != string::npos) {
  74. req->setKeepAlive(false);
  75. }
  76. // check whether Location header exists. If it does, update request object
  77. // with redirected URL.
  78. // then establish a connection to the new host and port
  79. if(headers.defined("Location")) {
  80. return handleRedirect(headers.getFirst("Location"), headers);
  81. }
  82. if(!e->segmentMan->downloadStarted) {
  83. string transferEncoding;
  84. if(headers.defined("Transfer-Encoding")) {
  85. return handleOtherEncoding(headers.getFirst("Transfer-Encoding"),
  86. headers);
  87. } else {
  88. return handleDefaultEncoding(headers);
  89. }
  90. } else {
  91. string filenameInHeader = determinFilename(headers);
  92. if(filenameInHeader != e->segmentMan->filename) {
  93. throw new DlAbortEx(EX_FILENAME_MISMATCH,
  94. filenameInHeader.c_str(),
  95. e->segmentMan->filename.c_str());
  96. }
  97. createHttpDownloadCommand();
  98. return true;
  99. }
  100. }
  101. void HttpResponseCommand::checkResponse(int status, const Segment& segment) {
  102. if(status == 401) {
  103. throw new DlAbortEx(EX_AUTH_FAILED);
  104. }
  105. if(!(300 <= status && status < 400 ||
  106. (segment.getPosition()+segment.writtenLength == 0 && (status == 200 || status == 206)) ||
  107. (segment.getPosition()+segment.writtenLength > 0 && status == 206))) {
  108. throw new DlRetryEx(EX_BAD_STATUS, status);
  109. }
  110. }
  111. bool HttpResponseCommand::handleRedirect(const string& url, const HttpHeader& headers) {
  112. req->redirectUrl(url);
  113. logger->info(MSG_REDIRECT, cuid, url.c_str());
  114. e->noWait = true;
  115. return prepareForRetry(0);
  116. }
  117. string HttpResponseCommand::determinFilename(const HttpHeader& headers) {
  118. string contentDisposition =
  119. Util::getContentDispositionFilename(headers.getFirst("Content-Disposition"));
  120. if(contentDisposition.empty()) {
  121. return Util::urldecode(req->getFile());
  122. } else {
  123. logger->info("CUID#%d - Content-Disposition Detected. Use %s as filename",
  124. cuid, contentDisposition.c_str());
  125. return Util::urldecode(contentDisposition);
  126. }
  127. }
  128. bool HttpResponseCommand::handleDefaultEncoding(const HttpHeader& headers) {
  129. // TODO quick and dirty way
  130. if(req->isTorrent) {
  131. long long int size = headers.getFirstAsLLInt("Content-Length");
  132. e->segmentMan->totalSize = size;
  133. if(size > 0) {
  134. e->segmentMan->initBitfield(e->option->getAsInt(PREF_SEGMENT_SIZE),
  135. e->segmentMan->totalSize);
  136. }
  137. // disable keep-alive
  138. req->setKeepAlive(false);
  139. e->segmentMan->isSplittable = false;
  140. e->segmentMan->downloadStarted = true;
  141. e->segmentMan->diskWriter->initAndOpenFile("/tmp/aria2"+Util::itos((int32_t)getpid()));
  142. createHttpDownloadCommand();
  143. return true;
  144. }
  145. long long int size = headers.getFirstAsLLInt("Content-Length");
  146. if(size == INT64_MAX || size < 0) {
  147. throw new DlAbortEx(EX_TOO_LARGE_FILE, size);
  148. }
  149. e->segmentMan->isSplittable = !(size == 0);
  150. e->segmentMan->filename = determinFilename(headers);
  151. // quick hack for method 'head'
  152. if(req->getMethod() == Request::METHOD_HEAD) {
  153. e->segmentMan->downloadStarted = true;
  154. e->segmentMan->totalSize = size;
  155. e->segmentMan->isSplittable = false; // TODO because we don't want segment file to be saved.
  156. return true;
  157. }
  158. bool segFileExists = e->segmentMan->segmentFileExists();
  159. e->segmentMan->downloadStarted = true;
  160. if(segFileExists) {
  161. e->segmentMan->load();
  162. e->segmentMan->diskWriter->openExistingFile(e->segmentMan->getFilePath());
  163. // send request again to the server with Range header
  164. return prepareForRetry(0);
  165. } else {
  166. e->segmentMan->totalSize = size;
  167. e->segmentMan->initBitfield(e->option->getAsInt(PREF_SEGMENT_SIZE),
  168. e->segmentMan->totalSize);
  169. e->segmentMan->diskWriter->initAndOpenFile(e->segmentMan->getFilePath(),
  170. size);
  171. return prepareForRetry(0);
  172. }
  173. }
  174. bool HttpResponseCommand::handleOtherEncoding(const string& transferEncoding, const HttpHeader& headers) {
  175. // quick hack for method 'head'
  176. if(req->getMethod() == Request::METHOD_HEAD) {
  177. e->segmentMan->downloadStarted = true;
  178. e->segmentMan->isSplittable = false;
  179. e->segmentMan->filename = determinFilename(headers);
  180. e->segmentMan->totalSize = 0;
  181. return true;
  182. }
  183. if(e->segmentMan->shouldCancelDownloadForSafety()) {
  184. throw new FatalException(EX_FILE_ALREADY_EXISTS,
  185. e->segmentMan->getFilePath().c_str(),
  186. e->segmentMan->getSegmentFilePath().c_str());
  187. }
  188. // we ignore content-length when transfer-encoding is set
  189. e->segmentMan->downloadStarted = true;
  190. e->segmentMan->isSplittable = false;
  191. e->segmentMan->filename = determinFilename(headers);
  192. e->segmentMan->totalSize = 0;
  193. // disable keep-alive
  194. req->setKeepAlive(false);
  195. Segment segment;
  196. e->segmentMan->getSegment(segment, cuid);
  197. e->segmentMan->diskWriter->initAndOpenFile(e->segmentMan->getFilePath());
  198. createHttpDownloadCommand(transferEncoding);
  199. return true;
  200. }
  201. void HttpResponseCommand::createHttpDownloadCommand(const string& transferEncoding) {
  202. HttpDownloadCommand* command = new HttpDownloadCommand(cuid, req, e, socket);
  203. command->setMaxDownloadSpeedLimit(e->option->getAsInt(PREF_MAX_DOWNLOAD_LIMIT));
  204. command->setStartupIdleTime(e->option->getAsInt(PREF_STARTUP_IDLE_TIME));
  205. command->setLowestDownloadSpeedLimit(e->option->getAsInt(PREF_LOWEST_SPEED_LIMIT));
  206. TransferEncoding* enc = NULL;
  207. if(transferEncoding.size() && (enc = command->getTransferEncoding(transferEncoding)) == NULL) {
  208. delete(command);
  209. throw new DlAbortEx(EX_TRANSFER_ENCODING_NOT_SUPPORTED, transferEncoding.c_str());
  210. } else {
  211. if(enc != NULL) {
  212. command->transferEncoding = transferEncoding;
  213. enc->init();
  214. }
  215. e->commands.push_back(command);
  216. }
  217. }
  218. void HttpResponseCommand::retrieveCookie(const HttpHeader& headers) {
  219. Strings v = headers.get("Set-Cookie");
  220. for(Strings::const_iterator itr = v.begin(); itr != v.end(); itr++) {
  221. Cookie c;
  222. req->cookieBox->parse(c, *itr);
  223. req->cookieBox->add(c);
  224. }
  225. }