-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_tcpServer_linux.cpp
More file actions
218 lines (183 loc) · 5.55 KB
/
Copy pathhttp_tcpServer_linux.cpp
File metadata and controls
218 lines (183 loc) · 5.55 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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#include "response.h"
#include "http_tcpServer_linux.h"
#include <netinet/in.h>
#include <ostream>
#include <fstream>
#include <functional>
#include <string>
#include <thread>
#include <sys/socket.h>
#include <iostream>
#include <sstream>
#include <unistd.h>
namespace{
const int BUFFER_SIZE = 30720;
void log(const std::string &message)
{
std::cout << message << std::endl;
}
void ewe(const std::string &errorMessage)
{
log("ERROR: " + errorMessage);
exit(1);
}
}
namespace http{
TcpServer::TcpServer(std:: string ip_address, int port)
: m_ip_address(ip_address), m_port(port), m_socket(), m_new_socket(), m_incomingMessage(),
m_socketAddress(), m_socketAddress_len(sizeof(m_socketAddress)), m_serverMessage()
{
m_socketAddress.sin_family = AF_INET;
m_socketAddress.sin_port = htons(m_port);
m_socketAddress.sin_addr.s_addr = inet_addr(m_ip_address.c_str());
startServer();
};
TcpServer::~TcpServer(){
closeServer();
};
int TcpServer:: startServer(){
m_socket = socket(AF_INET, SOCK_STREAM, 0);
if(m_socket < 0){
ewe("Failed to start the server");
return -1;
}
if (bind(m_socket,(sockaddr *)&m_socketAddress, m_socketAddress_len) < 0)
{
ewe("Cannot connect socket to address");
return 1;
}
return 0;
}
void TcpServer:: closeServer(){
close(m_socket);
close(m_new_socket);
exit(0);
}
void TcpServer::startListen(){
if(listen(m_socket, 20) < 0){
ewe("failed to listen! ");
}
std::ostringstream ss;
std:: cout << "\n Listening on address: " << inet_ntoa(m_socketAddress.sin_addr) << " | Port: " << ntohs(m_socketAddress.sin_port) << "\n" ;
int bytesReceived;
while (true)
{
log("====== Waiting for a new connection ======\n");
m_new_socket = accept(m_socket,(sockaddr *)&m_socketAddress, &m_socketAddress_len);
if(m_new_socket < 0){
ewe("Server failed to accept incomming connection");
}
int socket_fd = m_new_socket;
std:: thread t([this, socket_fd](){
handleClient(socket_fd);
});
t.detach();
}
}
void TcpServer::sendResponse(int socket_fd){
long bytesSent = write(socket_fd, m_serverMessage.c_str(), m_serverMessage.size());
if (bytesSent == m_serverMessage.size())
{
log("------ Server Response sent to client ------\n");
}
else
{
ewe("Error sending response to client");
}
}
HttpRequest parseRequest(const std::string& raw){
HttpRequest req;
// for method and path
std::string first_line = raw.substr(0, raw.find("\r\n"));
int pos = first_line.find(" ");
int pos2 = first_line.find(" ", pos+1);
req.method = first_line.substr(0, pos);
req.path = first_line.substr(pos + 1, pos2 - pos - 1);
// for headers
int headerStart = raw.find("\r\n") + 2;
int i = headerStart;
int headerEnd = raw.find("\r\n\r\n");
while(i < headerEnd){
int line_end = raw.find("\r\n", i);
std::string line = raw.substr(i, line_end - i);
int sep = line.find(": ");
std::string key = line.substr(0, sep);
std::string value = line.substr(sep + 2); // +2 to skip ": "
req.headers[key] = value;
i = line_end + 2;
}
return req;
};
void TcpServer::handleClient(int socket_fd){
std::string raw = readFullRequest(socket_fd);
HttpRequest req = parseRequest(raw);
log("Method: " + req.method);
log("Path: " + req.path);
//check if the path handler exits
if(routes.find(req.path) != routes.end()){
routes[req.path](req, socket_fd);
}else{
std::string notFound = "HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\n\r\nNot Found";
write(socket_fd, notFound.c_str(), notFound.size());
}
close(socket_fd);
}
std::string TcpServer::readFullRequest(int socket_fd){
std::string message = "";
char buffer[BUFFER_SIZE] = {0};
std::string ends = "\r\n\r\n";
int store;
while(true){
store = read(socket_fd, buffer, BUFFER_SIZE);
if(store == 0){
return message;
}
message.append(buffer, store);
if(message.find(ends) != std::string::npos){
return message;
}
};
}
void TcpServer::addRoute(std::string path, std::function<void(HttpRequest&, int socket_fd)> handler) {
routes[path] = handler;
}
// Response class implementation
void Response::send(int socket){
std::string res = "HTTP/1.1 " + std::to_string(status_code) + " " + statusText() + " \r\n"
+ "Content-Type: " + content_type + "\r\n"
+ "Content-Length: " + std::to_string(bodyhtml.size()) + "\r\n\r\n"
+ bodyhtml;
write(socket, res.c_str(), res.size());
}
Response& Response::status(int code){
status_code = code;
return *this;
}
Response& Response::body(std::string bodyh){
bodyhtml = bodyh;
return *this;
}
//fetching content from the file name
std::string Response::getContent(std::string file){
// fetching content_type
if(file.find(".html") != std::string::npos){
content_type = "text/html";
}else if(file.find(".css") != std::string::npos){
content_type = "text/css";
}else if(file.find(".js") != std::string::npos){
content_type = "text/javascript";
}
std::string line;
std::string bodyfull = "";
std::string bodyError = "<h1> 404 Not Found <h1>";
std::ifstream fp(file);
if(!fp.is_open()){
return bodyError;
}
while(std::getline(fp, line)){
bodyfull += line + "\n";
}
fp.close();
return bodyfull;
}
}