/
HTTP.cpp
133 lines (99 loc) · 2.66 KB
/
HTTP.cpp
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
#include <vector>
#include <iostream>
#include <string>
#include <deque>
#include <regex>
#include <mutex>
#include <thread>
#include <assert.h>
#include <sstream>
#include <unordered_map>
#include <boost/asio.hpp>
#include "Log.h"
#include "ASIOThreadPool.h"
#include "StringFacility.h"
#include "HTTP.h"
using boost::asio::ip::tcp;
namespace TorrentStream
{
namespace HTTP
{
URL ParseURL(const std::string& url)
{
URL result;
std::regex regex("^(?:http://)?([^/]+)(?:/?.*/?)/(.*)$");
std::match_results<std::string::const_iterator> what;
if (!std::regex_search(url, what, regex))
{
throw InvalidURL();
}
std::string base_url(what[1].first, what[1].second);
auto query = split(std::string(what[2].first, what[2].second), '?');
result.scheme = "http";
result.authority = base_url;
result.path = query[0];
if (query.size() > 1)
{
auto args = split(query[1], '&');
for (auto& keyval : args)
{
auto kv = split(keyval, '=');
auto key = kv[0];
std::string val = "";
if (kv.size() > 1)
{
val = kv[1];
}
result.arguments[key] = val;
}
}
return result;
}
HTTPResponse DoHTTPRequest(const URL& url)
{
assert(url.scheme == "http");
auto& service = ASIO::ThreadPool::Instance().GetService();
tcp::socket socket(service);
tcp::resolver resolver(service);
auto ipPort = split(url.authority, ':');
std::string ip = ipPort[0];
std::string port;
if (ipPort.size() == 1)
{
port = "80";
}
else
{
port = ipPort[1];
}
boost::asio::connect(socket, resolver.resolve({ ip, port }));
boost::asio::streambuf request;
std::ostream request_stream(&request);
request_stream << "GET /" << url.path << "?" << url.GetArgumentsString() << " HTTP/1.0\r\n";
request_stream << "Host: " << url.authority << "\r\n\r\n";
boost::asio::write(socket, request);
boost::system::error_code error;
boost::asio::streambuf buffer;
boost::asio::read_until(socket, buffer, "\r\n", error);
std::istream stream(&buffer);
std::string httpVersion;
stream >> httpVersion;
unsigned int statusCode;
stream >> statusCode;
boost::asio::read_until(socket, buffer, "\r\n\r\n", error);
std::string header;
while (std::getline(stream, header) && header != "\r");
while (boost::asio::read(socket, buffer, boost::asio::transfer_at_least(1), error))
{
if (error == boost::asio::error::eof)
{
break;
}
}
HTTPResponse result;
result.statusCode = statusCode;
result.content = std::vector<char>(std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>());
return result;
}
}
}