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 } catch (sg_exception& e) {
223 state = STATE_GETTING_HEADERS;
225 if (activeRequest->responseCode() == 204) {
226 noMessageBody = true;
227 } else if (activeRequest->method() == "HEAD") {
228 noMessageBody = true;
230 noMessageBody = false;
233 bodyTransferSize = -1;
234 chunkedTransfer = false;
235 _contentDecoder.reset();
238 void tryStartNextRequest()
240 while( !queuedRequests.empty()
241 && queuedRequests.front()->isComplete() )
242 queuedRequests.pop_front();
244 if (queuedRequests.empty()) {
249 if (sentRequests.size() > MAX_INFLIGHT_REQUESTS) {
253 if (state == STATE_CLOSED) {
254 if (!connectToHost()) {
258 setTerminator("\r\n");
262 Request_ptr r = queuedRequests.front();
265 std::stringstream headerData;
266 std::string path = r->path();
267 assert(!path.empty());
268 std::string query = r->query();
269 std::string bodyData;
271 if (!client->proxyHost().empty()) {
272 path = r->scheme() + "://" + r->host() + r->path();
275 if (r->bodyType() == CONTENT_TYPE_URL_ENCODED) {
276 headerData << r->method() << " " << path << " HTTP/1.1\r\n";
277 bodyData = query.substr(1); // URL-encode, drop the leading '?'
278 headerData << "Content-Type:" << CONTENT_TYPE_URL_ENCODED << "\r\n";
279 headerData << "Content-Length:" << bodyData.size() << "\r\n";
281 headerData << r->method() << " " << path << query << " HTTP/1.1\r\n";
282 if( r->hasBodyData() )
284 headerData << "Content-Length:" << r->bodyLength() << "\r\n";
285 headerData << "Content-Type:" << r->bodyType() << "\r\n";
289 headerData << "Host: " << r->hostAndPort() << "\r\n";
290 headerData << "User-Agent:" << client->userAgent() << "\r\n";
291 headerData << "Accept-Encoding: deflate, gzip\r\n";
292 if (!client->proxyAuth().empty()) {
293 headerData << "Proxy-Authorization: " << client->proxyAuth() << "\r\n";
296 BOOST_FOREACH(const StringMap::value_type& h, r->requestHeaders()) {
297 headerData << h.first << ": " << h.second << "\r\n";
300 headerData << "\r\n"; // final CRLF to terminate the headers
301 if (!bodyData.empty()) {
302 headerData << bodyData;
305 bool ok = push(headerData.str().c_str());
307 SG_LOG(SG_IO, SG_WARN, "HTTPClient: over-stuffed the socket");
308 // we've over-stuffed the socket, give up for now, let things
309 // drain down before trying to start any more requests.
313 if( r->hasBodyData() )
314 for(size_t body_bytes_sent = 0; body_bytes_sent < r->bodyLength();)
317 size_t len = r->getBodyData(buf, body_bytes_sent, 4096);
320 if( !bufferSend(buf, len) )
324 "overflow the HTTP::Connection output buffer");
325 state = STATE_SOCKET_ERROR;
328 body_bytes_sent += len;
334 "HTTP asynchronous request body generation is unsupported");
339 // SG_LOG(SG_IO, SG_INFO, "did start request:" << r->url() <<
340 // "\n\t @ " << reinterpret_cast<void*>(r.ptr()) <<
341 // "\n\t on connection " << this);
342 // successfully sent, remove from queue, and maybe send the next
343 queuedRequests.pop_front();
344 sentRequests.push_back(r);
345 state = STATE_WAITING_FOR_RESPONSE;
347 // pipelining, let's maybe send the next request right away
348 tryStartNextRequest();
351 virtual void collectIncomingData(const char* s, int n)
354 client->receivedBytes(static_cast<unsigned int>(n));
356 if( (state == STATE_GETTING_BODY)
357 || (state == STATE_GETTING_CHUNKED_BYTES) )
358 _contentDecoder.receivedBytes(s, n);
363 virtual void foundTerminator(void)
367 case STATE_WAITING_FOR_RESPONSE:
371 case STATE_GETTING_HEADERS:
376 case STATE_GETTING_BODY:
380 case STATE_GETTING_CHUNKED:
381 processChunkHeader();
384 case STATE_GETTING_CHUNKED_BYTES:
385 setTerminator("\r\n");
386 state = STATE_GETTING_CHUNKED;
391 case STATE_GETTING_TRAILER:
397 SG_LOG(SG_IO, SG_WARN, "HTTP got data in IDLE state, bad server?");
404 bool hasIdleTimeout() const
406 if (state != STATE_IDLE) {
410 assert(sentRequests.empty());
411 return idleTime.elapsedMSec() > 1000 * 10; // ten seconds
414 bool hasErrorTimeout() const
416 if (state == STATE_IDLE) {
420 return idleTime.elapsedMSec() > (1000 * 30); // 30 seconds
423 bool hasError() const
425 return (state == STATE_SOCKET_ERROR);
428 bool shouldStartNext() const
430 return !queuedRequests.empty() && (sentRequests.size() < MAX_INFLIGHT_REQUESTS);
433 bool isActive() const
435 return !queuedRequests.empty() || !sentRequests.empty();
440 SG_LOG(SG_IO, SG_DEBUG, "HTTP connecting to " << host << ":" << port);
443 SG_LOG(SG_ALL, SG_WARN, "HTTP::Connection: connectToHost: open() failed");
447 if (connect(host.c_str(), port) != 0) {
457 std::string h = strutils::simplify(buffer);
458 if (h.empty()) { // blank line terminates headers
463 int colonPos = buffer.find(':');
465 SG_LOG(SG_IO, SG_WARN, "malformed HTTP response header:" << h);
469 std::string key = strutils::simplify(buffer.substr(0, colonPos));
470 std::string lkey = boost::to_lower_copy(key);
471 std::string value = strutils::strip(buffer.substr(colonPos + 1));
473 // only consider these if getting headers (as opposed to trailers
474 // of a chunked transfer)
475 if (state == STATE_GETTING_HEADERS) {
476 if (lkey == "content-length") {
478 int sz = strutils::to_int(value);
479 if (bodyTransferSize <= 0) {
480 bodyTransferSize = sz;
482 activeRequest->setResponseLength(sz);
483 } else if (lkey == "transfer-length") {
484 bodyTransferSize = strutils::to_int(value);
485 } else if (lkey == "transfer-encoding") {
486 processTransferEncoding(value);
487 } else if (lkey == "content-encoding") {
488 _contentDecoder.setEncoding(value);
492 activeRequest->responseHeader(lkey, value);
495 void processTransferEncoding(const std::string& te)
497 if (te == "chunked") {
498 chunkedTransfer = true;
500 SG_LOG(SG_IO, SG_WARN, "unsupported transfer encoding:" << te);
505 void processChunkHeader()
507 if (buffer.empty()) {
508 // blank line after chunk data
513 int semiPos = buffer.find(';');
515 // extensions ignored for the moment
516 chunkSize = strutils::to_int(buffer.substr(0, semiPos), 16);
518 chunkSize = strutils::to_int(buffer, 16);
522 if (chunkSize == 0) { // trailer start
523 state = STATE_GETTING_TRAILER;
527 state = STATE_GETTING_CHUNKED_BYTES;
528 setByteCount(chunkSize);
531 void processTrailer()
533 if (buffer.empty()) {
539 // process as a normal header
543 void headersComplete()
545 activeRequest->responseHeadersComplete();
546 _contentDecoder.initWithRequest(activeRequest);
548 if (chunkedTransfer) {
549 state = STATE_GETTING_CHUNKED;
550 } else if (noMessageBody || (bodyTransferSize == 0)) {
551 // force the state to GETTING_BODY, to simplify logic in
552 // responseComplete and handleClose
553 state = STATE_GETTING_BODY;
556 setByteCount(bodyTransferSize); // may be -1, that's fine
557 state = STATE_GETTING_BODY;
561 void responseComplete()
563 Request_ptr completedRequest = activeRequest;
564 _contentDecoder.finish();
566 assert(sentRequests.front() == activeRequest);
567 sentRequests.pop_front();
568 bool doClose = activeRequest->closeAfterComplete();
569 activeRequest = NULL;
571 if ((state == STATE_GETTING_BODY) || (state == STATE_GETTING_TRAILER)) {
573 // this will bring us into handleClose() above, which updates
574 // state to STATE_CLOSED
577 // if we have additional requests waiting, try to start them now
578 tryStartNextRequest();
582 if (state != STATE_CLOSED) {
583 state = sentRequests.empty() ? STATE_IDLE : STATE_WAITING_FOR_RESPONSE;
586 // notify request after we change state, so this connection is idle
587 // if completion triggers other requests (which is likely)
588 // SG_LOG(SG_IO, SG_INFO, "*** responseComplete:" << activeRequest->url());
589 completedRequest->responseComplete();
590 client->requestFinished(this);
592 setTerminator("\r\n");
595 enum ConnectionState {
597 STATE_WAITING_FOR_RESPONSE,
598 STATE_GETTING_HEADERS,
600 STATE_GETTING_CHUNKED,
601 STATE_GETTING_CHUNKED_BYTES,
602 STATE_GETTING_TRAILER,
604 STATE_CLOSED ///< connection should be closed now
608 Request_ptr activeRequest;
609 ConnectionState state;
613 int bodyTransferSize;
614 SGTimeStamp idleTime;
615 bool chunkedTransfer;
618 RequestList queuedRequests;
619 RequestList sentRequests;
621 ContentDecoder _contentDecoder;
628 d->maxConnections = 4;
629 d->bytesTransferred = 0;
630 d->lastTransferRate = 0;
631 d->timeTransferSample.stamp();
632 d->totalBytesDownloaded = 0;
634 setUserAgent("SimGear-" SG_STRINGIZE(SIMGEAR_VERSION));
641 void Client::setMaxConnections(unsigned int maxCon)
644 throw sg_range_exception("illegal HTTP::Client::setMaxConnections value");
647 d->maxConnections = maxCon;
650 void Client::update(int waitTimeout)
652 if (!d->poller.hasChannels() && (waitTimeout > 0)) {
653 SGTimeStamp::sleepForMSec(waitTimeout);
655 d->poller.poll(waitTimeout);
658 bool waitingRequests = !d->pendingRequests.empty();
659 ConnectionDict::iterator it = d->connections.begin();
660 for (; it != d->connections.end(); ) {
661 Connection* con = it->second;
662 if (con->hasIdleTimeout() ||
664 con->hasErrorTimeout() ||
665 (!con->isActive() && waitingRequests))
667 if (con->hasErrorTimeout()) {
668 // tell the connection we're timing it out
669 con->handleTimeout();
672 // connection has been idle for a while, clean it up
673 // (or if we have requests waiting for a different host,
674 // or an error condition
675 ConnectionDict::iterator del = it++;
677 d->connections.erase(del);
679 if (it->second->shouldStartNext()) {
680 it->second->tryStartNextRequest();
684 } // of connection iteration
686 if (waitingRequests && (d->connections.size() < d->maxConnections)) {
687 RequestList waiting(d->pendingRequests);
688 d->pendingRequests.clear();
690 // re-submit all waiting requests in order; this takes care of
691 // finding multiple pending items targetted to the same (new)
693 BOOST_FOREACH(Request_ptr req, waiting) {
699 void Client::makeRequest(const Request_ptr& r)
701 if( r->isComplete() )
704 if( r->url().find("://") == std::string::npos ) {
705 r->setFailure(EINVAL, "malformed URL");
709 if( r->url().find("http://") != 0 ) {
710 r->setFailure(EINVAL, "only HTTP protocol is supported");
714 std::string host = r->host();
715 int port = r->port();
716 if (!d->proxy.empty()) {
721 Connection* con = NULL;
722 std::stringstream ss;
723 ss << host << "-" << port;
724 std::string connectionId = ss.str();
725 bool havePending = !d->pendingRequests.empty();
726 bool atConnectionsLimit = d->connections.size() >= d->maxConnections;
727 ConnectionDict::iterator consEnd = d->connections.end();
729 // assign request to an existing Connection.
730 // various options exist here, examined in order
731 ConnectionDict::iterator it = d->connections.find(connectionId);
732 if (atConnectionsLimit && (it == consEnd)) {
733 // maximum number of connections active, queue this request
734 // when a connection goes inactive, we'll start this one
735 d->pendingRequests.push_back(r);
739 // scan for an idle Connection to the same host (likely if we're
740 // retrieving multiple resources from the same host in quick succession)
741 // if we have pending requests (waiting for a free Connection), then
742 // force new requests on this id to always use the first Connection
743 // (instead of the random selection below). This ensures that when
744 // there's pressure on the number of connections to keep alive, one
745 // host can't DoS every other.
747 for (; (it != consEnd) && (it->first == connectionId); ++it, ++count) {
748 if (havePending || !it->second->isActive()) {
754 if (!con && atConnectionsLimit) {
755 // all current connections are busy (active), and we don't
756 // have free connections to allocate, so let's assign to
757 // an existing one randomly. Ideally we'd used whichever one will
758 // complete first but we don't have that info.
759 int index = rand() % count;
760 for (it = d->connections.find(connectionId); index > 0; --index) { ; }
764 // allocate a new connection object
766 con = new Connection(this);
767 con->setServer(host, port);
768 d->poller.addChannel(con);
769 d->connections.insert(d->connections.end(),
770 ConnectionDict::value_type(connectionId, con));
773 con->queueRequest(r);
776 //------------------------------------------------------------------------------
777 FileRequestRef Client::save( const std::string& url,
778 const std::string& filename )
780 FileRequestRef req = new FileRequest(url, filename);
785 //------------------------------------------------------------------------------
786 MemoryRequestRef Client::load(const std::string& url)
788 MemoryRequestRef req = new MemoryRequest(url);
793 void Client::requestFinished(Connection* con)
798 void Client::setUserAgent(const std::string& ua)
803 const std::string& Client::userAgent() const
808 const std::string& Client::proxyHost() const
813 const std::string& Client::proxyAuth() const
818 void Client::setProxy( const std::string& proxy,
820 const std::string& auth )
827 bool Client::hasActiveRequests() const
829 ConnectionDict::const_iterator it = d->connections.begin();
830 for (; it != d->connections.end(); ++it) {
831 if (it->second->isActive()) return true;
837 void Client::receivedBytes(unsigned int count)
839 d->bytesTransferred += count;
840 d->totalBytesDownloaded += count;
843 unsigned int Client::transferRateBytesPerSec() const
845 unsigned int e = d->timeTransferSample.elapsedMSec();
847 // too long a window, ignore
848 d->timeTransferSample.stamp();
849 d->bytesTransferred = 0;
850 d->lastTransferRate = 0;
854 if (e < 100) { // avoid really narrow windows
855 return d->lastTransferRate;
858 unsigned int ratio = (d->bytesTransferred * 1000) / e;
859 // run a low-pass filter
860 unsigned int smoothed = ((400 - e) * d->lastTransferRate) + (e * ratio);
863 d->timeTransferSample.stamp();
864 d->bytesTransferred = 0;
865 d->lastTransferRate = smoothed;
869 uint64_t Client::totalBytesDownloaded() const
871 return d->totalBytesDownloaded;
874 } // of namespace HTTP
876 } // of namespace simgear