-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_server.cpp
More file actions
191 lines (164 loc) · 5.73 KB
/
Copy pathhttp_server.cpp
File metadata and controls
191 lines (164 loc) · 5.73 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
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
#include <csignal>
#include <fstream>
#include <http_server.h>
#include <iostream>
#include <sstream>
#include <unistd.h>
#include <string>
#include <thread>
#include <queue>
#include "Config.h"
#include "Socket.h"
namespace {
const int BUFFER_SIZE = 30720;
}
namespace applicationLog
{
void log(const std::string &message)
{
std::cout << message << std::endl;
}
void exitWithError(const std::string &errorMessage)
{
log("ERROR: " + errorMessage);
exit(1);
}
}
namespace http
{
static bool gDone = false;
void doneRoutine(int signum) {
if (signum == SIGINT || signum == SIGQUIT || signum == SIGTERM) {
gDone = true;
std::cout << "All done. Quiting..." << std::endl;
}
else {
std::cerr << "Unknown signal " << signum << std::endl;
gDone = true;
}
}
Server::Server(std::string documentRoot, std::string ipAddress, int port) :
mDocumentRoot(documentRoot),
mIPAddress(ipAddress),
mSocket(),
mIncomingMessage(),
mServerMessage("<!DOCTYPE html><html lang=\"en\"><body><h1> 404 </h1><p> The page you requested does not exist</p></body></html>")
{
mSocket.bindToAddress(ipAddress, port);
if (start() != 0)
{
std::ostringstream ss;
ss << "Failed to start server with PORT: " << port;
applicationLog::log(ss.str());
}
}
Server::~Server()
{
stop();
}
int Server::start()
{
if (!mSocket.isValid())
{
applicationLog::exitWithError("Cannot create socket");
return 1;
}
return 0;
}
void Server::stop()
{
mSocket.close();
exit(0);
}
void Server::run()
{
if (mSocket.listen(20) < 0)
{
applicationLog::exitWithError("Socket listen failed");
}
std::queue<std::thread> tasks;
std::ostringstream ss;
ss << "\n*** Listening on ADDRESS: " << mSocket.ipAddress() << " PORT: " << mSocket.port() << " ***\n\n";
applicationLog::log(ss.str());
int bytesReceived;
while (true)
{
applicationLog::log("====== Waiting for a new connection ======\n\n\n");
Socket workSocket = mSocket.accept();
// TODO: here should be processing thread get from thread pool. And if all threads are already
// occupied, 501 response should be generated instead
std::thread t([this](Socket socket)->void
{
std::string request;
auto bytesCounter = socket.receive(request);
if (bytesCounter < 0)
{
applicationLog::exitWithError("Failed to read bytes from client socket connection");
}
std::ostringstream ss;
ss << "------ Received Request from client ------\n\n";
ss << "Request size: " << bytesCounter << ":" << request.size() << "\n";
ss << request;;
applicationLog::log(ss.str());
std::string response = this->makeResponse(request);
bytesCounter = socket.send(response);
std::cout << "Response is ==> " << response << std::endl;
if (bytesCounter != response.size()) {
applicationLog::log("Error sending response to client");
}
socket.close();
}, std::move(workSocket));
t.detach();
}
}
std::string Server::makeResponse(std::string const& request) {
if (request.rfind("GET", 0) == 0) {
std::string htmlFile = mDocumentRoot + "/index.html";
std::string response;
std::cout << "Requested page is " << htmlFile << std::endl;
std::ifstream ifs(htmlFile.c_str(),std::ios::in | std::ios::binary | std::ios::ate);
if (!ifs.is_open()) {
std::ostringstream ss;
std::string notFoundFile = mDocumentRoot + "/404.html";
std::ifstream nff(notFoundFile.c_str(),std::ios::binary | std::ios::ate);
auto nffSize = nff.tellg();
nff.seekg(0, std::ios::beg);
ss << "HTTP/1.1 404 NotFound\nContent-Type: text/html\nContent-Length: " << nffSize << "\n\n"
<< nff.rdbuf();
return ss.str();
}
auto fileSize = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::ostringstream ss;
ss << "HTTP/1.1 200 OK\nContent-Type: text/html\nContent-Length: " << fileSize << "\n\n"
<< ifs.rdbuf();
return ss.str();
}
std::ostringstream ss;
ss << "HTTP/1.1 400 BadRequest\n\n";
return ss.str();
}
void Server::process() {
gDone = false;
signal(SIGINT, doneRoutine);
signal(SIGTERM, doneRoutine);
for (size_t id = 0; id < config::Config::get()->serverCount(); id++) {
std::thread server([](size_t id) {
config::ServerNode serverConfig = config::Config::get()->server(id);
std::string serverIP("0.0.0.0");
if (serverConfig.ip != "*") {
serverIP = serverConfig.ip;
}
Server server(serverConfig.documentRoot, serverIP, serverConfig.port);
server.run();
}, id);
server.detach();
config::Config::get()->general().capacity--;
}
/* main loop */
while (!gDone) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
std::cout << "\nDone!" << std::endl;
}
} // namespace http