1 // Copyright (C) 2011 James Turner <zakalawe@mac.com>
2 // Copyright (C) 2013 Thomas Geymayer <tomgey@gmail.com>
4 // This library is free software; you can redistribute it and/or
5 // modify it under the terms of the GNU Library General Public
6 // License as published by the Free Software Foundation; either
7 // version 2 of the License, or (at your option) any later version.
9 // This library is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 // Library General Public License for more details.
14 // You should have received a copy of the GNU Library General Public
15 // License along with this library; if not, write to the Free Software
16 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
18 #include "HTTPRequest.hxx"
20 #include <simgear/compiler.h>
21 #include <simgear/debug/logstream.hxx>
22 #include <simgear/misc/strutils.hxx>
23 #include <simgear/props/props_io.hxx>
24 #include <simgear/structure/exception.hxx>
31 extern const int DEFAULT_HTTP_PORT;
33 //------------------------------------------------------------------------------
34 Request::Request(const std::string& url, const std::string method):
37 _responseVersion(HTTP_VERSION_UNKNOWN),
40 _receivedBodyBytes(0),
47 //------------------------------------------------------------------------------
53 //------------------------------------------------------------------------------
54 Request* Request::done(const Callback& cb)
56 if( _ready_state == DONE )
59 _cb_done.push_back(cb);
64 //------------------------------------------------------------------------------
65 Request* Request::fail(const Callback& cb)
67 if( _ready_state == FAILED )
70 _cb_fail.push_back(cb);
75 //------------------------------------------------------------------------------
76 Request* Request::always(const Callback& cb)
81 _cb_always.push_back(cb);
86 //------------------------------------------------------------------------------
87 void Request::setBodyData( const std::string& data,
88 const std::string& type )
91 _request_media_type = type;
93 if( !data.empty() && _method == "GET" )
97 //----------------------------------------------------------------------------
98 void Request::setBodyData(const SGPropertyNode* data)
103 std::stringstream buf;
104 writeProperties(buf, data, true);
106 setBodyData(buf.str(), "application/xml");
109 //------------------------------------------------------------------------------
110 void Request::setUrl(const std::string& url)
115 //------------------------------------------------------------------------------
116 void Request::requestStart()
118 setReadyState(OPENED);
121 //------------------------------------------------------------------------------
122 Request::HTTPVersion decodeHTTPVersion(const std::string& v)
124 if( v == "HTTP/1.1" ) return Request::HTTP_1_1;
125 if( v == "HTTP/1.0" ) return Request::HTTP_1_0;
126 if( strutils::starts_with(v, "HTTP/0.") ) return Request::HTTP_0_x;
127 return Request::HTTP_VERSION_UNKNOWN;
130 //------------------------------------------------------------------------------
131 void Request::responseStart(const std::string& r)
133 const int maxSplit = 2; // HTTP/1.1 nnn reason-string
134 string_list parts = strutils::split(r, NULL, maxSplit);
135 if (parts.size() != 3) {
136 throw sg_io_exception("bad HTTP response");
139 _responseVersion = decodeHTTPVersion(parts[0]);
140 _responseStatus = strutils::to_int(parts[1]);
141 _responseReason = parts[2];
144 //------------------------------------------------------------------------------
145 void Request::responseHeader(const std::string& key, const std::string& value)
147 if( key == "connection" )
148 _willClose = (value.find("close") != std::string::npos);
150 _responseHeaders[key] = value;
153 //------------------------------------------------------------------------------
154 void Request::responseHeadersComplete()
156 setReadyState(HEADERS_RECEIVED);
159 //------------------------------------------------------------------------------
160 void Request::responseComplete()
166 //------------------------------------------------------------------------------
167 void Request::gotBodyData(const char* s, int n)
169 setReadyState(LOADING);
172 //------------------------------------------------------------------------------
173 void Request::onDone()
178 //------------------------------------------------------------------------------
179 void Request::onFail()
185 "request failed:" << url() << " : "
186 << responseCode() << "/" << responseReason()
190 //------------------------------------------------------------------------------
191 void Request::onAlways()
196 //------------------------------------------------------------------------------
197 void Request::processBodyBytes(const char* s, int n)
199 _receivedBodyBytes += n;
203 //------------------------------------------------------------------------------
204 std::string Request::scheme() const
206 int firstColon = url().find(":");
207 if (firstColon > 0) {
208 return url().substr(0, firstColon);
211 return ""; // couldn't parse scheme
214 //------------------------------------------------------------------------------
215 std::string Request::path() const
217 std::string u(url());
218 int schemeEnd = u.find("://");
220 return ""; // couldn't parse scheme
223 int hostEnd = u.find('/', schemeEnd + 3);
225 // couldn't parse host, or URL looks like 'http://foo.com' (no trailing '/')
226 // fixup to root resource path: '/'
230 int query = u.find('?', hostEnd + 1);
232 // all remainder of URL is path
233 return u.substr(hostEnd);
236 return u.substr(hostEnd, query - hostEnd);
239 //------------------------------------------------------------------------------
240 std::string Request::query() const
242 std::string u(url());
243 int query = u.find('?');
245 return ""; //no query string found
248 return u.substr(query); //includes question mark
251 //------------------------------------------------------------------------------
252 std::string Request::host() const
254 std::string hp(hostAndPort());
255 int colonPos = hp.find(':');
257 return hp.substr(0, colonPos); // trim off the colon and port
259 return hp; // no port specifier
263 //------------------------------------------------------------------------------
264 unsigned short Request::port() const
266 std::string hp(hostAndPort());
267 int colonPos = hp.find(':');
269 return (unsigned short) strutils::to_int(hp.substr(colonPos + 1));
271 return DEFAULT_HTTP_PORT;
275 //------------------------------------------------------------------------------
276 std::string Request::hostAndPort() const
278 std::string u(url());
279 int schemeEnd = u.find("://");
281 return ""; // couldn't parse scheme
284 int hostEnd = u.find('/', schemeEnd + 3);
285 if (hostEnd < 0) { // all remainder of URL is host
286 return u.substr(schemeEnd + 3);
289 return u.substr(schemeEnd + 3, hostEnd - (schemeEnd + 3));
292 //------------------------------------------------------------------------------
293 std::string Request::responseMime() const
295 std::string content_type = _responseHeaders.get("content-type");
296 if( content_type.empty() )
297 return "application/octet-stream";
299 return content_type.substr(0, content_type.find(';'));
302 //------------------------------------------------------------------------------
303 void Request::setResponseLength(unsigned int l)
308 //------------------------------------------------------------------------------
309 unsigned int Request::responseLength() const
311 // if the server didn't supply a content length, use the number
312 // of bytes we actually received (so far)
313 if( (_responseLength == 0) && (_receivedBodyBytes > 0) )
314 return _receivedBodyBytes;
316 return _responseLength;
319 //------------------------------------------------------------------------------
320 void Request::setFailure(int code, const std::string& reason)
322 _responseStatus = code;
323 _responseReason = reason;
326 setReadyState(FAILED);
329 //------------------------------------------------------------------------------
330 void Request::setReadyState(ReadyState state)
332 _ready_state = state;
335 // Finish C++ part of request to ensure everything is finished (for example
336 // files and streams are closed) before calling any callback (possibly using
343 else if( state == FAILED )
356 //------------------------------------------------------------------------------
357 void Request::abort()
359 abort("Request aborted.");
362 //----------------------------------------------------------------------------
363 void Request::abort(const std::string& reason)
365 setFailure(-1, reason);
369 //------------------------------------------------------------------------------
370 bool Request::closeAfterComplete() const
372 // for non HTTP/1.1 connections, assume server closes
373 return _willClose || (_responseVersion != HTTP_1_1);
376 //------------------------------------------------------------------------------
377 bool Request::isComplete() const
379 return _ready_state == DONE || _ready_state == FAILED;
382 //------------------------------------------------------------------------------
383 bool Request::hasBodyData() const
385 return !_request_media_type.empty();
388 //------------------------------------------------------------------------------
389 std::string Request::bodyType() const
391 return _request_media_type;
394 //------------------------------------------------------------------------------
395 size_t Request::bodyLength() const
397 return _request_data.length();
400 //------------------------------------------------------------------------------
401 size_t Request::getBodyData(char* s, size_t offset, size_t max_count) const
403 size_t bytes_available = _request_data.size() - offset;
404 size_t bytes_to_read = std::min(bytes_available, max_count);
406 memcpy(s, _request_data.data() + offset, bytes_to_read);
408 return bytes_to_read;
411 } // of namespace HTTP
412 } // of namespace simgear