summaryrefslogtreecommitdiff
path: root/src/SFML/Network/Http.cpp
blob: 4a9502fceea87a1cec155a399f56d1b7c1a747bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2009 Laurent Gomila (laurent.gom@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Network/Http.hpp>
#include <ctype.h>
#include <algorithm>
#include <iterator>
#include <sstream>


namespace
{
    ////////////////////////////////////////////////////////////
    // Convenience function to convert a string to lower case
    ////////////////////////////////////////////////////////////
    std::string ToLower(const std::string& Str)
    {
        std::string Ret = Str;
        for (std::string::iterator i = Ret.begin(); i != Ret.end(); ++i)
            *i = static_cast<char>(tolower(*i));

        return Ret;
    }
}


namespace sf
{
////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
Http::Request::Request(Method RequestMethod, const std::string& URI, const std::string& Body)
{
    SetMethod(RequestMethod);
    SetURI(URI);
    SetHttpVersion(1, 0);
    SetBody(Body);
}


////////////////////////////////////////////////////////////
/// Set the value of a field; the field is added if it doesn't exist
////////////////////////////////////////////////////////////
void Http::Request::SetField(const std::string& Field, const std::string& Value)
{
    myFields[ToLower(Field)] = Value;
}


////////////////////////////////////////////////////////////
/// Set the request method.
/// This parameter is Get by default
////////////////////////////////////////////////////////////
void Http::Request::SetMethod(Http::Request::Method RequestMethod)
{
    myMethod = RequestMethod;
}


////////////////////////////////////////////////////////////
/// Set the target URI of the request.
/// This parameter is "/" by default
////////////////////////////////////////////////////////////
void Http::Request::SetURI(const std::string& URI)
{
    myURI = URI;

    // Make sure it starts with a '/'
    if (myURI.empty() || (myURI[0] != '/'))
        myURI.insert(0, "/");
}


////////////////////////////////////////////////////////////
/// Set the HTTP version of the request.
/// This parameter is 1.0 by default
////////////////////////////////////////////////////////////
void Http::Request::SetHttpVersion(unsigned int Major, unsigned int Minor)
{
    myMajorVersion = Major;
    myMinorVersion = Minor;
}


////////////////////////////////////////////////////////////
/// Set the body of the request. This parameter is optional and
/// makes sense only for POST requests.
/// This parameter is empty by default
////////////////////////////////////////////////////////////
void Http::Request::SetBody(const std::string& Body)
{
    myBody = Body;
}


////////////////////////////////////////////////////////////
/// Get the string representation of a request header
////////////////////////////////////////////////////////////
std::string Http::Request::ToString() const
{
    std::ostringstream Out;

    // Convert the method to its string representation
    std::string RequestMethod;
    switch (myMethod)
    {
        default :
        case Get :  RequestMethod = "GET";  break;
        case Post : RequestMethod = "POST"; break;
        case Head : RequestMethod = "HEAD"; break;
    }

    // Write the first line containing the request type
    Out << RequestMethod << " " << myURI << " ";
    Out << "HTTP/" << myMajorVersion << "." << myMinorVersion << "\r\n";

    // Write fields
    for (FieldTable::const_iterator i = myFields.begin(); i != myFields.end(); ++i)
    {
        Out << i->first << ": " << i->second << "\r\n";
    }

    // Use an extra \r\n to separate the header from the body
    Out << "\r\n";

    // Add the body
    Out << myBody;

    return Out.str();
}


////////////////////////////////////////////////////////////
/// Check if the given field has been defined
////////////////////////////////////////////////////////////
bool Http::Request::HasField(const std::string& Field) const
{
    return myFields.find(Field) != myFields.end();
}


////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
Http::Response::Response() :
myStatus      (ConnectionFailed),
myMajorVersion(0),
myMinorVersion(0)
{

}


////////////////////////////////////////////////////////////
/// Get the value of a field
////////////////////////////////////////////////////////////
const std::string& Http::Response::GetField(const std::string& Field) const
{
    FieldTable::const_iterator It = myFields.find(ToLower(Field));
    if (It != myFields.end())
    {
        return It->second;
    }
    else
    {
        static const std::string Empty = "";
        return Empty;
    }
}


////////////////////////////////////////////////////////////
/// Get the header's status code
////////////////////////////////////////////////////////////
Http::Response::Status Http::Response::GetStatus() const
{
    return myStatus;
}


////////////////////////////////////////////////////////////
/// Get the major HTTP version number of the response
////////////////////////////////////////////////////////////
unsigned int Http::Response::GetMajorHttpVersion() const
{
    return myMajorVersion;
}


////////////////////////////////////////////////////////////
/// Get the major HTTP version number of the response
////////////////////////////////////////////////////////////
unsigned int Http::Response::GetMinorHttpVersion() const
{
    return myMinorVersion;
}


////////////////////////////////////////////////////////////
/// Get the body of the response. The body can contain :
/// - the requested page (for GET requests)
/// - a response from the server (for POST requests)
/// - nothing (for HEAD requests)
/// - an error message (in case of an error)
////////////////////////////////////////////////////////////
const std::string& Http::Response::GetBody() const
{
    return myBody;
}


////////////////////////////////////////////////////////////
/// Construct the header from a response string
////////////////////////////////////////////////////////////
void Http::Response::FromString(const std::string& Data)
{
    std::istringstream In(Data);

    // Extract the HTTP version from the first line
    std::string Version;
    if (In >> Version)
    {
        if ((Version.size() >= 8) && (Version[6] == '.') &&
            (ToLower(Version.substr(0, 5)) == "http/")   &&
             isdigit(Version[5]) && isdigit(Version[7]))
        {
            myMajorVersion = Version[5] - '0';
            myMinorVersion = Version[7] - '0';
        }
        else
        {
            // Invalid HTTP version
            myStatus = InvalidResponse;
            return;
        }
    }

    // Extract the status code from the first line
    int StatusCode;
    if (In >> StatusCode)
    {
        myStatus = static_cast<Status>(StatusCode);
    }
    else
    {
        // Invalid status code
        myStatus = InvalidResponse;
        return;
    }

    // Ignore the end of the first line
    In.ignore(10000, '\n');

    // Parse the other lines, which contain fields, one by one
    std::string Line;
    while (std::getline(In, Line) && (Line.size() > 2))
    {
        std::string::size_type Pos = Line.find(": ");
        if (Pos != std::string::npos)
        {
            // Extract the field name and its value
            std::string Field = Line.substr(0, Pos);
            std::string Value = Line.substr(Pos + 2);

            // Remove any trailing \r
            if (!Value.empty() && (*Value.rbegin() == '\r'))
                Value.erase(Value.size() - 1);

            // Add the field
            myFields[ToLower(Field)] = Value;
        }
    }

    // Finally extract the body
    myBody.clear();
    std::copy(std::istreambuf_iterator<char>(In), std::istreambuf_iterator<char>(), std::back_inserter(myBody));
}


////////////////////////////////////////////////////////////
/// Default constructor
////////////////////////////////////////////////////////////
Http::Http() :
myHost(),
myPort(0)
{

}


////////////////////////////////////////////////////////////
/// Construct the Http instance with the target host
////////////////////////////////////////////////////////////
Http::Http(const std::string& Host, unsigned short Port)
{
    SetHost(Host, Port);
}


////////////////////////////////////////////////////////////
/// Set the target host
////////////////////////////////////////////////////////////
void Http::SetHost(const std::string& Host, unsigned short Port)
{
    // Detect the protocol used
    std::string Protocol = ToLower(Host.substr(0, 8));
    if (Protocol.substr(0, 7) == "http://")
    {
        // HTTP protocol
        myHostName = Host.substr(7);
        myPort     = (Port != 0 ? Port : 80);
    }
    else if (Protocol == "https://")
    {
        // HTTPS protocol
        myHostName = Host.substr(8);
        myPort     = (Port != 0 ? Port : 443);
    }
    else
    {
        // Undefined protocol - use HTTP
        myHostName = Host;
        myPort     = (Port != 0 ? Port : 80);
    }

    // Remove any trailing '/' from the host name
    if (!myHostName.empty() && (*myHostName.rbegin() == '/'))
        myHostName.erase(myHostName.size() - 1);

    myHost = sf::IPAddress(myHostName);
}


////////////////////////////////////////////////////////////
/// Send a HTTP request and return the server's response.
/// You must be connected to a host before sending requests.
/// Any missing mandatory header field will be added with an appropriate value.
/// Warning : this function waits for the server's response and may
/// not return instantly; use a thread if you don't want to block your
/// application.
////////////////////////////////////////////////////////////
Http::Response Http::SendRequest(const Http::Request& Req, float Timeout)
{
    // First make sure the request is valid -- add missing mandatory fields
    Request ToSend(Req);
    if (!ToSend.HasField("From"))
    {
        ToSend.SetField("From", "user@sfml-dev.org");
    }
    if (!ToSend.HasField("User-Agent"))
    {
        ToSend.SetField("User-Agent", "libsfml-network/1.x");
    }
    if (!ToSend.HasField("Host"))
    {
        ToSend.SetField("Host", myHostName);
    }
    if (!ToSend.HasField("Content-Length"))
    {
        std::ostringstream Out;
        Out << ToSend.myBody.size();
        ToSend.SetField("Content-Length", Out.str());
    }
    if ((ToSend.myMethod == Request::Post) && !ToSend.HasField("Content-Type"))
    {
        ToSend.SetField("Content-Type", "application/x-www-form-urlencoded");
    }
    if ((ToSend.myMajorVersion * 10 + ToSend.myMinorVersion >= 11) && !ToSend.HasField("Connection"))
    {
        ToSend.SetField("Connection", "close");
    }

    // Prepare the response
    Response Received;

    // Connect the socket to the host
    if (myConnection.Connect(myPort, myHost, Timeout) == Socket::Done)
    {
        // Convert the request to string and send it through the connected socket
        std::string RequestStr = ToSend.ToString();

        if (!RequestStr.empty())
        {
            // Send it through the socket
            if (myConnection.Send(RequestStr.c_str(), RequestStr.size()) == sf::Socket::Done)
            {
                // Wait for the server's response
                std::string ReceivedStr;
                std::size_t Size = 0;
                char Buffer[1024];
                while (myConnection.Receive(Buffer, sizeof(Buffer), Size) == sf::Socket::Done)
                {
                    ReceivedStr.append(Buffer, Buffer + Size);
                }

                // Build the Response object from the received data
                Received.FromString(ReceivedStr);
            }
        }

        // Close the connection
        myConnection.Close();
    }

    return Received;
}

} // namespace sf