aria2/src/HttpConnection.cc

191 lines
6.3 KiB
C++
Raw Normal View History

2006-02-17 13:35:04 +00:00
/* <!-- copyright */
/*
* aria2 - a simple utility for downloading files faster
*
* Copyright (C) 2006 Tatsuhiro Tsujikawa
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* copyright --> */
#include "HttpConnection.h"
#include "DlRetryEx.h"
#include "Util.h"
#include "Base64.h"
#include "message.h"
2006-02-21 14:00:58 +00:00
#include "prefs.h"
To add LogFactory which creates singleton logger: * src/LogFactory.h: New class. * src/LogFactory.cc: New class. * src/Command.h (logger): New variable. (Constructor): Use LogFactory. * src/AbstractCommand.cc: Use Command::logger * src/PeerConnection.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/SegmentSplitter.h : Made logger protected. * src/SegmentSplitter.cc (Constructor): Use LogFactory. * src/SegmentMan.cc (Constructor): Use LogFactory. * src/DownloadEngine.h : Made logger protected. * src/DownloadEngine.cc (Constructor): Use LogFactory. * src/PeerInteractionCommand.cc : Use Command::logger. * src/HttpResponseCommand.cc : Use Command::logger. * src/SegmentMan.h : Made logger private. * src/TorrentMan.h : Made logger private. * src/TorrentMan.cc : Use LogFactory. * src/FtpNegotiateCommand.cc : Use Command::logger. * src/HttpConnection.h (Constructor): Deleted the argument logger. * src/HttpConnection.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/FtpConnection.h (Constructor): Deleted the argument logger. * src/FtpConnection.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/DownloadCommand.cc : Use Command::logger. * src/PeerAbstractCommand.cc : Use Command::logger. * src/PeerListenCommand.cc : Use Command::logger. * src/PeerInitiateConnectionCommand.cc : Use Command::logger. * src/HttpInitiateConnectionCommand.cc : Use Command::logger. * src/FtpInitiateConnectionCommand.cc : Use Command::logger. * src/TrackerWatcherCommand.cc : Use Command::logger. * src/TrackerUpdateCommand.cc : Use Command::logger. * src/TrackerDownloadCommand.cc : Use Command::logger. * src/RequestSlotMan.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/SendMessageQueue.h (Constructor): Deleted the argument logger. * src/SendMessageQueue.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/main.cc (main): Use LogFactory. * src/DiskAdaptor.h (logger): New variable. * src/DiskAdaptor.cc (Constructor): Use LogFactory. * src/CopyDiskAdaptor.cc (fixFilename): Added a log message.
2006-04-17 16:17:20 +00:00
#include "LogFactory.h"
2006-02-17 13:35:04 +00:00
To add LogFactory which creates singleton logger: * src/LogFactory.h: New class. * src/LogFactory.cc: New class. * src/Command.h (logger): New variable. (Constructor): Use LogFactory. * src/AbstractCommand.cc: Use Command::logger * src/PeerConnection.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/SegmentSplitter.h : Made logger protected. * src/SegmentSplitter.cc (Constructor): Use LogFactory. * src/SegmentMan.cc (Constructor): Use LogFactory. * src/DownloadEngine.h : Made logger protected. * src/DownloadEngine.cc (Constructor): Use LogFactory. * src/PeerInteractionCommand.cc : Use Command::logger. * src/HttpResponseCommand.cc : Use Command::logger. * src/SegmentMan.h : Made logger private. * src/TorrentMan.h : Made logger private. * src/TorrentMan.cc : Use LogFactory. * src/FtpNegotiateCommand.cc : Use Command::logger. * src/HttpConnection.h (Constructor): Deleted the argument logger. * src/HttpConnection.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/FtpConnection.h (Constructor): Deleted the argument logger. * src/FtpConnection.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/DownloadCommand.cc : Use Command::logger. * src/PeerAbstractCommand.cc : Use Command::logger. * src/PeerListenCommand.cc : Use Command::logger. * src/PeerInitiateConnectionCommand.cc : Use Command::logger. * src/HttpInitiateConnectionCommand.cc : Use Command::logger. * src/FtpInitiateConnectionCommand.cc : Use Command::logger. * src/TrackerWatcherCommand.cc : Use Command::logger. * src/TrackerUpdateCommand.cc : Use Command::logger. * src/TrackerDownloadCommand.cc : Use Command::logger. * src/RequestSlotMan.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/SendMessageQueue.h (Constructor): Deleted the argument logger. * src/SendMessageQueue.cc (Constructor): Deleted the argument logger. Use LogFactory. * src/main.cc (main): Use LogFactory. * src/DiskAdaptor.h (logger): New variable. * src/DiskAdaptor.cc (Constructor): Use LogFactory. * src/CopyDiskAdaptor.cc (fixFilename): Added a log message.
2006-04-17 16:17:20 +00:00
HttpConnection::HttpConnection(int cuid, const Socket* socket, const Request* req, const Option* op):
cuid(cuid), socket(socket), req(req), option(op), headerBufLength(0) {
logger = LogFactory::getInstance();
}
2006-02-17 13:35:04 +00:00
2006-02-21 12:27:17 +00:00
void HttpConnection::sendRequest(const Segment& segment) const {
string request = createRequest(segment);
2006-02-21 15:01:05 +00:00
logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
2006-02-17 13:35:04 +00:00
socket->writeData(request.c_str(), request.size());
}
2006-02-21 12:27:17 +00:00
void HttpConnection::sendProxyRequest() const {
2006-02-21 14:00:58 +00:00
string request =
string("CONNECT ")+req->getHost()+":"+Util::llitos(req->getPort())+
2006-02-17 13:35:04 +00:00
string(" HTTP/1.1\r\n")+
"User-Agent: "+USER_AGENT+"\r\n"+
"Proxy-Connection: close\r\n"+
2006-02-17 13:35:04 +00:00
"Host: "+getHost(req->getHost(), req->getPort())+"\r\n";
if(useProxyAuth()) {
2006-02-22 15:40:04 +00:00
request += getProxyAuthString();
2006-02-17 13:35:04 +00:00
}
request += "\r\n";
2006-02-21 15:01:05 +00:00
logger->info(MSG_SENDING_REQUEST, cuid, request.c_str());
2006-02-17 13:35:04 +00:00
socket->writeData(request.c_str(), request.size());
}
2006-02-22 15:40:04 +00:00
string HttpConnection::getProxyAuthString() const {
return "Proxy-Authorization: Basic "+
Base64::encode(option->get(PREF_HTTP_PROXY_USER)+":"+
option->get(PREF_HTTP_PROXY_PASSWD))+"\r\n";
2006-02-22 15:40:04 +00:00
}
2006-02-21 12:27:17 +00:00
string HttpConnection::getHost(const string& host, int port) const {
return host+(port == 80 || port == 443 ? "" : ":"+Util::llitos(port));
2006-02-17 13:35:04 +00:00
}
2006-02-21 12:27:17 +00:00
string HttpConnection::createRequest(const Segment& segment) const {
string request = string("GET ")+
2006-02-22 15:40:04 +00:00
(req->getProtocol() == "ftp" || useProxy() && useProxyGet() ?
2006-02-21 12:27:17 +00:00
req->getCurrentUrl() :
((req->getDir() == "/" ? "/" : req->getDir()+"/")+req->getFile()))+
string(" HTTP/1.1\r\n")+
"User-Agent: "+USER_AGENT+"\r\n"+
2006-02-17 13:35:04 +00:00
"Connection: close\r\n"+
2006-02-21 12:27:17 +00:00
"Accept: */*\r\n"+ /* */
2006-02-17 13:35:04 +00:00
"Host: "+getHost(req->getHost(), req->getPort())+"\r\n"+
"Pragma: no-cache\r\n"+
"Cache-Control: no-cache\r\n";
if(segment.sp+segment.ds > 0) {
2006-02-21 14:00:58 +00:00
request += "Range: bytes="+
Util::llitos(segment.sp+segment.ds)+"-"+Util::llitos(segment.ep)+"\r\n";
2006-02-17 13:35:04 +00:00
}
2006-02-22 15:40:04 +00:00
if(useProxy() && useProxyAuth() && useProxyGet()) {
request += "Proxy-Connection: close\r\n";
2006-02-22 15:40:04 +00:00
request += getProxyAuthString();
}
To add TrackerUpdateCommand with which replaces CompactTrackerResponseProcessor: * src/TrackerWatcherCommand.h (req): Removed. * src/TrackerWatcherCommand.cc (execute): Send a request to tracker if the number of peer connections are less than 30. * src/ByteArrayDiskWriter.h (readData): Implemented. * src/SegmentMan.h (diskWriter): New function. * src/SegmentMan.cc (init): Added a call to diskWriter->closeFile() * src/main.cc : Removed #include "CompactTrackerResponseProcessor.h" (main): Use TrackerUpdateCommand. * src/TorrentMan.h (CompactTrackerResponseProcessor): Removed. (req): New variable. (setTrackerResponseProcessor): Removed. (getTrackerResponseProcessor): Removed. (processTrackerResponse): Removed. * src/DownloadEngine.h (diskWriter): Removed. * src/TorrentDownloadEngine.cc (afterEachIteration): Removed a call to torrentMan->processTrackerResponse(). To add Util::expandBuffer: * src/ByteArrayDiskWriter.h (expandBuffer): Removed. * src/ByteArrayDiskWriter.cc (writeData): Use Util::expandBuffer(). * src/Util.h (expandBuffer): New function. To fix the bug that causes segmentation fault when "-l ." is specified in command-line option: * src/SimpleLogger.h (SimpleLogger): Removed "filename" argument. (openFile): New function. (closeFile): New function. * src/SimpleLogger.cc (SimpleLogger): Removed fopen. (~SimpleLogger): Call closeFile(); * src/LogFactory.cc (getInstance): Added a call to slogger->openFile(). * src/main.cc (main): Added a check to see logger is configured properly. To enable HTTP authentication without specifying "--http-auth-scheme" * src/prefs.h (PREF_HTTP_AUTH_ENABLED): New definition. * src/HttpConnection.cc (createRequest): Send Authorization header if PREF_HTTP_AUTH_ENABLED == V_TRUE. * src/main.cc (main): Preset PREF_HTTP_AUTH_SCHEME to V_TRUE If "--http-user" is specified, set PREF_HTTP_AUTH_ENABLED to V_TRUE * src/Peer.cc (shouldChoke): Updated algorithm. * src/message.h (EX_AUTH_FAILED): New definition. (EX_FILE_OPEN): New definition. * src/HttpResponseCommand.cc (checkResponse): Throw DlAbortEx if status == 401. (handleDefaultEncoding): Added a call to diskWriter->initAndOpenFile() if req->isTorrent == true. * src/main.cc (handler): Removed the check to see e->diskWriter != NULL (torrentHandler): Removed the check to see diskAdaptor != NULL. * src/AbstractDiskWriter.cc (openExistingFile): Updated messsage. (createFile): Updated message.
2006-04-19 17:23:58 +00:00
if(option->get(PREF_HTTP_AUTH_ENABLED) == V_TRUE) {
if(option->get(PREF_HTTP_AUTH_SCHEME) == V_BASIC) {
request += "Authorization: Basic "+
Base64::encode(option->get(PREF_HTTP_USER)+":"+
option->get(PREF_HTTP_PASSWD))+"\r\n";
}
2006-02-17 13:35:04 +00:00
}
if(req->getPreviousUrl().size()) {
request += "Referer: "+req->getPreviousUrl()+"\r\n";
}
2006-02-17 13:35:04 +00:00
string cookiesValue;
Cookies cookies = req->cookieBox->criteriaFind(req->getHost(), req->getDir(), req->getProtocol() == "https" ? true : false);
for(Cookies::const_iterator itr = cookies.begin(); itr != cookies.end(); itr++) {
2006-02-17 13:35:04 +00:00
cookiesValue += (*itr).toString()+";";
}
if(cookiesValue.size()) {
request += string("Cookie: ")+cookiesValue+"\r\n";
}
request += "\r\n";
return request;
}
2006-03-21 14:12:51 +00:00
int HttpConnection::findEndOfHeader(const char* buf, const char* substr, int bufLength) const {
const char* p = buf;
while(bufLength > p-buf && bufLength-(p-buf) >= (int)strlen(substr)) {
if(memcmp(p, substr, strlen(substr)) == 0) {
return p-buf;
2006-02-22 15:40:04 +00:00
}
2006-03-21 14:12:51 +00:00
p++;
}
return -1;
}
int HttpConnection::receiveResponse(HttpHeader& headers) {
//char buf[512];
string header;
int delimiterSwith = 0;
char* delimiters[] = { "\r\n", "\n" };
int size = HEADERBUF_SIZE-headerBufLength;
if(size < 0) {
// TODO too large header
throw new DlRetryEx("too large header > 4096");
}
socket->peekData(headerBuf+headerBufLength, size);
if(size == 0) {
throw new DlRetryEx(EX_INVALID_RESPONSE);
}
//buf[size] = '\0';
int hlenTemp = headerBufLength+size;
//header += buf;
//string::size_type p;
int eohIndex;
if((eohIndex = findEndOfHeader(headerBuf, "\r\n\r\n", hlenTemp)) == -1 &&
(eohIndex = findEndOfHeader(headerBuf, "\n\n", hlenTemp)) == -1) {
socket->readData(headerBuf+headerBufLength, size);
} else {
if(eohIndex[headerBuf] == '\n') {
// for crapping non-standard HTTP server
delimiterSwith = 1;
2006-02-21 12:27:17 +00:00
} else {
2006-03-21 14:12:51 +00:00
delimiterSwith = 0;
2006-02-17 13:35:04 +00:00
}
2006-03-21 14:12:51 +00:00
headerBuf[eohIndex+strlen(delimiters[delimiterSwith])*2] = '\0';
header = headerBuf;
size = eohIndex+strlen(delimiters[delimiterSwith])*2-headerBufLength;
socket->readData(headerBuf+headerBufLength, size);
2006-02-17 13:35:04 +00:00
}
2006-03-21 14:12:51 +00:00
if(!Util::endsWith(header, "\r\n\r\n") && !Util::endsWith(header, "\n\n")) {
2006-02-21 12:27:17 +00:00
return 0;
}
// OK, we got all headers.
2006-02-17 13:35:04 +00:00
logger->info(MSG_RECEIVE_RESPONSE, cuid, header.c_str());
string::size_type p, np;
2006-02-17 13:35:04 +00:00
p = np = 0;
2006-03-21 14:12:51 +00:00
np = header.find(delimiters[delimiterSwith], p);
2006-02-17 13:35:04 +00:00
if(np == string::npos) {
throw new DlRetryEx(EX_NO_STATUS_HEADER);
}
// check HTTP status value
string status = header.substr(9, 3);
p = np+2;
// retreive status name-value pairs, then push these into map
2006-03-21 14:12:51 +00:00
while((np = header.find(delimiters[delimiterSwith], p)) != string::npos && np != p) {
2006-02-17 13:35:04 +00:00
string line = header.substr(p, np-p);
p = np+2;
pair<string, string> hp;
Util::split(hp, line, ':');
2006-02-21 12:27:17 +00:00
headers.put(hp.first, hp.second);
2006-02-17 13:35:04 +00:00
}
return (int)strtol(status.c_str(), NULL, 10);
}
2006-02-21 12:27:17 +00:00
bool HttpConnection::useProxy() const {
2006-02-21 14:00:58 +00:00
return option->get(PREF_HTTP_PROXY_ENABLED) == V_TRUE;
2006-02-17 13:35:04 +00:00
}
2006-02-21 12:27:17 +00:00
bool HttpConnection::useProxyAuth() const {
2006-02-21 14:00:58 +00:00
return option->get(PREF_HTTP_PROXY_AUTH_ENABLED) == V_TRUE;
2006-02-17 13:35:04 +00:00
}
2006-02-22 15:40:04 +00:00
bool HttpConnection::useProxyGet() const {
return option->get(PREF_HTTP_PROXY_METHOD) == V_GET;
}