]> git.mxchange.org Git - simgear.git/blob - simgear/io/HTTPRequest.cxx
Fix VS2010 lack of fminf
[simgear.git] / simgear / io / HTTPRequest.cxx
1 // Copyright (C) 2011  James Turner <zakalawe@mac.com>
2 // Copyright (C) 2013  Thomas Geymayer <tomgey@gmail.com>
3 //
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.
8 //
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.
13 //
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
17
18 #include "HTTPRequest.hxx"
19
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>
25
26 namespace simgear
27 {
28 namespace HTTP
29 {
30
31 extern const int DEFAULT_HTTP_PORT;
32
33 //------------------------------------------------------------------------------
34 Request::Request(const std::string& url, const std::string method):
35   _method(method),
36   _url(url),
37   _responseVersion(HTTP_VERSION_UNKNOWN),
38   _responseStatus(0),
39   _responseLength(0),
40   _receivedBodyBytes(0),
41   _ready_state(UNSENT),
42   _willClose(false)
43 {
44
45 }
46
47 //------------------------------------------------------------------------------
48 Request::~Request()
49 {
50
51 }
52
53 //------------------------------------------------------------------------------
54 Request* Request::done(const Callback& cb)
55 {
56   if( _ready_state == DONE )
57     cb(this);
58   else
59     _cb_done.push_back(cb);
60
61   return this;
62 }
63
64 //------------------------------------------------------------------------------
65 Request* Request::fail(const Callback& cb)
66 {
67   if( _ready_state == FAILED )
68     cb(this);
69   else
70     _cb_fail.push_back(cb);
71
72   return this;
73 }
74
75 //------------------------------------------------------------------------------
76 Request* Request::always(const Callback& cb)
77 {
78   if( isComplete() )
79     cb(this);
80   else
81     _cb_always.push_back(cb);
82
83   return this;
84 }
85
86 //------------------------------------------------------------------------------
87 void Request::setBodyData( const std::string& data,
88                            const std::string& type )
89 {
90   _request_data = data;
91   _request_media_type = type;
92
93   if( !data.empty() && _method == "GET" )
94     _method = "POST";
95 }
96
97 //----------------------------------------------------------------------------
98 void Request::setBodyData(const SGPropertyNode* data)
99 {
100   if( !data )
101     setBodyData("");
102
103   std::stringstream buf;
104   writeProperties(buf, data, true);
105
106   setBodyData(buf.str(), "application/xml");
107 }
108
109 //------------------------------------------------------------------------------
110 void Request::setUrl(const std::string& url)
111 {
112   _url = url;
113 }
114
115 //------------------------------------------------------------------------------
116 void Request::requestStart()
117 {
118   setReadyState(OPENED);
119 }
120
121 //------------------------------------------------------------------------------
122 Request::HTTPVersion decodeHTTPVersion(const std::string& v)
123 {
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;
128 }
129
130 //------------------------------------------------------------------------------
131 void Request::responseStart(const std::string& r)
132 {
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");
137     }
138     
139     _responseVersion = decodeHTTPVersion(parts[0]);
140     _responseStatus = strutils::to_int(parts[1]);
141     _responseReason = parts[2];
142 }
143
144 //------------------------------------------------------------------------------
145 void Request::responseHeader(const std::string& key, const std::string& value)
146 {
147   if( key == "connection" )
148     _willClose = (value.find("close") != std::string::npos);
149
150   _responseHeaders[key] = value;
151 }
152
153 //------------------------------------------------------------------------------
154 void Request::responseHeadersComplete()
155 {
156   setReadyState(HEADERS_RECEIVED);
157 }
158
159 //------------------------------------------------------------------------------
160 void Request::responseComplete()
161 {
162   if( !isComplete() )
163     setReadyState(DONE);
164 }
165
166 //------------------------------------------------------------------------------
167 void Request::gotBodyData(const char* s, int n)
168 {
169   setReadyState(LOADING);
170 }
171
172 //------------------------------------------------------------------------------
173 void Request::onDone()
174 {
175
176 }
177
178 //------------------------------------------------------------------------------
179 void Request::onFail()
180 {
181   SG_LOG
182   (
183     SG_IO,
184     SG_INFO,
185     "request failed:" << url() << " : "
186                       << responseCode() << "/" << responseReason()
187   );
188 }
189
190 //------------------------------------------------------------------------------
191 void Request::onAlways()
192 {
193
194 }
195
196 //------------------------------------------------------------------------------
197 void Request::processBodyBytes(const char* s, int n)
198 {
199   _receivedBodyBytes += n;
200   gotBodyData(s, n);
201 }
202
203 //------------------------------------------------------------------------------
204 std::string Request::scheme() const
205 {
206     int firstColon = url().find(":");
207     if (firstColon > 0) {
208         return url().substr(0, firstColon);
209     }
210     
211     return ""; // couldn't parse scheme
212 }
213
214 //------------------------------------------------------------------------------
215 std::string Request::path() const
216 {
217     std::string u(url());
218     int schemeEnd = u.find("://");
219     if (schemeEnd < 0) {
220         return ""; // couldn't parse scheme
221     }
222     
223     int hostEnd = u.find('/', schemeEnd + 3);
224     if (hostEnd < 0) {
225 // couldn't parse host, or URL looks like 'http://foo.com' (no trailing '/') 
226 // fixup to root resource path: '/' 
227         return "/"; 
228     }
229     
230     int query = u.find('?', hostEnd + 1);
231     if (query < 0) {
232         // all remainder of URL is path
233         return u.substr(hostEnd);
234     }
235     
236     return u.substr(hostEnd, query - hostEnd);
237 }
238
239 //------------------------------------------------------------------------------
240 std::string Request::query() const
241 {
242   std::string u(url());
243   int query = u.find('?');
244   if (query < 0) {
245     return "";  //no query string found
246   }
247   
248   return u.substr(query);   //includes question mark
249 }
250
251 //------------------------------------------------------------------------------
252 std::string Request::host() const
253 {
254   std::string hp(hostAndPort());
255   int colonPos = hp.find(':');
256   if (colonPos >= 0) {
257       return hp.substr(0, colonPos); // trim off the colon and port
258   } else {
259       return hp; // no port specifier
260   }
261 }
262
263 //------------------------------------------------------------------------------
264 unsigned short Request::port() const
265 {
266   std::string hp(hostAndPort());
267   int colonPos = hp.find(':');
268   if (colonPos >= 0) {
269       return (unsigned short) strutils::to_int(hp.substr(colonPos + 1));
270   } else {
271       return DEFAULT_HTTP_PORT;
272   }
273 }
274
275 //------------------------------------------------------------------------------
276 std::string Request::hostAndPort() const
277 {
278   std::string u(url());
279   int schemeEnd = u.find("://");
280   if (schemeEnd < 0) {
281       return ""; // couldn't parse scheme
282   }
283
284   int hostEnd = u.find('/', schemeEnd + 3);
285   if (hostEnd < 0) { // all remainder of URL is host
286       return u.substr(schemeEnd + 3);
287   }
288
289   return u.substr(schemeEnd + 3, hostEnd - (schemeEnd + 3));
290 }
291
292 //------------------------------------------------------------------------------
293 std::string Request::responseMime() const
294 {
295   std::string content_type = _responseHeaders.get("content-type");
296   if( content_type.empty() )
297     return "application/octet-stream";
298
299   return content_type.substr(0, content_type.find(';'));
300 }
301
302 //------------------------------------------------------------------------------
303 void Request::setResponseLength(unsigned int l)
304 {
305   _responseLength = l;
306 }
307
308 //------------------------------------------------------------------------------
309 unsigned int Request::responseLength() const
310 {
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;
315
316   return _responseLength;
317 }
318
319 //------------------------------------------------------------------------------
320 void Request::setFailure(int code, const std::string& reason)
321 {
322   _responseStatus = code;
323   _responseReason = reason;
324
325   if( !isComplete() )
326     setReadyState(FAILED);
327 }
328
329 //------------------------------------------------------------------------------
330 void Request::setReadyState(ReadyState state)
331 {
332   _ready_state = state;
333   if( state == DONE )
334   {
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
337     // such files)
338     onDone();
339     onAlways();
340
341     _cb_done(this);
342   }
343   else if( state == FAILED )
344   {
345     onFail();
346     onAlways();
347
348     _cb_fail(this);
349   }
350   else
351     return;
352
353   _cb_always(this);
354 }
355
356 //------------------------------------------------------------------------------
357 void Request::abort()
358 {
359   abort("Request aborted.");
360 }
361
362 //----------------------------------------------------------------------------
363 void Request::abort(const std::string& reason)
364 {
365   setFailure(-1, reason);
366   _willClose = true;
367 }
368
369 //------------------------------------------------------------------------------
370 bool Request::closeAfterComplete() const
371 {
372   // for non HTTP/1.1 connections, assume server closes
373   return _willClose || (_responseVersion != HTTP_1_1);
374 }
375
376 //------------------------------------------------------------------------------
377 bool Request::isComplete() const
378 {
379   return _ready_state == DONE || _ready_state == FAILED;
380 }
381
382 //------------------------------------------------------------------------------
383 bool Request::hasBodyData() const
384 {
385   return !_request_media_type.empty();
386 }
387
388 //------------------------------------------------------------------------------
389 std::string Request::bodyType() const
390 {
391   return _request_media_type;
392 }
393
394 //------------------------------------------------------------------------------
395 size_t Request::bodyLength() const
396 {
397   return _request_data.length();
398 }
399
400 //------------------------------------------------------------------------------
401 size_t Request::getBodyData(char* s, size_t offset, size_t max_count) const
402 {
403   size_t bytes_available = _request_data.size() - offset;
404   size_t bytes_to_read = std::min(bytes_available, max_count);
405
406   memcpy(s, _request_data.data() + offset, bytes_to_read);
407
408   return bytes_to_read;
409 }
410
411 } // of namespace HTTP
412 } // of namespace simgear