1 #include "HTTPClient.hxx"
7 #include <boost/foreach.hpp>
8 #include <boost/algorithm/string/case_conv.hpp>
10 #include <simgear/io/sg_netChat.hxx>
11 #include <simgear/misc/strutils.hxx>
12 #include <simgear/compiler.h>
13 #include <simgear/debug/logstream.hxx>
14 #include <simgear/timing/timestamp.hxx>
16 #if defined( HAVE_VERSION_H ) && HAVE_VERSION_H
19 # if !defined(SIMGEAR_VERSION)
20 # define SIMGEAR_VERSION "simgear-development"
25 using std::stringstream;
29 //using namespace std;
37 extern const int DEFAULT_HTTP_PORT = 80;
39 class Connection : public NetChat
42 Connection(Client* pr) :
45 port(DEFAULT_HTTP_PORT)
50 void setServer(const string& h, short p)
56 // socket-level errors
57 virtual void handleError(int error)
59 NetChat::handleError(error);
61 SG_LOG(SG_IO, SG_INFO, "HTTP socket error");
62 activeRequest->setFailure(error, "socket error");
66 state = STATE_SOCKET_ERROR;
69 virtual void handleClose()
71 NetChat::handleClose();
73 if ((state == STATE_GETTING_BODY) && activeRequest) {
74 // force state here, so responseComplete can avoid closing the
83 void queueRequest(const Request_ptr& r)
88 queuedRequests.push_back(r);
92 void startRequest(const Request_ptr& r)
94 if (state == STATE_CLOSED) {
95 if (!connectToHost()) {
104 bodyTransferSize = -1;
105 chunkedTransfer = false;
106 setTerminator("\r\n");
108 stringstream headerData;
109 string path = r->path();
110 if (!client->proxyHost().empty()) {
114 headerData << r->method() << " " << path << " HTTP/1.1\r\n";
115 headerData << "Host: " << r->hostAndPort() << "\r\n";
116 headerData << "User-Agent:" << client->userAgent() << "\r\n";
117 if (!client->proxyAuth().empty()) {
118 headerData << "Proxy-Authorization: " << client->proxyAuth() << "\r\n";
121 BOOST_FOREACH(string h, r->requestHeaders()) {
122 headerData << h << ": " << r->header(h) << "\r\n";
125 headerData << "\r\n"; // final CRLF to terminate the headers
127 // TODO - add request body support for PUT, etc operations
129 bool ok = push(headerData.str().c_str());
131 SG_LOG(SG_IO, SG_WARN, "HTTP writing to socket failed");
132 state = STATE_SOCKET_ERROR;
137 virtual void collectIncomingData(const char* s, int n)
139 if ((state == STATE_GETTING_BODY) || (state == STATE_GETTING_CHUNKED_BYTES)) {
140 activeRequest->processBodyBytes(s, n);
142 buffer += string(s, n);
146 virtual void foundTerminator(void)
150 activeRequest->responseStart(buffer);
151 state = STATE_GETTING_HEADERS;
155 case STATE_GETTING_HEADERS:
160 case STATE_GETTING_BODY:
164 case STATE_GETTING_CHUNKED:
165 processChunkHeader();
168 case STATE_GETTING_CHUNKED_BYTES:
169 setTerminator("\r\n");
170 state = STATE_GETTING_CHUNKED;
173 case STATE_GETTING_TRAILER:
183 bool hasIdleTimeout() const
185 if (state != STATE_IDLE) {
189 return idleTime.elapsedMSec() > 1000 * 10; // ten seconds
192 bool hasError() const
194 return (state == STATE_SOCKET_ERROR);
197 bool shouldStartNext() const
199 return !activeRequest && !queuedRequests.empty() &&
200 ((state == STATE_CLOSED) || (state == STATE_IDLE));
205 Request_ptr next = queuedRequests.front();
206 queuedRequests.pop_front();
212 SG_LOG(SG_IO, SG_INFO, "HTTP connecting to " << host << ":" << port);
215 SG_LOG(SG_ALL, SG_WARN, "HTTP::Connection: connectToHost: open() failed");
219 if (connect(host.c_str(), port) != 0) {
229 string h = strutils::simplify(buffer);
230 if (h.empty()) { // blank line terminates headers
233 if (chunkedTransfer) {
234 state = STATE_GETTING_CHUNKED;
236 setByteCount(bodyTransferSize); // may be -1, that's fine
237 state = STATE_GETTING_BODY;
243 int colonPos = buffer.find(':');
245 SG_LOG(SG_IO, SG_WARN, "malformed HTTP response header:" << h);
249 string key = strutils::simplify(buffer.substr(0, colonPos));
250 string lkey = boost::to_lower_copy(key);
251 string value = strutils::strip(buffer.substr(colonPos + 1));
253 // only consider these if getting headers (as opposed to trailers
254 // of a chunked transfer)
255 if (state == STATE_GETTING_HEADERS) {
256 if (lkey == "content-length") {
257 int sz = strutils::to_int(value);
258 if (bodyTransferSize <= 0) {
259 bodyTransferSize = sz;
261 activeRequest->setResponseLength(sz);
262 } else if (lkey == "transfer-length") {
263 bodyTransferSize = strutils::to_int(value);
264 } else if (lkey == "transfer-encoding") {
265 processTransferEncoding(value);
269 activeRequest->responseHeader(lkey, value);
272 void processTransferEncoding(const string& te)
274 if (te == "chunked") {
275 chunkedTransfer = true;
277 SG_LOG(SG_IO, SG_WARN, "unsupported transfer encoding:" << te);
282 void processChunkHeader()
284 if (buffer.empty()) {
285 // blank line after chunk data
290 int semiPos = buffer.find(';');
292 // extensions ignored for the moment
293 chunkSize = strutils::to_int(buffer.substr(0, semiPos), 16);
295 chunkSize = strutils::to_int(buffer, 16);
299 if (chunkSize == 0) { // trailer start
300 state = STATE_GETTING_TRAILER;
304 state = STATE_GETTING_CHUNKED_BYTES;
305 setByteCount(chunkSize);
308 void processTrailer()
310 if (buffer.empty()) {
316 // process as a normal header
320 void headersComplete()
322 activeRequest->responseHeadersComplete();
325 void responseComplete()
327 activeRequest->responseComplete();
328 client->requestFinished(this);
329 //cout << "response complete: " << activeRequest->url() << endl;
331 bool doClose = activeRequest->closeAfterComplete();
332 activeRequest = NULL;
333 if (state == STATE_GETTING_BODY) {
336 // this will bring us into handleClose() above, which updates
337 // state to STATE_CLOSED
342 setTerminator("\r\n");
344 // if we have more requests, and we're idle, can start the next
345 // request immediately. Note we cannot do this if we're in STATE_CLOSED,
346 // since NetChannel::close cleans up state after calling handleClose;
347 // instead we pick up waiting requests in update()
348 if (!queuedRequests.empty() && (state == STATE_IDLE)) {
355 enum ConnectionState {
357 STATE_GETTING_HEADERS,
359 STATE_GETTING_CHUNKED,
360 STATE_GETTING_CHUNKED_BYTES,
361 STATE_GETTING_TRAILER,
363 STATE_CLOSED ///< connection should be closed now
367 Request_ptr activeRequest;
368 ConnectionState state;
372 int bodyTransferSize;
373 SGTimeStamp idleTime;
374 bool chunkedTransfer;
376 std::list<Request_ptr> queuedRequests;
381 setUserAgent("SimGear-" SG_STRINGIZE(SIMGEAR_VERSION));
384 void Client::update()
388 ConnectionDict::iterator it = _connections.begin();
389 for (; it != _connections.end(); ) {
390 if (it->second->hasIdleTimeout() || it->second->hasError()) {
391 // connection has been idle for a while, clean it up
392 // (or has an error condition, again clean it up)
393 SG_LOG(SG_IO, SG_INFO, "cleaning up " << it->second);
394 ConnectionDict::iterator del = it++;
396 _connections.erase(del);
398 if (it->second->shouldStartNext()) {
399 it->second->startNext();
404 } // of connecion iteration
407 void Client::makeRequest(const Request_ptr& r)
409 string host = r->host();
410 int port = r->port();
411 if (!_proxy.empty()) {
417 ss << host << "-" << port;
418 string connectionId = ss.str();
420 if (_connections.find(connectionId) == _connections.end()) {
421 Connection* con = new Connection(this);
422 con->setServer(host, port);
423 _connections[connectionId] = con;
426 _connections[connectionId]->queueRequest(r);
429 void Client::requestFinished(Connection* con)
434 void Client::setUserAgent(const string& ua)
439 void Client::setProxy(const string& proxy, int port, const string& auth)
446 } // of namespace HTTP
448 } // of namespace simgear