Repository navigation
Expand file tree
/
Copy pathrequest_handler.cc
More file actions
93 lines (82 loc) · 2.54 KB
/
Copy pathrequest_handler.cc
File metadata and controls
93 lines (82 loc) · 2.54 KB
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
#include "request_handler.h"
#include <fstream>
#include <sstream>
#include <string>
#include <boost/lexical_cast.hpp>
#include "mime_types.h"
#include "reply.h"
#include "request.h"
namespace http {
namespace server {
request_handler::request_handler(const std::string& doc_root)
: doc_root_(doc_root)
{
}
void request_handler::handle_request(const request& req, reply& rep)
{
// Decode url to path.
std::string request_path;
if (!url_decode(req.uri, request_path)) {
rep = reply::stock_reply(reply::bad_request);
return;
}
if (request_path.empty() || request_path[0] != '/'
|| request_path.find("..") != std::string::npos) {
rep = reply::stock_reply(reply::bad_request);
return;
}
if ('/' == request_path[request_path.size() - 2]) {
request_path += "index.html";
}
std::size_t last_slash_pos = request_path.find_last_of("/");
std::size_t last_dot_pos = request_path.find_last_of(".");
std::string extension;
if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) {
extension = request_path.substr(last_dot_pos + 1);
}
std::string full_path = doc_root_ + request_path;
std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary);
if (!is) {
rep = reply::stock_reply(reply::not_found);
return;
}
// Fill out the reply to be sent to the client.
rep.status = reply::ok;
char buf[512] = "\0";
while (is.read(buf, sizeof(buf)).gcount() > 0) {
rep.content.append(buf, is.gcount());
}
rep.headers.resize(2);
rep.headers[0].name = "Content-Length";
rep.headers[0].value = boost::lexical_cast<std::string>(rep.content.size());
rep.headers[1].name = "Content-Type";
rep.headers[1].value = mime_types::extension_to_type(extension);
}
bool request_handler::url_decode(const std::string& in, std::string& out)
{
out.clear();
out.reserve(in.size());
for (std::size_t i=0; i < in.size(); ++i) {
if ('%' == in[i]) {
if (i + 3 <= in.size()) {
int value = 0;
std::istringstream is(in.substr(i + 1, 2));
if (is >> std::hex >> value) {
out += static_cast<char>(value);
i += 2;
} else {
return false;
}
} else {
return false;
}
} else if ('+' == in[i]) {
out += ' ';
} else {
out += in[i];
}
}
return true;
}
};
};