# tcp_http.cpp

Go to the documentation of this file.

    00001 /* $Id$ */
    00002
    00003 /*
    00004  * This file is part of OpenTTD.
    00005  * 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.
    00006  * 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.
    00007  * 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/>.
    00008  */
    00009
    00014 #ifdef ENABLE_NETWORK
    00015
    00016 #include "../../stdafx.h"
    00017 #include "../../debug.h"
    00018 #include "../../rev.h"
    00019 #include "../network_func.h"
    00020
    00021 #include "tcp_http.h"
    00022
    00024 static SmallVector<NetworkHTTPSocketHandler *, 1> _http_connections;
    00025
    00035 NetworkHTTPSocketHandler::NetworkHTTPSocketHandler(SOCKET s,
    00036     HTTPCallback *callback, const char *host, const char *url,
    00037     const char *data, int depth) :
    00038   NetworkSocketHandler(),
    00039   recv_pos(0),
    00040   recv_length(0),
    00041   callback(callback),
    00042   data(data),
    00043   redirect_depth(depth),
    00044   sock(s)
    00045 {
    00046   size_t bufferSize = strlen(url) + strlen(host) + strlen(_openttd_revision) + (data == NULL ? 0 : strlen(data)) + 128;
    00047   char *buffer = AllocaM(char, bufferSize);
    00048
    00049   DEBUG(net, 7, "[tcp/http] requesting %s%s", host, url);
    00050   if (data != NULL) {
    00051     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, _openttd_revision, (int)strlen(data), data);
    00052   } else {
    00053     seprintf(buffer, buffer + bufferSize - 1, "GET %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: OpenTTD/%s\r\n\r\n", url, host, _openttd_revision);
    00054   }
    00055
    00056   ssize_t size = strlen(buffer);
    00057   ssize_t res = send(this->sock, (const char*)buffer, size, 0);
    00058   if (res != size) {
    00059     /* Sending all data failed. Socket can't handle this little bit
    00060      * of information? Just fall back to the old system! */
    00061     this->callback->OnFailure();
    00062     delete this;
    00063     return;
    00064   }
    00065
    00066   *_http_connections.Append() = this;
    00067 }
    00068
    00070 NetworkHTTPSocketHandler::~NetworkHTTPSocketHandler()
    00071 {
    00072   this->CloseConnection();
    00073
    00074   if (this->sock != INVALID_SOCKET) closesocket(this->sock);
    00075   this->sock = INVALID_SOCKET;
    00076   free(this->data);
    00077 }
    00078
    00079 NetworkRecvStatus NetworkHTTPSocketHandler::CloseConnection(bool error)
    00080 {
    00081   NetworkSocketHandler::CloseConnection(error);
    00082   return NETWORK_RECV_STATUS_OKAY;
    00083 }
    00084
    00089 #define return_error(msg) { DEBUG(net, 0, msg); return -1; }
    00090
    00091 static const char * const NEWLINE        = "\r\n";
    00092 static const char * const END_OF_HEADER  = "\r\n\r\n";
    00093 static const char * const HTTP_1_0       = "HTTP/1.0 ";
    00094 static const char * const HTTP_1_1       = "HTTP/1.1 ";
    00095 static const char * const CONTENT_LENGTH = "Content-Length: ";
    00096 static const char * const LOCATION       = "Location: ";
    00097
    00108 int NetworkHTTPSocketHandler::HandleHeader()
    00109 {
    00110   assert(strlen(HTTP_1_0) == strlen(HTTP_1_1));
    00111   assert(strstr(this->recv_buffer, END_OF_HEADER) != NULL);
    00112
    00113   /* We expect a HTTP/1.[01] reply */
    00114   if (strncmp(this->recv_buffer, HTTP_1_0, strlen(HTTP_1_0)) != 0 &&
    00115       strncmp(this->recv_buffer, HTTP_1_1, strlen(HTTP_1_1)) != 0) {
    00116     return_error("[tcp/http] received invalid HTTP reply");
    00117   }
    00118
    00119   char *status = this->recv_buffer + strlen(HTTP_1_0);
    00120   if (strncmp(status, "200", 3) == 0) {
    00121     /* We are going to receive a document. */
    00122
    00123     /* Get the length of the document to receive */
    00124     char *length = strcasestr(this->recv_buffer, CONTENT_LENGTH);
    00125     if (length == NULL) return_error("[tcp/http] missing 'content-length' header");
    00126
    00127     /* Skip the header */
    00128     length += strlen(CONTENT_LENGTH);
    00129
    00130     /* Search the end of the line. This is safe because the header will
    00131      * always end with two newlines. */
    00132     char *end_of_line = strstr(length, NEWLINE);
    00133
    00134     /* Read the length */
    00135     *end_of_line = '\0';
    00136     int len = atoi(length);
    00137     /* Restore the header. */
    00138     *end_of_line = '\r';
    00139
    00140     /* Make sure we're going to download at least something;
    00141      * zero sized files are, for OpenTTD's purposes, always
    00142      * wrong. You can't have gzips of 0 bytes! */
    00143     if (len == 0) return_error("[tcp/http] refusing to download 0 bytes");
    00144
    00145     DEBUG(net, 7, "[tcp/http] downloading %i bytes", len);
    00146     return len;
    00147   }
    00148
    00149   if (strncmp(status, "301", 3) != 0 &&
    00150       strncmp(status, "302", 3) != 0 &&
    00151       strncmp(status, "303", 3) != 0 &&
    00152       strncmp(status, "307", 3) != 0) {
    00153     /* We are not going to be redirected :(. */
    00154
    00155     /* Search the end of the line. This is safe because the header will
    00156      * always end with two newlines. */
    00157     *strstr(status, NEWLINE) = '\0';
    00158     DEBUG(net, 0, "[tcp/http] unhandled status reply %s", status);
    00159     return -1;
    00160   }
    00161
    00162   if (this->redirect_depth == 5) return_error("[tcp/http] too many redirects, looping redirects?");
    00163
    00164   /* Redirect to other URL */
    00165   char *uri = strcasestr(this->recv_buffer, LOCATION);
    00166   if (uri == NULL) return_error("[tcp/http] missing 'location' header for redirect");
    00167
    00168   uri += strlen(LOCATION);
    00169
    00170   /* Search the end of the line. This is safe because the header will
    00171    * always end with two newlines. */
    00172   char *end_of_line = strstr(uri, NEWLINE);
    00173   *end_of_line = '\0';
    00174
    00175   DEBUG(net, 6, "[tcp/http] redirecting to %s", uri);
    00176
    00177   int ret = NetworkHTTPSocketHandler::Connect(uri, this->callback, this->data, this->redirect_depth + 1);
    00178   if (ret != 0) return ret;
    00179
    00180   /* We've relinquished control of data now. */
    00181   this->data = NULL;
    00182
    00183   /* Restore the header. */
    00184   *end_of_line = '\r';
    00185   return 0;
    00186 }
    00187
    00195 /* static */ int NetworkHTTPSocketHandler::Connect(char *uri, HTTPCallback *callback, const char *data, int depth)
    00196 {
    00197   char *hname = strstr(uri, "://");
    00198   if (hname == NULL) return_error("[tcp/http] invalid location");
    00199
    00200   hname += 3;
    00201
    00202   char *url = strchr(hname, '/');
    00203   if (url == NULL) return_error("[tcp/http] invalid location");
    00204
    00205   *url = '\0';
    00206
    00207   /* Fetch the hostname, and possible port number. */
    00208   const char *company = NULL;
    00209   const char *port = NULL;
    00210   ParseConnectionString(&company, &port, hname);
    00211   if (company != NULL) return_error("[tcp/http] invalid hostname");
    00212
    00213   NetworkAddress address(hname, port == NULL ? 80 : atoi(port));
    00214
    00215   /* Restore the URL. */
    00216   *url = '/';
    00217   new NetworkHTTPContentConnecter(address, callback, url, data, depth);
    00218   return 0;
    00219 }
    00220
    00221 #undef return_error
    00222
    00230 int NetworkHTTPSocketHandler::Receive()
    00231 {
    00232   for (;;) {
    00233     ssize_t res = recv(this->sock, (char *)this->recv_buffer + this->recv_pos, lengthof(this->recv_buffer) - this->recv_pos, 0);
    00234     if (res == -1) {
    00235       int err = GET_LAST_ERROR();
    00236       if (err != EWOULDBLOCK) {
    00237         /* Something went wrong... (104 is connection reset by peer) */
    00238         if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
    00239         return -1;
    00240       }
    00241       /* Connection would block, so stop for now */
    00242       return 1;
    00243     }
    00244
    00245     /* No more data... did we get everything we wanted? */
    00246     if (res == 0) {
    00247       if (this->recv_length != 0) return -1;
    00248
    00249       this->callback->OnReceiveData(NULL, 0);
    00250       return 0;
    00251     }
    00252
    00253     /* Wait till we read the end-of-header identifier */
    00254     if (this->recv_length == 0) {
    00255       int read = this->recv_pos + res;
    00256       int end = min(read, lengthof(this->recv_buffer) - 1);
    00257
    00258       /* Do a 'safe' search for the end of the header. */
    00259       char prev = this->recv_buffer[end];
    00260       this->recv_buffer[end] = '\0';
    00261       char *end_of_header = strstr(this->recv_buffer, END_OF_HEADER);
    00262       this->recv_buffer[end] = prev;
    00263
    00264       if (end_of_header == NULL) {
    00265         if (read == lengthof(this->recv_buffer)) {
    00266           DEBUG(net, 0, "[tcp/http] header too big");
    00267           return -1;
    00268         }
    00269         this->recv_pos = read;
    00270       } else {
    00271         int ret = this->HandleHeader();
    00272         if (ret <= 0) return ret;
    00273
    00274         this->recv_length = ret;
    00275
    00276         end_of_header += strlen(END_OF_HEADER);
    00277         int len = min(read - (end_of_header - this->recv_buffer), res);
    00278         if (len != 0) {
    00279           this->callback->OnReceiveData(end_of_header, len);
    00280           this->recv_length -= len;
    00281         }
    00282
    00283         this->recv_pos = 0;
    00284       }
    00285     } else {
    00286       res = min(this->recv_length, res);
    00287       /* Receive whatever we're expecting. */
    00288       this->callback->OnReceiveData(this->recv_buffer, res);
    00289       this->recv_length -= res;
    00290     }
    00291   }
    00292 }
    00293
    00297 /* static */ void NetworkHTTPSocketHandler::HTTPReceive()
    00298 {
    00299   /* No connections, just bail out. */
    00300   if (_http_connections.Length() == 0) return;
    00301
    00302   fd_set read_fd;
    00303   struct timeval tv;
    00304
    00305   FD_ZERO(&read_fd);
    00306   for (NetworkHTTPSocketHandler **iter = _http_connections.Begin(); iter < _http_connections.End(); iter++) {
    00307     FD_SET((*iter)->sock, &read_fd);
    00308   }
    00309
    00310   tv.tv_sec = tv.tv_usec = 0; // don't block at all.
    00311 #if !defined(__MORPHOS__) && !defined(__AMIGA__)
    00312   int n = select(FD_SETSIZE, &read_fd, NULL, NULL, &tv);
    00313 #else
    00314   int n = WaitSelect(FD_SETSIZE, &read_fd, NULL, NULL, &tv, NULL);
    00315 #endif
    00316   if (n == -1) return;
    00317
    00318   for (NetworkHTTPSocketHandler **iter = _http_connections.Begin(); iter < _http_connections.End(); /* nothing */) {
    00319     NetworkHTTPSocketHandler *cur = *iter;
    00320
    00321     if (FD_ISSET(cur->sock, &read_fd)) {
    00322       int ret = cur->Receive();
    00323       /* First send the failure. */
    00324       if (ret < 0) cur->callback->OnFailure();
    00325       if (ret <= 0) {
    00326         /* Then... the connection can be closed */
    00327         cur->CloseConnection();
    00328         _http_connections.Erase(iter);
    00329         delete cur;
    00330         continue;
    00331       }
    00332     }
    00333     iter++;
    00334   }
    00335 }
    00336
    00337 #endif /* ENABLE_NETWORK */