2 * \file HTTPClient.cxx - simple HTTP client engine for SimHear
5 // Written by James Turner
7 // Copyright (C) 2013 James Turner <zakalawe@mac.com>
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Library General Public
11 // License as published by the Free Software Foundation; either
12 // version 2 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Library General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
24 #include "HTTPClient.hxx"
25 #include "HTTPFileRequest.hxx"
29 #include <cstdlib> // rand()
35 #include <boost/foreach.hpp>
36 #include <boost/algorithm/string/case_conv.hpp>
38 #include <simgear/io/sg_netChat.hxx>
39 #include <simgear/io/HTTPContentDecode.hxx>
40 #include <simgear/misc/strutils.hxx>
41 #include <simgear/compiler.h>
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/timing/timestamp.hxx>
44 #include <simgear/structure/exception.hxx>
46 #if defined( HAVE_VERSION_H ) && HAVE_VERSION_H
49 # if !defined(SIMGEAR_VERSION)
50 # define SIMGEAR_VERSION "simgear-development"
60 extern const int DEFAULT_HTTP_PORT = 80;
61 const char* CONTENT_TYPE_URL_ENCODED = "application/x-www-form-urlencoded";
62 const unsigned int MAX_INFLIGHT_REQUESTS = 32;
65 typedef std::multimap<std::string, Connection*> ConnectionDict;
66 typedef std::list<Request_ptr> RequestList;
68 class Client::ClientPrivate
71 std::string userAgent;
74 std::string proxyAuth;
75 NetChannelPoller poller;
76 unsigned int maxConnections;
78 RequestList pendingRequests;
80 // connections by host (potentially more than one)
81 ConnectionDict connections;
83 SGTimeStamp timeTransferSample;
84 unsigned int bytesTransferred;
85 unsigned int lastTransferRate;
86 uint64_t totalBytesDownloaded;
89 class Connection : public NetChat
92 Connection(Client* pr) :
95 port(DEFAULT_HTTP_PORT)
103 virtual void handleBufferRead (NetBuffer& buffer)
105 if( !activeRequest || !activeRequest->isComplete() )
106 return NetChat::handleBufferRead(buffer);
108 // Request should be aborted (signaled by setting its state to complete).
110 // force the state to GETTING_BODY, to simplify logic in
111 // responseComplete and handleClose
112 state = STATE_GETTING_BODY;
116 void setServer(const std::string& h, short p)
122 // socket-level errors
123 virtual void handleError(int error)
125 if (error == ENOENT) {
126 // name lookup failure
127 // we won't have an active request yet, so the logic below won't
128 // fire to actually call setFailure. Let's fail all of the requests
129 BOOST_FOREACH(Request_ptr req, sentRequests) {
130 req->setFailure(error, "hostname lookup failure");
133 BOOST_FOREACH(Request_ptr req, queuedRequests) {
134 req->setFailure(error, "hostname lookup failure");
137 // name lookup failure, abandon all requests on this connection
138 sentRequests.clear();
139 queuedRequests.clear();
142 NetChat::handleError(error);
144 SG_LOG(SG_IO, SG_INFO, "HTTP socket error");
145 activeRequest->setFailure(error, "socket error");
146 activeRequest = NULL;
147 _contentDecoder.reset();
150 state = STATE_SOCKET_ERROR;
153 virtual void handleClose()
155 NetChat::handleClose();
157 // closing of the connection from the server side when getting the body,
158 bool canCloseState = (state == STATE_GETTING_BODY);
159 if (canCloseState && activeRequest) {
160 // force state here, so responseComplete can avoid closing the
162 state = STATE_CLOSED;
166 activeRequest->setFailure(500, "server closed connection");
167 // remove the failed request from sentRequests, so it does
169 RequestList::iterator it = std::find(sentRequests.begin(),
170 sentRequests.end(), activeRequest);
171 if (it != sentRequests.end()) {
172 sentRequests.erase(it);
174 activeRequest = NULL;
175 _contentDecoder.reset();
178 state = STATE_CLOSED;
181 if (sentRequests.empty()) {
185 // restore sent requests to the queue, so they will be re-sent
186 // when the connection opens again
187 queuedRequests.insert(queuedRequests.begin(),
188 sentRequests.begin(), sentRequests.end());
189 sentRequests.clear();
194 NetChat::handleError(ETIMEDOUT);
196 SG_LOG(SG_IO, SG_DEBUG, "HTTP socket timeout");
197 activeRequest->setFailure(ETIMEDOUT, "socket timeout");
198 activeRequest = NULL;
199 _contentDecoder.reset();
202 state = STATE_SOCKET_ERROR;
205 void queueRequest(const Request_ptr& r)
207 queuedRequests.push_back(r);
208 tryStartNextRequest();
213 assert(!sentRequests.empty());
214 assert(state == STATE_WAITING_FOR_RESPONSE);
216 activeRequest = sentRequests.front();
218 activeRequest->responseStart(buffer);
219 state = STATE_GETTING_HEADERS;
221 if (activeRequest->responseCode() == 204) {
222 noMessageBody = true;
223 } else if (activeRequest->method() == "HEAD") {
224 noMessageBody = true;
226 noMessageBody = false;
229 bodyTransferSize = -1;
230 chunkedTransfer = false;
231 _contentDecoder.reset();
234 void tryStartNextRequest()
236 while( !queuedRequests.empty()
237 && queuedRequests.front()->isComplete() )
238 queuedRequests.pop_front();
240 if (queuedRequests.empty()) {
245 if (sentRequests.size() > MAX_INFLIGHT_REQUESTS) {
249 if (state == STATE_CLOSED) {
250 if (!connectToHost()) {
254 setTerminator("\r\n");
258 Request_ptr r = queuedRequests.front();
261 std::stringstream headerData;
262 std::string path = r->path();
263 assert(!path.empty());
264 std::string query = r->query();
265 std::string bodyData;
267 if (!client->proxyHost().empty()) {
268 path = r->scheme() + "://" + r->host() + r->path();
271 if (r->bodyType() == CONTENT_TYPE_URL_ENCODED) {
272 headerData << r->method() << " " << path << " HTTP/1.1\r\n";
273 bodyData = query.substr(1); // URL-encode, drop the leading '?'
274 headerData << "Content-Type:" << CONTENT_TYPE_URL_ENCODED << "\r\n";
275 headerData << "Content-Length:" << bodyData.size() << "\r\n";
277 headerData << r->method() << " " << path << query << " HTTP/1.1\r\n";
278 if( r->hasBodyData() )
280 headerData << "Content-Length:" << r->bodyLength() << "\r\n";
281 headerData << "Content-Type:" << r->bodyType() << "\r\n";
285 headerData << "Host: " << r->hostAndPort() << "\r\n";
286 headerData << "User-Agent:" << client->userAgent() << "\r\n";
287 headerData << "Accept-Encoding: deflate, gzip\r\n";
288 if (!client->proxyAuth().empty()) {
289 headerData << "Proxy-Authorization: " << client->proxyAuth() << "\r\n";
292 BOOST_FOREACH(const StringMap::value_type& h, r->requestHeaders()) {
293 headerData << h.first << ": " << h.second << "\r\n";
296 headerData << "\r\n"; // final CRLF to terminate the headers
297 if (!bodyData.empty()) {
298 headerData << bodyData;
301 bool ok = push(headerData.str().c_str());
303 SG_LOG(SG_IO, SG_WARN, "HTTPClient: over-stuffed the socket");
304 // we've over-stuffed the socket, give up for now, let things
305 // drain down before trying to start any more requests.
309 if( r->hasBodyData() )
310 for(size_t body_bytes_sent = 0; body_bytes_sent < r->bodyLength();)
313 size_t len = r->getBodyData(buf, body_bytes_sent, 4096);
316 if( !bufferSend(buf, len) )
320 "overflow the HTTP::Connection output buffer");
321 state = STATE_SOCKET_ERROR;
324 body_bytes_sent += len;
330 "HTTP asynchronous request body generation is unsupported");
335 // SG_LOG(SG_IO, SG_INFO, "did start request:" << r->url() <<
336 // "\n\t @ " << reinterpret_cast<void*>(r.ptr()) <<
337 // "\n\t on connection " << this);
338 // successfully sent, remove from queue, and maybe send the next
339 queuedRequests.pop_front();
340 sentRequests.push_back(r);
341 state = STATE_WAITING_FOR_RESPONSE;
343 // pipelining, let's maybe send the next request right away
344 tryStartNextRequest();
347 virtual void collectIncomingData(const char* s, int n)
350 client->receivedBytes(static_cast<unsigned int>(n));
352 if( (state == STATE_GETTING_BODY)
353 || (state == STATE_GETTING_CHUNKED_BYTES) )
354 _contentDecoder.receivedBytes(s, n);
359 virtual void foundTerminator(void)
363 case STATE_WAITING_FOR_RESPONSE:
367 case STATE_GETTING_HEADERS:
372 case STATE_GETTING_BODY:
376 case STATE_GETTING_CHUNKED:
377 processChunkHeader();
380 case STATE_GETTING_CHUNKED_BYTES:
381 setTerminator("\r\n");
382 state = STATE_GETTING_CHUNKED;
387 case STATE_GETTING_TRAILER:
393 SG_LOG(SG_IO, SG_WARN, "HTTP got data in IDLE state, bad server?");
400 bool hasIdleTimeout() const
402 if (state != STATE_IDLE) {
406 assert(sentRequests.empty());
407 return idleTime.elapsedMSec() > 1000 * 10; // ten seconds
410 bool hasErrorTimeout() const
412 if (state == STATE_IDLE) {
416 return idleTime.elapsedMSec() > (1000 * 30); // 30 seconds
419 bool hasError() const
421 return (state == STATE_SOCKET_ERROR);
424 bool shouldStartNext() const
426 return !queuedRequests.empty() && (sentRequests.size() < MAX_INFLIGHT_REQUESTS);
429 bool isActive() const
431 return !queuedRequests.empty() || !sentRequests.empty();
436 SG_LOG(SG_IO, SG_DEBUG, "HTTP connecting to " << host << ":" << port);
439 SG_LOG(SG_ALL, SG_WARN, "HTTP::Connection: connectToHost: open() failed");
443 if (connect(host.c_str(), port) != 0) {
453 std::string h = strutils::simplify(buffer);
454 if (h.empty()) { // blank line terminates headers
459 int colonPos = buffer.find(':');
461 SG_LOG(SG_IO, SG_WARN, "malformed HTTP response header:" << h);
465 std::string key = strutils::simplify(buffer.substr(0, colonPos));
466 std::string lkey = boost::to_lower_copy(key);
467 std::string value = strutils::strip(buffer.substr(colonPos + 1));
469 // only consider these if getting headers (as opposed to trailers
470 // of a chunked transfer)
471 if (state == STATE_GETTING_HEADERS) {
472 if (lkey == "content-length") {
474 int sz = strutils::to_int(value);
475 if (bodyTransferSize <= 0) {
476 bodyTransferSize = sz;
478 activeRequest->setResponseLength(sz);
479 } else if (lkey == "transfer-length") {
480 bodyTransferSize = strutils::to_int(value);
481 } else if (lkey == "transfer-encoding") {
482 processTransferEncoding(value);
483 } else if (lkey == "content-encoding") {
484 _contentDecoder.setEncoding(value);
488 activeRequest->responseHeader(lkey, value);
491 void processTransferEncoding(const std::string& te)
493 if (te == "chunked") {
494 chunkedTransfer = true;
496 SG_LOG(SG_IO, SG_WARN, "unsupported transfer encoding:" << te);
501 void processChunkHeader()
503 if (buffer.empty()) {
504 // blank line after chunk data
509 int semiPos = buffer.find(';');
511 // extensions ignored for the moment
512 chunkSize = strutils::to_int(buffer.substr(0, semiPos), 16);
514 chunkSize = strutils::to_int(buffer, 16);
518 if (chunkSize == 0) { // trailer start
519 state = STATE_GETTING_TRAILER;
523 state = STATE_GETTING_CHUNKED_BYTES;
524 setByteCount(chunkSize);
527 void processTrailer()
529 if (buffer.empty()) {
535 // process as a normal header
539 void headersComplete()
541 activeRequest->responseHeadersComplete();
542 _contentDecoder.initWithRequest(activeRequest);
544 if (chunkedTransfer) {
545 state = STATE_GETTING_CHUNKED;
546 } else if (noMessageBody || (bodyTransferSize == 0)) {
547 // force the state to GETTING_BODY, to simplify logic in
548 // responseComplete and handleClose
549 state = STATE_GETTING_BODY;
552 setByteCount(bodyTransferSize); // may be -1, that's fine
553 state = STATE_GETTING_BODY;
557 void responseComplete()
559 Request_ptr completedRequest = activeRequest;
560 _contentDecoder.finish();
562 assert(sentRequests.front() == activeRequest);
563 sentRequests.pop_front();
564 bool doClose = activeRequest->closeAfterComplete();
565 activeRequest = NULL;
567 if ((state == STATE_GETTING_BODY) || (state == STATE_GETTING_TRAILER)) {
569 // this will bring us into handleClose() above, which updates
570 // state to STATE_CLOSED
573 // if we have additional requests waiting, try to start them now
574 tryStartNextRequest();
578 if (state != STATE_CLOSED) {
579 state = sentRequests.empty() ? STATE_IDLE : STATE_WAITING_FOR_RESPONSE;
582 // notify request after we change state, so this connection is idle
583 // if completion triggers other requests (which is likely)
584 // SG_LOG(SG_IO, SG_INFO, "*** responseComplete:" << activeRequest->url());
585 completedRequest->responseComplete();
586 client->requestFinished(this);
588 setTerminator("\r\n");
591 enum ConnectionState {
593 STATE_WAITING_FOR_RESPONSE,
594 STATE_GETTING_HEADERS,
596 STATE_GETTING_CHUNKED,
597 STATE_GETTING_CHUNKED_BYTES,
598 STATE_GETTING_TRAILER,
600 STATE_CLOSED ///< connection should be closed now
604 Request_ptr activeRequest;
605 ConnectionState state;
609 int bodyTransferSize;
610 SGTimeStamp idleTime;
611 bool chunkedTransfer;
614 RequestList queuedRequests;
615 RequestList sentRequests;
617 ContentDecoder _contentDecoder;
624 d->maxConnections = 4;
625 d->bytesTransferred = 0;
626 d->lastTransferRate = 0;
627 d->timeTransferSample.stamp();
628 d->totalBytesDownloaded = 0;
630 setUserAgent("SimGear-" SG_STRINGIZE(SIMGEAR_VERSION));
637 void Client::setMaxConnections(unsigned int maxCon)
640 throw sg_range_exception("illegal HTTP::Client::setMaxConnections value");
643 d->maxConnections = maxCon;
646 void Client::update(int waitTimeout)
648 if (!d->poller.hasChannels() && (waitTimeout > 0)) {
649 SGTimeStamp::sleepForMSec(waitTimeout);
651 d->poller.poll(waitTimeout);
654 bool waitingRequests = !d->pendingRequests.empty();
655 ConnectionDict::iterator it = d->connections.begin();
656 for (; it != d->connections.end(); ) {
657 Connection* con = it->second;
658 if (con->hasIdleTimeout() ||
660 con->hasErrorTimeout() ||
661 (!con->isActive() && waitingRequests))
663 if (con->hasErrorTimeout()) {
664 // tell the connection we're timing it out
665 con->handleTimeout();
668 // connection has been idle for a while, clean it up
669 // (or if we have requests waiting for a different host,
670 // or an error condition
671 ConnectionDict::iterator del = it++;
673 d->connections.erase(del);
675 if (it->second->shouldStartNext()) {
676 it->second->tryStartNextRequest();
680 } // of connection iteration
682 if (waitingRequests && (d->connections.size() < d->maxConnections)) {
683 RequestList waiting(d->pendingRequests);
684 d->pendingRequests.clear();
686 // re-submit all waiting requests in order; this takes care of
687 // finding multiple pending items targetted to the same (new)
689 BOOST_FOREACH(Request_ptr req, waiting) {
695 void Client::makeRequest(const Request_ptr& r)
697 if( r->isComplete() )
700 if( r->url().find("://") == std::string::npos ) {
701 r->setFailure(EINVAL, "malformed URL");
705 if( r->url().find("http://") != 0 ) {
706 r->setFailure(EINVAL, "only HTTP protocol is supported");
710 std::string host = r->host();
711 int port = r->port();
712 if (!d->proxy.empty()) {
717 Connection* con = NULL;
718 std::stringstream ss;
719 ss << host << "-" << port;
720 std::string connectionId = ss.str();
721 bool havePending = !d->pendingRequests.empty();
722 bool atConnectionsLimit = d->connections.size() >= d->maxConnections;
723 ConnectionDict::iterator consEnd = d->connections.end();
725 // assign request to an existing Connection.
726 // various options exist here, examined in order
727 ConnectionDict::iterator it = d->connections.find(connectionId);
728 if (atConnectionsLimit && (it == consEnd)) {
729 // maximum number of connections active, queue this request
730 // when a connection goes inactive, we'll start this one
731 d->pendingRequests.push_back(r);
735 // scan for an idle Connection to the same host (likely if we're
736 // retrieving multiple resources from the same host in quick succession)
737 // if we have pending requests (waiting for a free Connection), then
738 // force new requests on this id to always use the first Connection
739 // (instead of the random selection below). This ensures that when
740 // there's pressure on the number of connections to keep alive, one
741 // host can't DoS every other.
743 for (; (it != consEnd) && (it->first == connectionId); ++it, ++count) {
744 if (havePending || !it->second->isActive()) {
750 if (!con && atConnectionsLimit) {
751 // all current connections are busy (active), and we don't
752 // have free connections to allocate, so let's assign to
753 // an existing one randomly. Ideally we'd used whichever one will
754 // complete first but we don't have that info.
755 int index = rand() % count;
756 for (it = d->connections.find(connectionId); index > 0; --index) { ; }
760 // allocate a new connection object
762 con = new Connection(this);
763 con->setServer(host, port);
764 d->poller.addChannel(con);
765 d->connections.insert(d->connections.end(),
766 ConnectionDict::value_type(connectionId, con));
769 con->queueRequest(r);
772 //------------------------------------------------------------------------------
773 FileRequestRef Client::save( const std::string& url,
774 const std::string& filename )
776 FileRequestRef req = new FileRequest(url, filename);
781 //------------------------------------------------------------------------------
782 MemoryRequestRef Client::load(const std::string& url)
784 MemoryRequestRef req = new MemoryRequest(url);
789 void Client::requestFinished(Connection* con)
794 void Client::setUserAgent(const std::string& ua)
799 const std::string& Client::userAgent() const
804 const std::string& Client::proxyHost() const
809 const std::string& Client::proxyAuth() const
814 void Client::setProxy( const std::string& proxy,
816 const std::string& auth )
823 bool Client::hasActiveRequests() const
825 ConnectionDict::const_iterator it = d->connections.begin();
826 for (; it != d->connections.end(); ++it) {
827 if (it->second->isActive()) return true;
833 void Client::receivedBytes(unsigned int count)
835 d->bytesTransferred += count;
836 d->totalBytesDownloaded += count;
839 unsigned int Client::transferRateBytesPerSec() const
841 unsigned int e = d->timeTransferSample.elapsedMSec();
843 // too long a window, ignore
844 d->timeTransferSample.stamp();
845 d->bytesTransferred = 0;
846 d->lastTransferRate = 0;
850 if (e < 100) { // avoid really narrow windows
851 return d->lastTransferRate;
854 unsigned int ratio = (d->bytesTransferred * 1000) / e;
855 // run a low-pass filter
856 unsigned int smoothed = ((400 - e) * d->lastTransferRate) + (e * ratio);
859 d->timeTransferSample.stamp();
860 d->bytesTransferred = 0;
861 d->lastTransferRate = smoothed;
865 uint64_t Client::totalBytesDownloaded() const
867 return d->totalBytesDownloaded;
870 } // of namespace HTTP
872 } // of namespace simgear