1 #ifndef CLIENT_HTTP_HPP
2 #define CLIENT_HTTP_HPP
4 #include <boost/asio.hpp>
5 #include <boost/utility/string_ref.hpp>
6 #include <boost/algorithm/string/predicate.hpp>
7 #include <boost/functional/hash.hpp>
9 #include <unordered_map>
13 #include <type_traits>
15 #ifndef CASE_INSENSITIVE_EQUALS_AND_HASH
16 #define CASE_INSENSITIVE_EQUALS_AND_HASH
17 //Based on http://www.boost.org/doc/libs/1_60_0/doc/html/unordered/hash_equality.html
18 class case_insensitive_equals {
20 bool operator()(const std::string &key1, const std::string &key2) const {
21 return boost::algorithm::iequals(key1, key2);
24 class case_insensitive_hash {
26 size_t operator()(const std::string &key) const {
29 boost::hash_combine(seed, std::tolower(c));
36 template <class socket_type>
39 template <class socket_type>
42 virtual ~ClientBase() {}
45 friend class ClientBase<socket_type>;
46 friend class Client<socket_type>;
48 std::string http_version, status_code;
52 std::unordered_multimap<std::string, std::string, case_insensitive_hash, case_insensitive_equals> header;
55 boost::asio::streambuf content_buffer;
57 Response(): content(&content_buffer) {}
61 friend class ClientBase<socket_type>;
65 /// Set timeout on requests in seconds. Default value: 0 (no timeout).
67 /// Set connect timeout in seconds. Default value: 0 (Config::timeout is then used instead).
68 size_t timeout_connect=0;
69 /// Set proxy server (server:port)
70 std::string proxy_server;
73 /// Set before calling request
76 std::shared_ptr<Response> request(const std::string& request_type, const std::string& path="/", boost::string_ref content="",
77 const std::map<std::string, std::string>& header=std::map<std::string, std::string>()) {
78 auto corrected_path=path;
79 if(corrected_path=="")
81 if(!config.proxy_server.empty() && std::is_same<socket_type, boost::asio::ip::tcp::socket>::value)
82 corrected_path="http://"+host+':'+std::to_string(port)+corrected_path;
84 boost::asio::streambuf write_buffer;
85 std::ostream write_stream(&write_buffer);
86 write_stream << request_type << " " << corrected_path << " HTTP/1.1\r\n";
87 write_stream << "Host: " << host << "\r\n";
88 for(auto& h: header) {
89 write_stream << h.first << ": " << h.second << "\r\n";
92 write_stream << "Content-Length: " << content.size() << "\r\n";
93 write_stream << "\r\n";
97 auto timer=get_timeout_timer();
98 boost::asio::async_write(*socket, write_buffer,
99 [this, &content, timer](const boost::system::error_code &ec, size_t /*bytes_transferred*/) {
103 if(!content.empty()) {
104 auto timer=get_timeout_timer();
105 boost::asio::async_write(*socket, boost::asio::buffer(content.data(), content.size()),
106 [this, timer](const boost::system::error_code &ec, size_t /*bytes_transferred*/) {
110 std::lock_guard<std::mutex> lock(socket_mutex);
111 this->socket=nullptr;
112 throw boost::system::system_error(ec);
118 std::lock_guard<std::mutex> lock(socket_mutex);
120 throw boost::system::system_error(ec);
126 return request_read();
129 std::shared_ptr<Response> request(const std::string& request_type, const std::string& path, std::iostream& content,
130 const std::map<std::string, std::string>& header=std::map<std::string, std::string>()) {
131 auto corrected_path=path;
132 if(corrected_path=="")
134 if(!config.proxy_server.empty() && std::is_same<socket_type, boost::asio::ip::tcp::socket>::value)
135 corrected_path="http://"+host+':'+std::to_string(port)+corrected_path;
137 content.seekp(0, std::ios::end);
138 auto content_length=content.tellp();
139 content.seekp(0, std::ios::beg);
141 boost::asio::streambuf write_buffer;
142 std::ostream write_stream(&write_buffer);
143 write_stream << request_type << " " << corrected_path << " HTTP/1.1\r\n";
144 write_stream << "Host: " << host << "\r\n";
145 for(auto& h: header) {
146 write_stream << h.first << ": " << h.second << "\r\n";
149 write_stream << "Content-Length: " << content_length << "\r\n";
150 write_stream << "\r\n";
152 write_stream << content.rdbuf();
156 auto timer=get_timeout_timer();
157 boost::asio::async_write(*socket, write_buffer,
158 [this, timer](const boost::system::error_code &ec, size_t /*bytes_transferred*/) {
162 std::lock_guard<std::mutex> lock(socket_mutex);
164 throw boost::system::system_error(ec);
170 return request_read();
174 std::lock_guard<std::mutex> lock(socket_mutex);
176 boost::system::error_code ec;
177 socket->lowest_layer().shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
178 socket->lowest_layer().close();
183 boost::asio::io_service io_service;
184 boost::asio::ip::tcp::resolver resolver;
186 std::unique_ptr<socket_type> socket;
187 std::mutex socket_mutex;
192 ClientBase(const std::string& host_port, unsigned short default_port) : resolver(io_service) {
193 auto parsed_host_port=parse_host_port(host_port, default_port);
194 host=parsed_host_port.first;
195 port=parsed_host_port.second;
198 std::pair<std::string, unsigned short> parse_host_port(const std::string &host_port, unsigned short default_port) {
199 std::pair<std::string, unsigned short> parsed_host_port;
200 size_t host_end=host_port.find(':');
201 if(host_end==std::string::npos) {
202 parsed_host_port.first=host_port;
203 parsed_host_port.second=default_port;
206 parsed_host_port.first=host_port.substr(0, host_end);
207 parsed_host_port.second=static_cast<unsigned short>(stoul(host_port.substr(host_end+1)));
209 return parsed_host_port;
212 virtual void connect()=0;
214 std::shared_ptr<boost::asio::deadline_timer> get_timeout_timer(size_t timeout=0) {
216 timeout=config.timeout;
220 auto timer=std::make_shared<boost::asio::deadline_timer>(io_service);
221 timer->expires_from_now(boost::posix_time::seconds(timeout));
222 timer->async_wait([this](const boost::system::error_code& ec) {
230 void parse_response_header(const std::shared_ptr<Response> &response) const {
232 getline(response->content, line);
233 size_t version_end=line.find(' ');
234 if(version_end!=std::string::npos) {
236 response->http_version=line.substr(5, version_end-5);
237 if((version_end+1)<line.size())
238 response->status_code=line.substr(version_end+1, line.size()-(version_end+1)-1);
240 getline(response->content, line);
242 while((param_end=line.find(':'))!=std::string::npos) {
243 size_t value_start=param_end+1;
244 if((value_start)<line.size()) {
245 if(line[value_start]==' ')
247 if(value_start<line.size())
248 response->header.insert(std::make_pair(line.substr(0, param_end), line.substr(value_start, line.size()-value_start-1)));
251 getline(response->content, line);
256 std::shared_ptr<Response> request_read() {
257 std::shared_ptr<Response> response(new Response());
259 boost::asio::streambuf chunked_streambuf;
261 auto timer=get_timeout_timer();
262 boost::asio::async_read_until(*socket, response->content_buffer, "\r\n\r\n",
263 [this, &response, &chunked_streambuf, timer](const boost::system::error_code& ec, size_t bytes_transferred) {
267 size_t num_additional_bytes=response->content_buffer.size()-bytes_transferred;
269 parse_response_header(response);
271 auto header_it=response->header.find("Content-Length");
272 if(header_it!=response->header.end()) {
273 auto content_length=stoull(header_it->second);
274 if(content_length>num_additional_bytes) {
275 auto timer=get_timeout_timer();
276 boost::asio::async_read(*socket, response->content_buffer,
277 boost::asio::transfer_exactly(content_length-num_additional_bytes),
278 [this, timer](const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
282 std::lock_guard<std::mutex> lock(socket_mutex);
283 this->socket=nullptr;
284 throw boost::system::system_error(ec);
289 else if((header_it=response->header.find("Transfer-Encoding"))!=response->header.end() && header_it->second=="chunked") {
290 request_read_chunked(response, chunked_streambuf);
292 else if(response->http_version<"1.1" || ((header_it=response->header.find("Connection"))!=response->header.end() && header_it->second=="close")) {
293 auto timer=get_timeout_timer();
294 boost::asio::async_read(*socket, response->content_buffer,
295 [this, timer](const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
299 std::lock_guard<std::mutex> lock(socket_mutex);
300 this->socket=nullptr;
301 if(ec!=boost::asio::error::eof)
302 throw boost::system::system_error(ec);
308 std::lock_guard<std::mutex> lock(socket_mutex);
310 throw boost::system::system_error(ec);
319 void request_read_chunked(const std::shared_ptr<Response> &response, boost::asio::streambuf &streambuf) {
320 auto timer=get_timeout_timer();
321 boost::asio::async_read_until(*socket, response->content_buffer, "\r\n",
322 [this, &response, &streambuf, timer](const boost::system::error_code& ec, size_t bytes_transferred) {
327 getline(response->content, line);
328 bytes_transferred-=line.size()+1;
330 std::streamsize length=stol(line, 0, 16);
332 auto num_additional_bytes=static_cast<std::streamsize>(response->content_buffer.size()-bytes_transferred);
334 auto post_process=[this, &response, &streambuf, length] {
335 std::ostream stream(&streambuf);
337 std::vector<char> buffer(static_cast<size_t>(length));
338 response->content.read(&buffer[0], length);
339 stream.write(&buffer[0], length);
343 response->content.get();
344 response->content.get();
347 request_read_chunked(response, streambuf);
349 std::ostream response_stream(&response->content_buffer);
350 response_stream << stream.rdbuf();
354 if((2+length)>num_additional_bytes) {
355 auto timer=get_timeout_timer();
356 boost::asio::async_read(*socket, response->content_buffer,
357 boost::asio::transfer_exactly(2+length-num_additional_bytes),
358 [this, post_process, timer](const boost::system::error_code& ec, size_t /*bytes_transferred*/) {
365 std::lock_guard<std::mutex> lock(socket_mutex);
366 this->socket=nullptr;
367 throw boost::system::system_error(ec);
375 std::lock_guard<std::mutex> lock(socket_mutex);
377 throw boost::system::system_error(ec);
383 template<class socket_type>
384 class Client : public ClientBase<socket_type> {};
386 typedef boost::asio::ip::tcp::socket HTTP;
389 class Client<HTTP> : public ClientBase<HTTP> {
391 Client(const std::string& server_port_path) : ClientBase<HTTP>::ClientBase(server_port_path, 80) {}
395 if(!socket || !socket->is_open()) {
396 std::unique_ptr<boost::asio::ip::tcp::resolver::query> query;
397 if(config.proxy_server.empty())
398 query=std::unique_ptr<boost::asio::ip::tcp::resolver::query>(new boost::asio::ip::tcp::resolver::query(host, std::to_string(port)));
400 auto proxy_host_port=parse_host_port(config.proxy_server, 8080);
401 query=std::unique_ptr<boost::asio::ip::tcp::resolver::query>(new boost::asio::ip::tcp::resolver::query(proxy_host_port.first, std::to_string(proxy_host_port.second)));
403 resolver.async_resolve(*query, [this](const boost::system::error_code &ec,
404 boost::asio::ip::tcp::resolver::iterator it){
407 std::lock_guard<std::mutex> lock(socket_mutex);
408 socket=std::unique_ptr<HTTP>(new HTTP(io_service));
411 auto timer=get_timeout_timer(config.timeout_connect);
412 boost::asio::async_connect(*socket, it, [this, timer]
413 (const boost::system::error_code &ec, boost::asio::ip::tcp::resolver::iterator /*it*/){
417 boost::asio::ip::tcp::no_delay option(true);
418 this->socket->set_option(option);
421 std::lock_guard<std::mutex> lock(socket_mutex);
422 this->socket=nullptr;
423 throw boost::system::system_error(ec);
428 std::lock_guard<std::mutex> lock(socket_mutex);
430 throw boost::system::system_error(ec);
440 #endif /* CLIENT_HTTP_HPP */