OpenTTD Source  1.11.2
tcp_http.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
12 #include "../../stdafx.h"
13 #include "../../debug.h"
14 #include "../../rev.h"
15 #include "../network_func.h"
16 #include "game_info.h"
17 
18 #include "tcp_http.h"
19 
20 #include "../../safeguards.h"
21 
23 static std::vector<NetworkHTTPSocketHandler *> _http_connections;
24 
35  HTTPCallback *callback, const char *host, const char *url,
36  const char *data, int depth) :
38  recv_pos(0),
39  recv_length(0),
40  callback(callback),
41  data(data),
42  redirect_depth(depth),
43  sock(s)
44 {
45  size_t bufferSize = strlen(url) + strlen(host) + strlen(GetNetworkRevisionString()) + (data == nullptr ? 0 : strlen(data)) + 128;
46  char *buffer = AllocaM(char, bufferSize);
47 
48  DEBUG(net, 7, "[tcp/http] requesting %s%s", host, url);
49  if (data != nullptr) {
50  seprintf(buffer, buffer + bufferSize - 1, "POST %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: OpenTTD/%s\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s\r\n", url, host, GetNetworkRevisionString(), (int)strlen(data), data);
51  } else {
52  seprintf(buffer, buffer + bufferSize - 1, "GET %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: OpenTTD/%s\r\n\r\n", url, host, GetNetworkRevisionString());
53  }
54 
55  ssize_t size = strlen(buffer);
56  ssize_t res = send(this->sock, (const char*)buffer, size, 0);
57  if (res != size) {
58  /* Sending all data failed. Socket can't handle this little bit
59  * of information? Just fall back to the old system! */
60  this->callback->OnFailure();
61  delete this;
62  return;
63  }
64 
65  _http_connections.push_back(this);
66 }
67 
70 {
71  this->CloseConnection();
72 
73  if (this->sock != INVALID_SOCKET) closesocket(this->sock);
74  this->sock = INVALID_SOCKET;
75  free(this->data);
76 }
77 
79 {
82 }
83 
88 #define return_error(msg) { DEBUG(net, 0, msg); return -1; }
89 
90 static const char * const NEWLINE = "\r\n";
91 static const char * const END_OF_HEADER = "\r\n\r\n";
92 static const char * const HTTP_1_0 = "HTTP/1.0 ";
93 static const char * const HTTP_1_1 = "HTTP/1.1 ";
94 static const char * const CONTENT_LENGTH = "Content-Length: ";
95 static const char * const LOCATION = "Location: ";
96 
108 {
109  assert(strlen(HTTP_1_0) == strlen(HTTP_1_1));
110  assert(strstr(this->recv_buffer, END_OF_HEADER) != nullptr);
111 
112  /* We expect a HTTP/1.[01] reply */
113  if (strncmp(this->recv_buffer, HTTP_1_0, strlen(HTTP_1_0)) != 0 &&
114  strncmp(this->recv_buffer, HTTP_1_1, strlen(HTTP_1_1)) != 0) {
115  return_error("[tcp/http] received invalid HTTP reply");
116  }
117 
118  char *status = this->recv_buffer + strlen(HTTP_1_0);
119  if (strncmp(status, "200", 3) == 0) {
120  /* We are going to receive a document. */
121 
122  /* Get the length of the document to receive */
123  char *length = strcasestr(this->recv_buffer, CONTENT_LENGTH);
124  if (length == nullptr) return_error("[tcp/http] missing 'content-length' header");
125 
126  /* Skip the header */
127  length += strlen(CONTENT_LENGTH);
128 
129  /* Search the end of the line. This is safe because the header will
130  * always end with two newlines. */
131  char *end_of_line = strstr(length, NEWLINE);
132 
133  /* Read the length */
134  *end_of_line = '\0';
135  int len = atoi(length);
136  /* Restore the header. */
137  *end_of_line = '\r';
138 
139  /* Make sure we're going to download at least something;
140  * zero sized files are, for OpenTTD's purposes, always
141  * wrong. You can't have gzips of 0 bytes! */
142  if (len == 0) return_error("[tcp/http] refusing to download 0 bytes");
143 
144  DEBUG(net, 7, "[tcp/http] downloading %i bytes", len);
145  return len;
146  }
147 
148  if (strncmp(status, "301", 3) != 0 &&
149  strncmp(status, "302", 3) != 0 &&
150  strncmp(status, "303", 3) != 0 &&
151  strncmp(status, "307", 3) != 0) {
152  /* We are not going to be redirected :(. */
153 
154  /* Search the end of the line. This is safe because the header will
155  * always end with two newlines. */
156  *strstr(status, NEWLINE) = '\0';
157  DEBUG(net, 0, "[tcp/http] unhandled status reply %s", status);
158  return -1;
159  }
160 
161  if (this->redirect_depth == 5) return_error("[tcp/http] too many redirects, looping redirects?");
162 
163  /* Redirect to other URL */
164  char *uri = strcasestr(this->recv_buffer, LOCATION);
165  if (uri == nullptr) return_error("[tcp/http] missing 'location' header for redirect");
166 
167  uri += strlen(LOCATION);
168 
169  /* Search the end of the line. This is safe because the header will
170  * always end with two newlines. */
171  char *end_of_line = strstr(uri, NEWLINE);
172  *end_of_line = '\0';
173 
174  DEBUG(net, 6, "[tcp/http] redirecting to %s", uri);
175 
176  int ret = NetworkHTTPSocketHandler::Connect(uri, this->callback, this->data, this->redirect_depth + 1);
177  if (ret != 0) return ret;
178 
179  /* We've relinquished control of data now. */
180  this->data = nullptr;
181 
182  /* Restore the header. */
183  *end_of_line = '\r';
184  return 0;
185 }
186 
194 /* static */ int NetworkHTTPSocketHandler::Connect(char *uri, HTTPCallback *callback, const char *data, int depth)
195 {
196  char *hname = strstr(uri, "://");
197  if (hname == nullptr) return_error("[tcp/http] invalid location");
198 
199  hname += 3;
200 
201  char *url = strchr(hname, '/');
202  if (url == nullptr) return_error("[tcp/http] invalid location");
203 
204  *url = '\0';
205 
206  /* Fetch the hostname, and possible port number. */
207  const char *company = nullptr;
208  const char *port = nullptr;
209  ParseConnectionString(&company, &port, hname);
210  if (company != nullptr) return_error("[tcp/http] invalid hostname");
211 
212  NetworkAddress address(hname, port == nullptr ? 80 : atoi(port));
213 
214  /* Restore the URL. */
215  *url = '/';
216  new NetworkHTTPContentConnecter(address, callback, url, data, depth);
217  return 0;
218 }
219 
220 #undef return_error
221 
230 {
231  for (;;) {
232  ssize_t res = recv(this->sock, (char *)this->recv_buffer + this->recv_pos, lengthof(this->recv_buffer) - this->recv_pos, 0);
233  if (res == -1) {
235  if (!err.WouldBlock()) {
236  /* Something went wrong... */
237  if (!err.IsConnectionReset()) DEBUG(net, 0, "recv failed with error %s", err.AsString());
238  return -1;
239  }
240  /* Connection would block, so stop for now */
241  return 1;
242  }
243 
244  /* No more data... did we get everything we wanted? */
245  if (res == 0) {
246  if (this->recv_length != 0) return -1;
247 
248  this->callback->OnReceiveData(nullptr, 0);
249  return 0;
250  }
251 
252  /* Wait till we read the end-of-header identifier */
253  if (this->recv_length == 0) {
254  ssize_t read = this->recv_pos + res;
255  ssize_t end = std::min<ssize_t>(read, lengthof(this->recv_buffer) - 1);
256 
257  /* Do a 'safe' search for the end of the header. */
258  char prev = this->recv_buffer[end];
259  this->recv_buffer[end] = '\0';
260  char *end_of_header = strstr(this->recv_buffer, END_OF_HEADER);
261  this->recv_buffer[end] = prev;
262 
263  if (end_of_header == nullptr) {
264  if (read == lengthof(this->recv_buffer)) {
265  DEBUG(net, 0, "[tcp/http] header too big");
266  return -1;
267  }
268  this->recv_pos = read;
269  } else {
270  int ret = this->HandleHeader();
271  if (ret <= 0) return ret;
272 
273  this->recv_length = ret;
274 
275  end_of_header += strlen(END_OF_HEADER);
276  int len = std::min(read - (end_of_header - this->recv_buffer), res);
277  if (len != 0) {
278  this->callback->OnReceiveData(end_of_header, len);
279  this->recv_length -= len;
280  }
281 
282  this->recv_pos = 0;
283  }
284  } else {
285  res = std::min<ssize_t>(this->recv_length, res);
286  /* Receive whatever we're expecting. */
287  this->callback->OnReceiveData(this->recv_buffer, res);
288  this->recv_length -= res;
289  }
290  }
291 }
292 
297 {
298  /* No connections, just bail out. */
299  if (_http_connections.size() == 0) return;
300 
301  fd_set read_fd;
302  struct timeval tv;
303 
304  FD_ZERO(&read_fd);
306  FD_SET(handler->sock, &read_fd);
307  }
308 
309  tv.tv_sec = tv.tv_usec = 0; // don't block at all.
310  int n = select(FD_SETSIZE, &read_fd, nullptr, nullptr, &tv);
311  if (n == -1) return;
312 
313  for (auto iter = _http_connections.begin(); iter < _http_connections.end(); /* nothing */) {
314  NetworkHTTPSocketHandler *cur = *iter;
315 
316  if (FD_ISSET(cur->sock, &read_fd)) {
317  int ret = cur->Receive();
318  /* First send the failure. */
319  if (ret < 0) cur->callback->OnFailure();
320  if (ret <= 0) {
321  /* Then... the connection can be closed */
322  cur->CloseConnection();
323  iter = _http_connections.erase(iter);
324  delete cur;
325  continue;
326  }
327  }
328  iter++;
329  }
330 }
END_OF_HEADER
static const char *const END_OF_HEADER
End of header marker.
Definition: tcp_http.cpp:91
NetworkHTTPSocketHandler
Base socket handler for HTTP traffic.
Definition: tcp_http.h:38
NetworkHTTPSocketHandler::callback
HTTPCallback * callback
The callback to call for the incoming data.
Definition: tcp_http.h:43
HTTPCallback
Callback for when the HTTP handler has something to tell us.
Definition: tcp_http.h:18
tcp_http.h
NetworkSocketHandler
SocketHandler for all network sockets in OpenTTD.
Definition: core.h:41
NetworkHTTPSocketHandler::data
const char * data
The (POST) data we might want to forward (to a redirect).
Definition: tcp_http.h:44
HTTPCallback::OnReceiveData
virtual void OnReceiveData(const char *data, size_t length)=0
We're receiving data.
NetworkSocketHandler::CloseConnection
virtual NetworkRecvStatus CloseConnection(bool error=true)
Close the current connection; for TCP this will be mostly equivalent to Close(), but for UDP it just ...
Definition: core.h:59
LOCATION
static const char *const LOCATION
Header for location.
Definition: tcp_http.cpp:95
NetworkHTTPSocketHandler::~NetworkHTTPSocketHandler
~NetworkHTTPSocketHandler()
Free whatever needs to be freed.
Definition: tcp_http.cpp:69
NetworkHTTPContentConnecter
Connect with a HTTP server and do ONE query.
Definition: tcp_http.h:75
NetworkHTTPSocketHandler::redirect_depth
int redirect_depth
The depth of the redirection.
Definition: tcp_http.h:45
NetworkHTTPSocketHandler::recv_pos
int recv_pos
Current position in buffer.
Definition: tcp_http.h:41
DEBUG
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:35
NetworkHTTPSocketHandler::recv_buffer
char recv_buffer[4096]
Partially received message.
Definition: tcp_http.h:40
HTTP_1_1
static const char *const HTTP_1_1
Preamble for HTTP 1.1 servers.
Definition: tcp_http.cpp:93
NetworkError::WouldBlock
bool WouldBlock() const
Check whether this error describes that the operation would block.
Definition: os_abstraction.cpp:38
NetworkError::GetLast
static NetworkError GetLast()
Get the last network error.
Definition: os_abstraction.cpp:116
ParseConnectionString
void ParseConnectionString(const char **company, const char **port, char *connection_string)
Converts a string to ip/port/company Format: IP:port::company.
Definition: network.cpp:459
_http_connections
static std::vector< NetworkHTTPSocketHandler * > _http_connections
List of open HTTP connections.
Definition: tcp_http.cpp:23
HTTPCallback::OnFailure
virtual void OnFailure()=0
An error has occurred and the connection has been closed.
NetworkHTTPSocketHandler::CloseConnection
NetworkRecvStatus CloseConnection(bool error=true) override
Close the current connection; for TCP this will be mostly equivalent to Close(), but for UDP it just ...
Definition: tcp_http.cpp:78
NetworkHTTPSocketHandler::Connect
static int Connect(char *uri, HTTPCallback *callback, const char *data=nullptr, int depth=0)
Connect to the given URI.
Definition: tcp_http.cpp:194
NetworkHTTPSocketHandler::Receive
int Receive()
Handle receiving of HTTP data.
Definition: tcp_http.cpp:229
NetworkAddress
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
Definition: address.h:29
NetworkRecvStatus
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
Definition: core.h:22
NetworkHTTPSocketHandler::NetworkHTTPSocketHandler
NetworkHTTPSocketHandler(SOCKET sock, HTTPCallback *callback, const char *host, const char *url, const char *data, int depth)
Start the querying.
Definition: tcp_http.cpp:34
HTTP_1_0
static const char *const HTTP_1_0
Preamble for HTTP 1.0 servers.
Definition: tcp_http.cpp:92
NetworkHTTPSocketHandler::HTTPReceive
static void HTTPReceive()
Do the receiving for all HTTP connections.
Definition: tcp_http.cpp:296
NetworkError::IsConnectionReset
bool IsConnectionReset() const
Check whether this error describes a connection reset.
Definition: os_abstraction.cpp:53
seprintf
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:460
game_info.h
NetworkError
Abstraction of a network error where all implementation details of the error codes are encapsulated i...
Definition: os_abstraction.h:23
GetNetworkRevisionString
const char * GetNetworkRevisionString()
Get the network version string used by this build.
Definition: game_info.cpp:41
return_error
#define return_error(msg)
Helper to simplify the error handling.
Definition: tcp_http.cpp:88
NEWLINE
static const char *const NEWLINE
End of line marker.
Definition: tcp_http.cpp:90
error
void CDECL error(const char *s,...)
Error handling for fatal non-user errors.
Definition: openttd.cpp:132
NetworkHTTPSocketHandler::recv_length
int recv_length
Length of the data still retrieving.
Definition: tcp_http.h:42
lengthof
#define lengthof(x)
Return the length of an fixed size array.
Definition: stdafx.h:369
NETWORK_RECV_STATUS_OKAY
@ NETWORK_RECV_STATUS_OKAY
Everything is okay.
Definition: core.h:23
free
static void free(const void *ptr)
Version of the standard free that accepts const pointers.
Definition: stdafx.h:456
NetworkError::AsString
const char * AsString() const
Get the string representation of the error message.
Definition: os_abstraction.cpp:79
CONTENT_LENGTH
static const char *const CONTENT_LENGTH
Header for the length of the content.
Definition: tcp_http.cpp:94
NetworkHTTPSocketHandler::sock
SOCKET sock
The socket currently connected to.
Definition: tcp_http.h:50
AllocaM
#define AllocaM(T, num_elements)
alloca() has to be called in the parent function, so define AllocaM() as a macro
Definition: alloc_func.hpp:132
NetworkHTTPSocketHandler::HandleHeader
int HandleHeader()
Handle the header of a HTTP reply.
Definition: tcp_http.cpp:107