-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
318 lines (274 loc) · 9.49 KB
/
Copy pathServer.cpp
File metadata and controls
318 lines (274 loc) · 9.49 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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#include <iostream>
#include "stdafx.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include "targetver.h"
#include<string>
#include<sstream>
#include<vector>
#include <map> // Added for HttpRequest headers
#include <fstream>
#include <filesystem>
using namespace std;
// HTTP Request structure
struct HttpRequest {
std::string method;
std::string path;
std::string version;
std::map<std::string, std::string> headers;
std::string body;
};
// Function to read HTTP request until \r\n\r\n
std::string readHttpRequest(SOCKET clientSocket) {
std::string request;
char buffer[1024];
int totalBytes = 0;
while (true) {
int bytesReceived = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
if (bytesReceived <= 0) {
break;
}
buffer[bytesReceived] = '\0';
request += buffer;
totalBytes += bytesReceived;
// Check if we've received the complete request (ends with \r\n\r\n)
if (request.find("\r\n\r\n") != std::string::npos) {
break;
}
// Prevent infinite loop - limit request size
if (totalBytes > 8192) {
break;
}
}
return request;
}
// Function to parse HTTP request
HttpRequest parseHttpRequest(const std::string& rawRequest) {
HttpRequest req;
std::istringstream stream(rawRequest);
std::string line;
// Parse request line (first line)
if (std::getline(stream, line)) {
std::istringstream lineStream(line);
lineStream >> req.method >> req.path >> req.version;
}
// Parse headers
while (std::getline(stream, line) && line != "\r" && !line.empty()) {
size_t colonPos = line.find(':');
if (colonPos != std::string::npos) {
std::string key = line.substr(0, colonPos);
std::string value = line.substr(colonPos + 1);
// Remove leading spaces and \r
while (!value.empty() && (value[0] == ' ' || value[0] == '\r')) {
value.erase(0, 1);
}
req.headers[key] = value;
}
}
return req;
}
// Function to create HTTP response
std::string createHttpResponse(int statusCode, const std::string& statusText,
const std::string& contentType, const std::string& body) {
std::ostringstream response;
// Status line
response << "HTTP/1.1 " << statusCode << " " << statusText << "\r\n";
// Headers
response << "Content-Type: " << contentType << "\r\n";
response << "Content-Length: " << body.length() << "\r\n";
response << "Connection: close\r\n";
response << "\r\n";
// Body
response << body;
return response.str();
}
// Helper function for common responses
std::string createSimpleResponse(int statusCode, const std::string& statusText, const std::string& message) {
std::string htmlBody = "<html><body><h1>" + std::to_string(statusCode) + " " + statusText + "</h1><p>" + message + "</p></body></html>";
return createHttpResponse(statusCode, statusText, "text/html", htmlBody);
}
// Add these includes at the top (after the existing includes)
#include <fstream>
#include <filesystem>
// Function to get MIME type based on file extension
std::string getMimeType(const std::string& path) {
size_t dotPos = path.find_last_of('.');
if (dotPos == std::string::npos) {
return "text/plain";
}
std::string extension = path.substr(dotPos + 1);
if (extension == "html" || extension == "htm") {
return "text/html";
} else if (extension == "css") {
return "text/css";
} else if (extension == "js") {
return "application/javascript";
} else if (extension == "png") {
return "image/png";
} else if (extension == "jpg" || extension == "jpeg") {
return "image/jpeg";
} else if (extension == "gif") {
return "image/gif";
} else {
return "text/plain";
}
}
// Function to read file content
std::string readFileContent(const std::string& filePath) {
std::ifstream file(filePath, std::ios::binary);
if (!file.is_open()) {
return "";
}
// Get file size
file.seekg(0, std::ios::end);
std::streamsize size = file.tellg();
file.seekg(0, std::ios::beg);
// Read file content
std::string content(size, '\0');
if (file.read(&content[0], size)) {
return content;
}
return "";
}
// Function to serve static files
std::string serveStaticFile(const std::string& requestPath) {
// Remove leading slash and handle default path
std::string filePath = requestPath;
if (filePath == "/" || filePath.empty()) {
filePath = "/index.html";
}
// Remove leading slash for filesystem path
if (filePath[0] == '/') {
filePath = filePath.substr(1);
}
// Security: prevent directory traversal (basic protection)
if (filePath.find("..") != std::string::npos) {
return createSimpleResponse(403, "Forbidden", "Access denied.");
}
// Check if file exists
std::ifstream testFile(filePath);
if (!testFile.good()) {
return createSimpleResponse(404, "Not Found", "File not found: " + requestPath);
}
testFile.close();
// Read file content
std::string content = readFileContent(filePath);
if (content.empty()) {
return createSimpleResponse(500, "Internal Server Error", "Failed to read file.");
}
// Get MIME type
std::string mimeType = getMimeType(filePath);
// Create response
return createHttpResponse(200, "OK", mimeType, content);
}
int main(){
cout << "=====Step 1: WSAStartup()=====" << endl;
SOCKET serverSocket, acceptSocket;
int PORT = 5555;
WSADATA wsaData;
int wsaerr;
WORD wVersionRequested = MAKEWORD(2,2);
wsaerr = WSAStartup(wVersionRequested, &wsaData);
if(wsaerr != 0){
cout << "The winsock dll not found! " << wsaerr << endl;
return 1;
}
else{
cout << "The winsock dll found!" << endl;
cout<<"The status: "<<wsaData.szSystemStatus<<endl;
}
cout << "=====Step 2: Create()=====" << endl;
serverSocket = INVALID_SOCKET;
serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(serverSocket == INVALID_SOCKET){
cout<<"Error at socket(): "<<WSAGetLastError() <<endl;
WSACleanup();
return 0;
}
else{
cout<<"socket() is OK!"<<endl;
}
cout << "=====Step 3: Bind()=====" << endl;
sockaddr_in service;
service.sin_family = AF_INET;
InetPton(AF_INET, "127.0.0.1", &service.sin_addr.s_addr);
service.sin_port = htons(PORT);
if(bind(serverSocket, (SOCKADDR*)&service, sizeof(service))==SOCKET_ERROR){
cout<<"bind() failed: "<<WSAGetLastError() <<endl;
closesocket(serverSocket);
WSACleanup();
return 0;
}
else{
cout<<"bind() is OK!"<<endl;
}
cout << "=====Step 4: Listen()=====" << endl;
if(listen(serverSocket, 1)==SOCKET_ERROR){
cout<<"listen(): Error listening on socket"<<WSAGetLastError()<<endl;
}
else{
cout<<"listen() is OK, I'm waiting for connections.."<<endl;
}
cout << "=====Step 5: Accept()=====" << endl;
acceptSocket = accept(serverSocket, NULL, NULL);
if(acceptSocket ==INVALID_SOCKET){
cout<<"accept failed: "<<WSAGetLastError()<<endl;
WSACleanup();
return -1;
}
else{
cout<<"Accepted connection"<<endl;
}
cout << "=====Step 6: Connect()=====" << endl;
// cout << "=====Step 8: Recv()=====" << endl;
// char buffer[200];
// int byteCount = recv(acceptSocket, buffer, 200, 0);
// if(byteCount>0){
// cout<<"Server: recv() is ok!"<<endl;
// cout<<"Server: message received from client: "<<buffer<<endl;
// } else{
// cout<<"Server: recv() failed!"<<WSAGetLastError()<<endl;
// WSACleanup();
// return -1;
cout << "=====Step 8: HTTP Request Handling =====" << endl;
std::string rawRequest = readHttpRequest(acceptSocket);
if (!rawRequest.empty()) {
cout << "Raw HTTP request received:" << endl;
cout << rawRequest << endl;
// Parse the request
HttpRequest request = parseHttpRequest(rawRequest);
cout << "Parsed request - Method: " << request.method << ", Path: " << request.path << endl;
// Handle the request
std::string response;
if (request.method == "GET") {
// Try to serve static file
response = serveStaticFile(request.path);
} else {
response = createSimpleResponse(405, "Method Not Allowed", "This method is not supported.");
}
// Send the response
int bytesSent = send(acceptSocket, response.c_str(), response.length(), 0);
if (bytesSent > 0) {
cout << "HTTP response sent successfully!" << endl;
} else {
cout << "Failed to send HTTP response: " << WSAGetLastError() << endl;
}
} else {
cout << "Failed to read HTTP request!" << endl;
}
cout << "=====Step 7: Send()=====" << endl;
char buffer2[200]= "Message received";
int byteCount2 = send(acceptSocket, buffer2, strlen(buffer2), 0);
if(byteCount2>0){
cout<<"Server: send() is ok!"<<endl;
cout<<"Server: message sent to client: "<<buffer2<<endl;
} else{
cout<<"Server: send() failed!"<<WSAGetLastError()<<endl;
}
cout << "=====Step 9: Close()=====" << endl;
cout << "=====Step 10: WSACleanup()=====" << endl;
system("pause");
WSACleanup();
return 0;
}