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:" + r);
139 _responseVersion = decodeHTTPVersion(parts[0]);
140 _responseStatus = strutils::to_int(parts[1]);
141 _responseReason = parts[2];
143 setReadyState(STATUS_RECEIVED);
146 //------------------------------------------------------------------------------
147 void Request::responseHeader(const std::string& key, const std::string& value)
149 if( key == "connection" ) {
150 _willClose = (value.find("close") != std::string::npos);
151 } else if (key == "content-length") {
152 int sz = strutils::to_int(value);
153 setResponseLength(sz);
156 _responseHeaders[key] = value;
159 //------------------------------------------------------------------------------
160 void Request::responseHeadersComplete()
162 setReadyState(HEADERS_RECEIVED);
165 //------------------------------------------------------------------------------
166 void Request::responseComplete()
172 //------------------------------------------------------------------------------
173 void Request::gotBodyData(const char* s, int n)
175 setReadyState(LOADING);
178 //------------------------------------------------------------------------------
179 void Request::onDone()
184 //------------------------------------------------------------------------------
185 void Request::onFail()
191 "request failed:" << url() << " : "
192 << responseCode() << "/" << responseReason()
196 //------------------------------------------------------------------------------
197 void Request::onAlways()
202 //------------------------------------------------------------------------------
203 void Request::processBodyBytes(const char* s, int n)
205 _receivedBodyBytes += n;
209 //------------------------------------------------------------------------------
210 std::string Request::scheme() const
212 int firstColon = url().find(":");
213 if (firstColon > 0) {
214 return url().substr(0, firstColon);
217 return ""; // couldn't parse scheme
220 //------------------------------------------------------------------------------
221 std::string Request::path() const
223 std::string u(url());
224 int schemeEnd = u.find("://");
226 return ""; // couldn't parse scheme
229 int hostEnd = u.find('/', schemeEnd + 3);
231 // couldn't parse host, or URL looks like 'http://foo.com' (no trailing '/')
232 // fixup to root resource path: '/'
236 int query = u.find('?', hostEnd + 1);
238 // all remainder of URL is path
239 return u.substr(hostEnd);
242 return u.substr(hostEnd, query - hostEnd);
245 //------------------------------------------------------------------------------
246 std::string Request::query() const
248 std::string u(url());
249 int query = u.find('?');
251 return ""; //no query string found
254 return u.substr(query); //includes question mark
257 //------------------------------------------------------------------------------
258 std::string Request::host() const
260 std::string hp(hostAndPort());
261 int colonPos = hp.find(':');
263 return hp.substr(0, colonPos); // trim off the colon and port
265 return hp; // no port specifier
269 //------------------------------------------------------------------------------
270 unsigned short Request::port() const
272 std::string hp(hostAndPort());
273 int colonPos = hp.find(':');
275 return (unsigned short) strutils::to_int(hp.substr(colonPos + 1));
277 return DEFAULT_HTTP_PORT;
281 //------------------------------------------------------------------------------
282 std::string Request::hostAndPort() const
284 std::string u(url());
285 int schemeEnd = u.find("://");
287 return ""; // couldn't parse scheme
290 int hostEnd = u.find('/', schemeEnd + 3);
291 if (hostEnd < 0) { // all remainder of URL is host
292 return u.substr(schemeEnd + 3);
295 return u.substr(schemeEnd + 3, hostEnd - (schemeEnd + 3));
298 //------------------------------------------------------------------------------
299 std::string Request::responseMime() const
301 std::string content_type = _responseHeaders.get("content-type");
302 if( content_type.empty() )
303 return "application/octet-stream";
305 return content_type.substr(0, content_type.find(';'));
308 //------------------------------------------------------------------------------
309 void Request::setResponseLength(unsigned int l)
314 //------------------------------------------------------------------------------
315 unsigned int Request::responseLength() const
317 // if the server didn't supply a content length, use the number
318 // of bytes we actually received (so far)
319 if( (_responseLength == 0) && (_receivedBodyBytes > 0) )
320 return _receivedBodyBytes;
322 return _responseLength;
325 //------------------------------------------------------------------------------
326 void Request::setFailure(int code, const std::string& reason)
328 _responseStatus = code;
329 _responseReason = reason;
332 setReadyState(FAILED);
335 //------------------------------------------------------------------------------
336 void Request::setReadyState(ReadyState state)
338 _ready_state = state;
341 // Finish C++ part of request to ensure everything is finished (for example
342 // files and streams are closed) before calling any callback (possibly using
349 else if( state == FAILED )
362 //------------------------------------------------------------------------------
363 void Request::abort()
365 abort("Request aborted.");
368 //----------------------------------------------------------------------------
369 void Request::abort(const std::string& reason)
371 setFailure(-1, reason);
375 //------------------------------------------------------------------------------
376 bool Request::closeAfterComplete() const
378 // for non HTTP/1.1 connections, assume server closes
379 return _willClose || (_responseVersion != HTTP_1_1);
382 //------------------------------------------------------------------------------
383 bool Request::isComplete() const
385 return _ready_state == DONE || _ready_state == FAILED;
388 //------------------------------------------------------------------------------
389 bool Request::hasBodyData() const
391 return !_request_media_type.empty();
394 //------------------------------------------------------------------------------
395 std::string Request::bodyType() const
397 return _request_media_type;
400 //------------------------------------------------------------------------------
401 size_t Request::bodyLength() const
403 return _request_data.length();
406 //------------------------------------------------------------------------------
407 size_t Request::getBodyData(char* s, size_t offset, size_t max_count) const
409 size_t bytes_available = _request_data.size() - offset;
410 size_t bytes_to_read = std::min(bytes_available, max_count);
412 memcpy(s, _request_data.data() + offset, bytes_to_read);
414 return bytes_to_read;
417 } // of namespace HTTP
418 } // of namespace simgear