summaryrefslogtreecommitdiff
path: root/http_connection.h
blob: f5cd01a20928e93f1931d5cb3b94f7ccf11d8f5b (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
#ifndef HTTP_CONNECTION_H
#define HTTP_CONNECTION_H

#include <string>
#include <vector>
#include <list>
#include <map>
#include <istream>

#include <boost/asio.hpp>
#include <boost/enable_shared_from_this.hpp>
using boost::asio::ip::tcp;

#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;

#include <boost/function.hpp>

namespace HTTP {
	class Connection : public boost::enable_shared_from_this<Connection> {
		friend class Server;
		
		public:
			typedef boost::shared_ptr<Connection> p;
			typedef boost::function<void (Connection::p)> Handler;
			typedef std::list<std::string> PathList;
			
			//! Request method.
			std::string method;
			
			//! Request path.
			PathList path;
			
			//! Base path.
			PathList base_path;
			
			//! Pop topmost element of path and add to base_path.
			std::string pop_path_base();
			
			//! Request arguments.
			std::map<std::string, std::string> args;
			
			//! Request version.
			std::string version;
			
			//! Request headers.
			std::map<std::string, std::string> headers;
			
			//! Send error.
			void send_error(int code);
			
			//! Add response header.
			void add_header(std::string key, std::string value);
			
			//! Send data.
			void send_data(const std::string& data);
			void send_data(const void* data, std::size_t size);
			void send_data(std::istream& stream);
			
			//! Send file.
			void send_file(const fs::path& filename);
			
		private:
			typedef std::vector<std::pair<std::string, std::string> > HeaderList;
			
			//! Constructor.
			Connection(boost::asio::io_service& io_service);
			
			//! Start reading the request headers.
			void read_request(Handler callback);
			
			void handle_write(const boost::system::error_code& error, size_t bytes_transferred);
			void handle_read(const boost::system::error_code& error, size_t bytes_transferred, Handler callback);
			
			tcp::socket socket;
			boost::asio::streambuf buf;
			
			//! Response headers.
			HeaderList response_headers;
			
			//! Parse request headers.
			bool parse_request(boost::asio::streambuf& buf);
			
			//! Write response headers.
			void write_headers(int code = 200);
			
			//! Response headers written?
			bool headers_written;
	};
	
	typedef Connection::Handler Handler;
};

#endif