-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpServer.cpp
More file actions
180 lines (155 loc) · 5.97 KB
/
HttpServer.cpp
File metadata and controls
180 lines (155 loc) · 5.97 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
#include "HttpServer.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <unordered_map>
namespace {
std::string getMimeType(const std::string& extension) {
static const std::unordered_map<std::string, std::string> mimeTypes = {
{".html", "text/html; charset=utf-8"},
{".htm", "text/html; charset=utf-8"},
{".css", "text/css; charset=utf-8"},
{".js", "application/javascript; charset=utf-8"},
{".json", "application/json; charset=utf-8"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"},
{".svg", "image/svg+xml"},
{".ico", "image/x-icon"}
};
auto it = mimeTypes.find(extension);
if (it != mimeTypes.end()) {
return it->second;
}
return "application/octet-stream";
}
bool sendAll(SOCKET socket, const char* data, int length) {
int totalSent = 0;
while (totalSent < length) {
int sent = send(socket, data + totalSent, length - totalSent, 0);
if (sent == SOCKET_ERROR) {
return false;
}
totalSent += sent;
}
return true;
}
bool readFileBinary(const std::filesystem::path& filePath, std::string& content) {
std::ifstream file(filePath, std::ios::binary);
if (!file) {
return false;
}
std::ostringstream buffer;
buffer << file.rdbuf();
content = buffer.str();
return true;
}
std::string buildHttpResponse(const std::string& statusLine,
const std::string& contentType,
const std::string& body) {
std::ostringstream response;
response << statusLine << "\r\n";
response << "Content-Type: " << contentType << "\r\n";
response << "Content-Length: " << body.size() << "\r\n";
response << "Connection: close\r\n\r\n";
response << body;
return response.str();
}
}
HttpServer::HttpServer(int p) : port(p), serverSocket(INVALID_SOCKET) {}
void HttpServer::start() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Error inicializando Winsock\n";
return;
}
// Crear socket y bind
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET) {
std::cerr << "Error creando socket\n";
WSACleanup();
return;
}
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(port);
if (bind(serverSocket, (struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
std::cerr << "Error bind\n";
closesocket(serverSocket);
WSACleanup();
return;
}
if (listen(serverSocket, 5) == SOCKET_ERROR) {
std::cerr << "Error listen\n";
closesocket(serverSocket);
WSACleanup();
return;
}
std::cout << "Servidor escuchando en puerto " << port << "\n";
while (true) {
SOCKET clientSocket = accept(serverSocket, nullptr, nullptr);
if (clientSocket == INVALID_SOCKET) continue;
std::thread(&HttpServer::handleClient, this, clientSocket).detach();
}
}
void HttpServer::handleClient(SOCKET clientSocket) {
char buffer[4096];
int bytes = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
if (bytes > 0) {
buffer[bytes] = '\0';
std::istringstream requestStream(buffer);
std::string method;
std::string requestedPath;
std::string version;
requestStream >> method >> requestedPath >> version;
if (method != "GET") {
const std::string body = "Method Not Allowed";
std::string response = buildHttpResponse("HTTP/1.1 405 Method Not Allowed",
"text/plain; charset=utf-8",
body);
sendAll(clientSocket, response.c_str(), static_cast<int>(response.size()));
closesocket(clientSocket);
return;
}
std::string relativePath = requestedPath;
size_t queryStart = relativePath.find('?');
if (queryStart != std::string::npos) {
relativePath = relativePath.substr(0, queryStart);
}
if (relativePath.empty() || relativePath == "/") {
relativePath = "/index.html";
}
if (!relativePath.empty() && relativePath.front() == '/') {
relativePath.erase(0, 1);
}
// Bloquea traversal para evitar salir de la carpeta www.
if (relativePath.find("..") != std::string::npos) {
const std::string body = "Forbidden";
std::string response = buildHttpResponse("HTTP/1.1 403 Forbidden",
"text/plain; charset=utf-8",
body);
sendAll(clientSocket, response.c_str(), static_cast<int>(response.size()));
closesocket(clientSocket);
return;
}
std::filesystem::path fullPath = std::filesystem::path("www") / relativePath;
std::string fileContent;
if (!std::filesystem::exists(fullPath) || !std::filesystem::is_regular_file(fullPath) ||
!readFileBinary(fullPath, fileContent)) {
const std::string body = "404 - Archivo no encontrado";
std::string response = buildHttpResponse("HTTP/1.1 404 Not Found",
"text/plain; charset=utf-8",
body);
sendAll(clientSocket, response.c_str(), static_cast<int>(response.size()));
closesocket(clientSocket);
return;
}
std::string contentType = getMimeType(fullPath.extension().string());
std::string response = buildHttpResponse("HTTP/1.1 200 OK", contentType, fileContent);
sendAll(clientSocket, response.c_str(), static_cast<int>(response.size()));
}
closesocket(clientSocket);
}