EOL cleanups.

This commit is contained in:
James Turner
2015-11-22 22:36:54 +00:00
parent 5676f96fbf
commit 5c9ca9cbe2
6 changed files with 130 additions and 132 deletions
-2
View File
@@ -419,5 +419,3 @@ CONFIGURE_FILE(
IMMEDIATE @ONLY) IMMEDIATE @ONLY)
ADD_CUSTOM_TARGET(uninstall ADD_CUSTOM_TARGET(uninstall
"${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake") "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake")
+3 -3
View File
@@ -56,7 +56,7 @@ if(SIMGEAR_SHARED)
set_property(TARGET SimGearCore PROPERTY SOVERSION ${SIMGEAR_SOVERSION}) set_property(TARGET SimGearCore PROPERTY SOVERSION ${SIMGEAR_SOVERSION})
install(TARGETS SimGearCore EXPORT SimGearCoreConfig LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(TARGETS SimGearCore EXPORT SimGearCoreConfig LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
install(EXPORT SimGearCoreConfig DESTINATION share/SimGearCore) install(EXPORT SimGearCoreConfig DESTINATION share/SimGearCore)
if(NOT SIMGEAR_HEADLESS) if(NOT SIMGEAR_HEADLESS)
add_library(SimGearScene SHARED ${sceneSources}) add_library(SimGearScene SHARED ${sceneSources})
set_property(TARGET SimGearScene PROPERTY LINKER_LANGUAGE CXX) set_property(TARGET SimGearScene PROPERTY LINKER_LANGUAGE CXX)
@@ -67,7 +67,7 @@ if(SIMGEAR_SHARED)
install(TARGETS SimGearScene LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ) install(TARGETS SimGearScene LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} )
# install(EXPORT SimGearSceneConfig DESTINATION share/SimGearScene) # install(EXPORT SimGearSceneConfig DESTINATION share/SimGearScene)
endif() endif()
else() else()
message(STATUS "Library building mode: STATIC LIBRARIES") message(STATUS "Library building mode: STATIC LIBRARIES")
@@ -91,7 +91,7 @@ else()
add_library(SimGearCore STATIC ${coreSources} ${localExpatSources}) add_library(SimGearCore STATIC ${coreSources} ${localExpatSources})
install(TARGETS SimGearCore ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}) install(TARGETS SimGearCore ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
if(NOT SIMGEAR_HEADLESS) if(NOT SIMGEAR_HEADLESS)
get_property(FG_GROUPS_SCENE_SOURCES_C GLOBAL PROPERTY FG_GROUPS_SCENE_SOURCES_C) get_property(FG_GROUPS_SCENE_SOURCES_C GLOBAL PROPERTY FG_GROUPS_SCENE_SOURCES_C)
string(REPLACE "@" ";" groups ${FG_GROUPS_SCENE_SOURCES_C} ) string(REPLACE "@" ";" groups ${FG_GROUPS_SCENE_SOURCES_C} )
+99 -99
View File
@@ -95,7 +95,7 @@ public:
port(DEFAULT_HTTP_PORT) port(DEFAULT_HTTP_PORT)
{ {
} }
virtual ~Connection() virtual ~Connection()
{ {
} }
@@ -112,13 +112,13 @@ public:
state = STATE_GETTING_BODY; state = STATE_GETTING_BODY;
responseComplete(); responseComplete();
} }
void setServer(const std::string& h, short p) void setServer(const std::string& h, short p)
{ {
host = h; host = h;
port = p; port = p;
} }
// socket-level errors // socket-level errors
virtual void handleError(int error) virtual void handleError(int error)
{ {
@@ -132,42 +132,42 @@ public:
BOOST_FOREACH(Request_ptr req, sentRequests) { BOOST_FOREACH(Request_ptr req, sentRequests) {
req->setFailure(error, errStr); req->setFailure(error, errStr);
} }
BOOST_FOREACH(Request_ptr req, queuedRequests) { BOOST_FOREACH(Request_ptr req, queuedRequests) {
req->setFailure(error, errStr); req->setFailure(error, errStr);
} }
sentRequests.clear(); sentRequests.clear();
queuedRequests.clear(); queuedRequests.clear();
} }
NetChat::handleError(error); NetChat::handleError(error);
if (activeRequest) { if (activeRequest) {
activeRequest->setFailure(error, errStr); activeRequest->setFailure(error, errStr);
activeRequest = NULL; activeRequest = NULL;
_contentDecoder.reset(); _contentDecoder.reset();
} }
state = STATE_SOCKET_ERROR; state = STATE_SOCKET_ERROR;
} }
virtual void handleClose() virtual void handleClose()
{ {
NetChat::handleClose(); NetChat::handleClose();
// closing of the connection from the server side when getting the body, // closing of the connection from the server side when getting the body,
bool canCloseState = (state == STATE_GETTING_BODY); bool canCloseState = (state == STATE_GETTING_BODY);
if (canCloseState && activeRequest) { if (canCloseState && activeRequest) {
// force state here, so responseComplete can avoid closing the // force state here, so responseComplete can avoid closing the
// socket again // socket again
state = STATE_CLOSED; state = STATE_CLOSED;
responseComplete(); responseComplete();
} else { } else {
if (activeRequest) { if (activeRequest) {
activeRequest->setFailure(500, "server closed connection"); activeRequest->setFailure(500, "server closed connection");
// remove the failed request from sentRequests, so it does // remove the failed request from sentRequests, so it does
// not get restored // not get restored
RequestList::iterator it = std::find(sentRequests.begin(), RequestList::iterator it = std::find(sentRequests.begin(),
sentRequests.end(), activeRequest); sentRequests.end(), activeRequest);
if (it != sentRequests.end()) { if (it != sentRequests.end()) {
sentRequests.erase(it); sentRequests.erase(it);
@@ -175,21 +175,21 @@ public:
activeRequest = NULL; activeRequest = NULL;
_contentDecoder.reset(); _contentDecoder.reset();
} }
state = STATE_CLOSED; state = STATE_CLOSED;
} }
if (sentRequests.empty()) { if (sentRequests.empty()) {
return; return;
} }
// restore sent requests to the queue, so they will be re-sent // restore sent requests to the queue, so they will be re-sent
// when the connection opens again // when the connection opens again
queuedRequests.insert(queuedRequests.begin(), queuedRequests.insert(queuedRequests.begin(),
sentRequests.begin(), sentRequests.end()); sentRequests.begin(), sentRequests.end());
sentRequests.clear(); sentRequests.clear();
} }
void handleTimeout() void handleTimeout()
{ {
NetChat::handleError(ETIMEDOUT); NetChat::handleError(ETIMEDOUT);
@@ -199,21 +199,21 @@ public:
activeRequest = NULL; activeRequest = NULL;
_contentDecoder.reset(); _contentDecoder.reset();
} }
state = STATE_SOCKET_ERROR; state = STATE_SOCKET_ERROR;
} }
void queueRequest(const Request_ptr& r) void queueRequest(const Request_ptr& r)
{ {
queuedRequests.push_back(r); queuedRequests.push_back(r);
tryStartNextRequest(); tryStartNextRequest();
} }
void beginResponse() void beginResponse()
{ {
assert(!sentRequests.empty()); assert(!sentRequests.empty());
assert(state == STATE_WAITING_FOR_RESPONSE); assert(state == STATE_WAITING_FOR_RESPONSE);
activeRequest = sentRequests.front(); activeRequest = sentRequests.front();
try { try {
activeRequest->responseStart(buffer); activeRequest->responseStart(buffer);
@@ -221,7 +221,7 @@ public:
handleError(EIO); handleError(EIO);
return; return;
} }
state = STATE_GETTING_HEADERS; state = STATE_GETTING_HEADERS;
buffer.clear(); buffer.clear();
if (activeRequest->responseCode() == 204) { if (activeRequest->responseCode() == 204) {
@@ -236,7 +236,7 @@ public:
chunkedTransfer = false; chunkedTransfer = false;
_contentDecoder.reset(); _contentDecoder.reset();
} }
void tryStartNextRequest() void tryStartNextRequest()
{ {
while( !queuedRequests.empty() while( !queuedRequests.empty()
@@ -247,21 +247,21 @@ public:
idleTime.stamp(); idleTime.stamp();
return; return;
} }
if (sentRequests.size() > MAX_INFLIGHT_REQUESTS) { if (sentRequests.size() > MAX_INFLIGHT_REQUESTS) {
return; return;
} }
if (state == STATE_CLOSED) { if (state == STATE_CLOSED) {
if (!connectToHost()) { if (!connectToHost()) {
return; return;
} }
setTerminator("\r\n"); setTerminator("\r\n");
state = STATE_IDLE; state = STATE_IDLE;
} }
Request_ptr r = queuedRequests.front(); Request_ptr r = queuedRequests.front();
r->requestStart(); r->requestStart();
@@ -270,7 +270,7 @@ public:
assert(!path.empty()); assert(!path.empty());
std::string query = r->query(); std::string query = r->query();
std::string bodyData; std::string bodyData;
if (!client->proxyHost().empty()) { if (!client->proxyHost().empty()) {
path = r->scheme() + "://" + r->host() + r->path(); path = r->scheme() + "://" + r->host() + r->path();
} }
@@ -288,7 +288,7 @@ public:
headerData << "Content-Type:" << r->bodyType() << "\r\n"; headerData << "Content-Type:" << r->bodyType() << "\r\n";
} }
} }
headerData << "Host: " << r->hostAndPort() << "\r\n"; headerData << "Host: " << r->hostAndPort() << "\r\n";
headerData << "User-Agent:" << client->userAgent() << "\r\n"; headerData << "User-Agent:" << client->userAgent() << "\r\n";
headerData << "Accept-Encoding: deflate, gzip\r\n"; headerData << "Accept-Encoding: deflate, gzip\r\n";
@@ -304,7 +304,7 @@ public:
if (!bodyData.empty()) { if (!bodyData.empty()) {
headerData << bodyData; headerData << bodyData;
} }
bool ok = push(headerData.str().c_str()); bool ok = push(headerData.str().c_str());
if (!ok) { if (!ok) {
SG_LOG(SG_IO, SG_WARN, "HTTPClient: over-stuffed the socket"); SG_LOG(SG_IO, SG_WARN, "HTTPClient: over-stuffed the socket");
@@ -338,7 +338,7 @@ public:
break; break;
} }
} }
// SG_LOG(SG_IO, SG_INFO, "did start request:" << r->url() << // SG_LOG(SG_IO, SG_INFO, "did start request:" << r->url() <<
// "\n\t @ " << reinterpret_cast<void*>(r.ptr()) << // "\n\t @ " << reinterpret_cast<void*>(r.ptr()) <<
// "\n\t on connection " << this); // "\n\t on connection " << this);
@@ -346,11 +346,11 @@ public:
queuedRequests.pop_front(); queuedRequests.pop_front();
sentRequests.push_back(r); sentRequests.push_back(r);
state = STATE_WAITING_FOR_RESPONSE; state = STATE_WAITING_FOR_RESPONSE;
// pipelining, let's maybe send the next request right away // pipelining, let's maybe send the next request right away
tryStartNextRequest(); tryStartNextRequest();
} }
virtual void collectIncomingData(const char* s, int n) virtual void collectIncomingData(const char* s, int n)
{ {
idleTime.stamp(); idleTime.stamp();
@@ -370,69 +370,69 @@ public:
case STATE_WAITING_FOR_RESPONSE: case STATE_WAITING_FOR_RESPONSE:
beginResponse(); beginResponse();
break; break;
case STATE_GETTING_HEADERS: case STATE_GETTING_HEADERS:
processHeader(); processHeader();
buffer.clear(); buffer.clear();
break; break;
case STATE_GETTING_BODY: case STATE_GETTING_BODY:
responseComplete(); responseComplete();
break; break;
case STATE_GETTING_CHUNKED: case STATE_GETTING_CHUNKED:
processChunkHeader(); processChunkHeader();
break; break;
case STATE_GETTING_CHUNKED_BYTES: case STATE_GETTING_CHUNKED_BYTES:
setTerminator("\r\n"); setTerminator("\r\n");
state = STATE_GETTING_CHUNKED; state = STATE_GETTING_CHUNKED;
buffer.clear(); buffer.clear();
break; break;
case STATE_GETTING_TRAILER: case STATE_GETTING_TRAILER:
processTrailer(); processTrailer();
buffer.clear(); buffer.clear();
break; break;
case STATE_IDLE: case STATE_IDLE:
SG_LOG(SG_IO, SG_WARN, "HTTP got data in IDLE state, bad server?"); SG_LOG(SG_IO, SG_WARN, "HTTP got data in IDLE state, bad server?");
default: default:
break; break;
} }
} }
bool hasIdleTimeout() const bool hasIdleTimeout() const
{ {
if (state != STATE_IDLE) { if (state != STATE_IDLE) {
return false; return false;
} }
assert(sentRequests.empty()); assert(sentRequests.empty());
return idleTime.elapsedMSec() > 1000 * 10; // ten seconds return idleTime.elapsedMSec() > 1000 * 10; // ten seconds
} }
bool hasErrorTimeout() const bool hasErrorTimeout() const
{ {
if (state == STATE_IDLE) { if (state == STATE_IDLE) {
return false; return false;
} }
return idleTime.elapsedMSec() > (1000 * 30); // 30 seconds return idleTime.elapsedMSec() > (1000 * 30); // 30 seconds
} }
bool hasError() const bool hasError() const
{ {
return (state == STATE_SOCKET_ERROR); return (state == STATE_SOCKET_ERROR);
} }
bool shouldStartNext() const bool shouldStartNext() const
{ {
return !queuedRequests.empty() && (sentRequests.size() < MAX_INFLIGHT_REQUESTS); return !queuedRequests.empty() && (sentRequests.size() < MAX_INFLIGHT_REQUESTS);
} }
bool isActive() const bool isActive() const
{ {
return !queuedRequests.empty() || !sentRequests.empty(); return !queuedRequests.empty() || !sentRequests.empty();
@@ -441,20 +441,20 @@ private:
bool connectToHost() bool connectToHost()
{ {
SG_LOG(SG_IO, SG_DEBUG, "HTTP connecting to " << host << ":" << port); SG_LOG(SG_IO, SG_DEBUG, "HTTP connecting to " << host << ":" << port);
if (!open()) { if (!open()) {
SG_LOG(SG_ALL, SG_WARN, "HTTP::Connection: connectToHost: open() failed"); SG_LOG(SG_ALL, SG_WARN, "HTTP::Connection: connectToHost: open() failed");
return false; return false;
} }
if (connect(host.c_str(), port) != 0) { if (connect(host.c_str(), port) != 0) {
return false; return false;
} }
return true; return true;
} }
void processHeader() void processHeader()
{ {
std::string h = strutils::simplify(buffer); std::string h = strutils::simplify(buffer);
@@ -462,18 +462,18 @@ private:
headersComplete(); headersComplete();
return; return;
} }
int colonPos = buffer.find(':'); int colonPos = buffer.find(':');
if (colonPos < 0) { if (colonPos < 0) {
SG_LOG(SG_IO, SG_WARN, "malformed HTTP response header:" << h); SG_LOG(SG_IO, SG_WARN, "malformed HTTP response header:" << h);
return; return;
} }
std::string key = strutils::simplify(buffer.substr(0, colonPos)); std::string key = strutils::simplify(buffer.substr(0, colonPos));
std::string lkey = boost::to_lower_copy(key); std::string lkey = boost::to_lower_copy(key);
std::string value = strutils::strip(buffer.substr(colonPos + 1)); std::string value = strutils::strip(buffer.substr(colonPos + 1));
// only consider these if getting headers (as opposed to trailers // only consider these if getting headers (as opposed to trailers
// of a chunked transfer) // of a chunked transfer)
if (state == STATE_GETTING_HEADERS) { if (state == STATE_GETTING_HEADERS) {
if (lkey == "content-length") { if (lkey == "content-length") {
@@ -491,10 +491,10 @@ private:
_contentDecoder.setEncoding(value); _contentDecoder.setEncoding(value);
} }
} }
activeRequest->responseHeader(lkey, value); activeRequest->responseHeader(lkey, value);
} }
void processTransferEncoding(const std::string& te) void processTransferEncoding(const std::string& te)
{ {
if (te == "chunked") { if (te == "chunked") {
@@ -504,14 +504,14 @@ private:
// failure // failure
} }
} }
void processChunkHeader() void processChunkHeader()
{ {
if (buffer.empty()) { if (buffer.empty()) {
// blank line after chunk data // blank line after chunk data
return; return;
} }
int chunkSize = 0; int chunkSize = 0;
int semiPos = buffer.find(';'); int semiPos = buffer.find(';');
if (semiPos >= 0) { if (semiPos >= 0) {
@@ -520,34 +520,34 @@ private:
} else { } else {
chunkSize = strutils::to_int(buffer, 16); chunkSize = strutils::to_int(buffer, 16);
} }
buffer.clear(); buffer.clear();
if (chunkSize == 0) { // trailer start if (chunkSize == 0) { // trailer start
state = STATE_GETTING_TRAILER; state = STATE_GETTING_TRAILER;
return; return;
} }
state = STATE_GETTING_CHUNKED_BYTES; state = STATE_GETTING_CHUNKED_BYTES;
setByteCount(chunkSize); setByteCount(chunkSize);
} }
void processTrailer() void processTrailer()
{ {
if (buffer.empty()) { if (buffer.empty()) {
// end of trailers // end of trailers
responseComplete(); responseComplete();
return; return;
} }
// process as a normal header // process as a normal header
processHeader(); processHeader();
} }
void headersComplete() void headersComplete()
{ {
activeRequest->responseHeadersComplete(); activeRequest->responseHeadersComplete();
_contentDecoder.initWithRequest(activeRequest); _contentDecoder.initWithRequest(activeRequest);
if (chunkedTransfer) { if (chunkedTransfer) {
state = STATE_GETTING_CHUNKED; state = STATE_GETTING_CHUNKED;
} else if (noMessageBody || (bodyTransferSize == 0)) { } else if (noMessageBody || (bodyTransferSize == 0)) {
@@ -560,41 +560,41 @@ private:
state = STATE_GETTING_BODY; state = STATE_GETTING_BODY;
} }
} }
void responseComplete() void responseComplete()
{ {
Request_ptr completedRequest = activeRequest; Request_ptr completedRequest = activeRequest;
_contentDecoder.finish(); _contentDecoder.finish();
assert(sentRequests.front() == activeRequest); assert(sentRequests.front() == activeRequest);
sentRequests.pop_front(); sentRequests.pop_front();
bool doClose = activeRequest->closeAfterComplete(); bool doClose = activeRequest->closeAfterComplete();
activeRequest = NULL; activeRequest = NULL;
if ((state == STATE_GETTING_BODY) || (state == STATE_GETTING_TRAILER)) { if ((state == STATE_GETTING_BODY) || (state == STATE_GETTING_TRAILER)) {
if (doClose) { if (doClose) {
// this will bring us into handleClose() above, which updates // this will bring us into handleClose() above, which updates
// state to STATE_CLOSED // state to STATE_CLOSED
close(); close();
// if we have additional requests waiting, try to start them now // if we have additional requests waiting, try to start them now
tryStartNextRequest(); tryStartNextRequest();
} }
} }
if (state != STATE_CLOSED) { if (state != STATE_CLOSED) {
state = sentRequests.empty() ? STATE_IDLE : STATE_WAITING_FOR_RESPONSE; state = sentRequests.empty() ? STATE_IDLE : STATE_WAITING_FOR_RESPONSE;
} }
// notify request after we change state, so this connection is idle // notify request after we change state, so this connection is idle
// if completion triggers other requests (which is likely) // if completion triggers other requests (which is likely)
// SG_LOG(SG_IO, SG_INFO, "*** responseComplete:" << activeRequest->url()); // SG_LOG(SG_IO, SG_INFO, "*** responseComplete:" << activeRequest->url());
completedRequest->responseComplete(); completedRequest->responseComplete();
client->requestFinished(this); client->requestFinished(this);
setTerminator("\r\n"); setTerminator("\r\n");
} }
enum ConnectionState { enum ConnectionState {
STATE_IDLE = 0, STATE_IDLE = 0,
STATE_WAITING_FOR_RESPONSE, STATE_WAITING_FOR_RESPONSE,
@@ -606,7 +606,7 @@ private:
STATE_SOCKET_ERROR, STATE_SOCKET_ERROR,
STATE_CLOSED ///< connection should be closed now STATE_CLOSED ///< connection should be closed now
}; };
Client* client; Client* client;
Request_ptr activeRequest; Request_ptr activeRequest;
ConnectionState state; ConnectionState state;
@@ -617,10 +617,10 @@ private:
SGTimeStamp idleTime; SGTimeStamp idleTime;
bool chunkedTransfer; bool chunkedTransfer;
bool noMessageBody; bool noMessageBody;
RequestList queuedRequests; RequestList queuedRequests;
RequestList sentRequests; RequestList sentRequests;
ContentDecoder _contentDecoder; ContentDecoder _contentDecoder;
}; };
@@ -657,12 +657,12 @@ void Client::update(int waitTimeout)
} else { } else {
d->poller.poll(waitTimeout); d->poller.poll(waitTimeout);
} }
bool waitingRequests = !d->pendingRequests.empty(); bool waitingRequests = !d->pendingRequests.empty();
ConnectionDict::iterator it = d->connections.begin(); ConnectionDict::iterator it = d->connections.begin();
for (; it != d->connections.end(); ) { for (; it != d->connections.end(); ) {
Connection* con = it->second; Connection* con = it->second;
if (con->hasIdleTimeout() || if (con->hasIdleTimeout() ||
con->hasError() || con->hasError() ||
con->hasErrorTimeout() || con->hasErrorTimeout() ||
(!con->isActive() && waitingRequests)) (!con->isActive() && waitingRequests))
@@ -671,7 +671,7 @@ void Client::update(int waitTimeout)
// tell the connection we're timing it out // tell the connection we're timing it out
con->handleTimeout(); con->handleTimeout();
} }
// connection has been idle for a while, clean it up // connection has been idle for a while, clean it up
// (or if we have requests waiting for a different host, // (or if we have requests waiting for a different host,
// or an error condition // or an error condition
@@ -685,11 +685,11 @@ void Client::update(int waitTimeout)
++it; ++it;
} }
} // of connection iteration } // of connection iteration
if (waitingRequests && (d->connections.size() < d->maxConnections)) { if (waitingRequests && (d->connections.size() < d->maxConnections)) {
RequestList waiting(d->pendingRequests); RequestList waiting(d->pendingRequests);
d->pendingRequests.clear(); d->pendingRequests.clear();
// re-submit all waiting requests in order; this takes care of // re-submit all waiting requests in order; this takes care of
// finding multiple pending items targetted to the same (new) // finding multiple pending items targetted to the same (new)
// connection // connection
@@ -728,17 +728,17 @@ void Client::makeRequest(const Request_ptr& r)
bool havePending = !d->pendingRequests.empty(); bool havePending = !d->pendingRequests.empty();
bool atConnectionsLimit = d->connections.size() >= d->maxConnections; bool atConnectionsLimit = d->connections.size() >= d->maxConnections;
ConnectionDict::iterator consEnd = d->connections.end(); ConnectionDict::iterator consEnd = d->connections.end();
// assign request to an existing Connection. // assign request to an existing Connection.
// various options exist here, examined in order // various options exist here, examined in order
ConnectionDict::iterator it = d->connections.find(connectionId); ConnectionDict::iterator it = d->connections.find(connectionId);
if (atConnectionsLimit && (it == consEnd)) { if (atConnectionsLimit && (it == consEnd)) {
// maximum number of connections active, queue this request // maximum number of connections active, queue this request
// when a connection goes inactive, we'll start this one // when a connection goes inactive, we'll start this one
d->pendingRequests.push_back(r); d->pendingRequests.push_back(r);
return; return;
} }
// scan for an idle Connection to the same host (likely if we're // scan for an idle Connection to the same host (likely if we're
// retrieving multiple resources from the same host in quick succession) // retrieving multiple resources from the same host in quick succession)
// if we have pending requests (waiting for a free Connection), then // if we have pending requests (waiting for a free Connection), then
@@ -753,7 +753,7 @@ void Client::makeRequest(const Request_ptr& r)
break; break;
} }
} }
if (!con && atConnectionsLimit) { if (!con && atConnectionsLimit) {
// all current connections are busy (active), and we don't // all current connections are busy (active), and we don't
// have free connections to allocate, so let's assign to // have free connections to allocate, so let's assign to
@@ -763,16 +763,16 @@ void Client::makeRequest(const Request_ptr& r)
for (it = d->connections.find(connectionId); index > 0; --index) { ; } for (it = d->connections.find(connectionId); index > 0; --index) { ; }
con = it->second; con = it->second;
} }
// allocate a new connection object // allocate a new connection object
if (!con) { if (!con) {
con = new Connection(this); con = new Connection(this);
con->setServer(host, port); con->setServer(host, port);
d->poller.addChannel(con); d->poller.addChannel(con);
d->connections.insert(d->connections.end(), d->connections.insert(d->connections.end(),
ConnectionDict::value_type(connectionId, con)); ConnectionDict::value_type(connectionId, con));
} }
con->queueRequest(r); con->queueRequest(r);
} }
@@ -795,7 +795,7 @@ MemoryRequestRef Client::load(const std::string& url)
void Client::requestFinished(Connection* con) void Client::requestFinished(Connection* con)
{ {
} }
void Client::setUserAgent(const std::string& ua) void Client::setUserAgent(const std::string& ua)
@@ -807,12 +807,12 @@ const std::string& Client::userAgent() const
{ {
return d->userAgent; return d->userAgent;
} }
const std::string& Client::proxyHost() const const std::string& Client::proxyHost() const
{ {
return d->proxy; return d->proxy;
} }
const std::string& Client::proxyAuth() const const std::string& Client::proxyAuth() const
{ {
return d->proxyAuth; return d->proxyAuth;
@@ -833,7 +833,7 @@ bool Client::hasActiveRequests() const
for (; it != d->connections.end(); ++it) { for (; it != d->connections.end(); ++it) {
if (it->second->isActive()) return true; if (it->second->isActive()) return true;
} }
return false; return false;
} }
@@ -842,7 +842,7 @@ void Client::receivedBytes(unsigned int count)
d->bytesTransferred += count; d->bytesTransferred += count;
d->totalBytesDownloaded += count; d->totalBytesDownloaded += count;
} }
unsigned int Client::transferRateBytesPerSec() const unsigned int Client::transferRateBytesPerSec() const
{ {
unsigned int e = d->timeTransferSample.elapsedMSec(); unsigned int e = d->timeTransferSample.elapsedMSec();
@@ -853,16 +853,16 @@ unsigned int Client::transferRateBytesPerSec() const
d->lastTransferRate = 0; d->lastTransferRate = 0;
return 0; return 0;
} }
if (e < 100) { // avoid really narrow windows if (e < 100) { // avoid really narrow windows
return d->lastTransferRate; return d->lastTransferRate;
} }
unsigned int ratio = (d->bytesTransferred * 1000) / e; unsigned int ratio = (d->bytesTransferred * 1000) / e;
// run a low-pass filter // run a low-pass filter
unsigned int smoothed = ((400 - e) * d->lastTransferRate) + (e * ratio); unsigned int smoothed = ((400 - e) * d->lastTransferRate) + (e * ratio);
smoothed /= 400; smoothed /= 400;
d->timeTransferSample.stamp(); d->timeTransferSample.stamp();
d->bytesTransferred = 0; d->bytesTransferred = 0;
d->lastTransferRate = smoothed; d->lastTransferRate = smoothed;
+13 -13
View File
@@ -38,15 +38,15 @@ namespace HTTP
// forward decls // forward decls
class Connection; class Connection;
class Client class Client
{ {
public: public:
Client(); Client();
~Client(); ~Client();
void update(int waitTimeout = 0); void update(int waitTimeout = 0);
void makeRequest(const Request_ptr& r); void makeRequest(const Request_ptr& r);
/** /**
@@ -68,31 +68,31 @@ public:
void setUserAgent(const std::string& ua); void setUserAgent(const std::string& ua);
void setProxy(const std::string& proxy, int port, const std::string& auth = ""); void setProxy(const std::string& proxy, int port, const std::string& auth = "");
/** /**
* Specify the maximum permitted simultaneous connections * Specify the maximum permitted simultaneous connections
* (default value is 1) * (default value is 1)
*/ */
void setMaxConnections(unsigned int maxCons); void setMaxConnections(unsigned int maxCons);
const std::string& userAgent() const; const std::string& userAgent() const;
const std::string& proxyHost() const; const std::string& proxyHost() const;
const std::string& proxyAuth() const; const std::string& proxyAuth() const;
/** /**
* predicate, check if at least one connection is active, with at * predicate, check if at least one connection is active, with at
* least one request active or queued. * least one request active or queued.
*/ */
bool hasActiveRequests() const; bool hasActiveRequests() const;
/** /**
* crude tracking of bytes-per-second transferred over the socket. * crude tracking of bytes-per-second transferred over the socket.
* suitable for user feedback and rough profiling, nothing more. * suitable for user feedback and rough profiling, nothing more.
*/ */
unsigned int transferRateBytesPerSec() const; unsigned int transferRateBytesPerSec() const;
/** /**
* total bytes downloaded by this HTTP client, for bandwidth usage * total bytes downloaded by this HTTP client, for bandwidth usage
* monitoring * monitoring
@@ -100,12 +100,12 @@ public:
uint64_t totalBytesDownloaded() const; uint64_t totalBytesDownloaded() const;
private: private:
void requestFinished(Connection* con); void requestFinished(Connection* con);
void receivedBytes(unsigned int count); void receivedBytes(unsigned int count);
friend class Connection; friend class Connection;
friend class Request; friend class Request;
class ClientPrivate; class ClientPrivate;
std::auto_ptr<ClientPrivate> d; std::auto_ptr<ClientPrivate> d;
}; };
+14 -14
View File
@@ -124,19 +124,19 @@ public:
void setBodyData( const SGPropertyNode* data ); void setBodyData( const SGPropertyNode* data );
virtual void setUrl(const std::string& url); virtual void setUrl(const std::string& url);
virtual std::string method() const virtual std::string method() const
{ return _method; } { return _method; }
virtual std::string url() const virtual std::string url() const
{ return _url; } { return _url; }
virtual std::string scheme() const; virtual std::string scheme() const;
virtual std::string path() const; virtual std::string path() const;
virtual std::string host() const; virtual std::string host() const;
virtual std::string hostAndPort() const; virtual std::string hostAndPort() const;
virtual unsigned short port() const; virtual unsigned short port() const;
virtual std::string query() const; virtual std::string query() const;
StringMap const& responseHeaders() const StringMap const& responseHeaders() const
{ return _responseHeaders; } { return _responseHeaders; }
@@ -144,13 +144,13 @@ public:
virtual int responseCode() const virtual int responseCode() const
{ return _responseStatus; } { return _responseStatus; }
virtual std::string responseReason() const virtual std::string responseReason() const
{ return _responseReason; } { return _responseReason; }
void setResponseLength(unsigned int l); void setResponseLength(unsigned int l);
virtual unsigned int responseLength() const; virtual unsigned int responseLength() const;
/** /**
* Check if request contains body data. * Check if request contains body data.
*/ */
@@ -165,32 +165,32 @@ public:
* Retrieve the size of the request body. * Retrieve the size of the request body.
*/ */
virtual size_t bodyLength() const; virtual size_t bodyLength() const;
/** /**
* Retrieve the body data bytes. Will be passed the maximum body bytes * Retrieve the body data bytes. Will be passed the maximum body bytes
* to return in the buffer, and must return the actual number * to return in the buffer, and must return the actual number
* of bytes written. * of bytes written.
*/ */
virtual size_t getBodyData(char* s, size_t offset, size_t max_count) const; virtual size_t getBodyData(char* s, size_t offset, size_t max_count) const;
/** /**
* running total of body bytes received so far. Can be used * running total of body bytes received so far. Can be used
* to generate a completion percentage, if the response length is * to generate a completion percentage, if the response length is
* known. * known.
*/ */
unsigned int responseBytesReceived() const unsigned int responseBytesReceived() const
{ return _receivedBodyBytes; } { return _receivedBodyBytes; }
enum HTTPVersion { enum HTTPVersion {
HTTP_VERSION_UNKNOWN = 0, HTTP_VERSION_UNKNOWN = 0,
HTTP_0_x, // 0.9 or similar HTTP_0_x, // 0.9 or similar
HTTP_1_0, HTTP_1_0,
HTTP_1_1 HTTP_1_1
}; };
HTTPVersion responseVersion() const HTTPVersion responseVersion() const
{ return _responseVersion; } { return _responseVersion; }
ReadyState readyState() const { return _ready_state; } ReadyState readyState() const { return _ready_state; }
/** /**
@@ -226,7 +226,7 @@ private:
friend class Client; friend class Client;
friend class Connection; friend class Connection;
friend class ContentDecoder; friend class ContentDecoder;
Request(const Request&); // = delete; Request(const Request&); // = delete;
Request& operator=(const Request&); // = delete; Request& operator=(const Request&); // = delete;
+1 -1
View File
@@ -1,6 +1,6 @@
/* -*-c++-*- /* -*-c++-*-
* *
* Copyright (C) 2005-2006 Mathias Froehlich * Copyright (C) 2005-2006 Mathias Froehlich
* *
* This program is free software; you can redistribute it and/or * This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as * modify it under the terms of the GNU General Public License as