-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileManager.cpp
More file actions
1407 lines (1178 loc) · 52 KB
/
Copy pathFileManager.cpp
File metadata and controls
1407 lines (1178 loc) · 52 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "FileManager.hpp"
#include "Utils.hpp"
#include <cstring>
#include <ctime>
#include <limits.h>
#include <unistd.h>
#include <errno.h>
#include <set>
FileManager::FileManager(Config& config) : config(config) {
importantExtensions.push_back(".conf");
importantExtensions.push_back(".key");
importantExtensions.push_back(".cert");
importantExtensions.push_back(".db");
initializeMimeTypes();
try {
cachedLocations = config.get_all_Locations();
// Debug: print out all cached locations
debug("[FileManager]: Cached " + Utils::to_string(cachedLocations.size()) + " locations");
// Print out the locations for verification
for (std::map<std::string, Location>::const_iterator it = cachedLocations.begin();
it != cachedLocations.end(); ++it) {
debug("Cached Location: " + it->first + ", Root: " + it->second.get_root());
}
} catch (const std::exception& e) {
debug("[FileManager]: Error caching locations: " + std::string(e.what()));
}
}
FileManager::~FileManager() {
// No resources to clean up
}
void FileManager::initializeMimeTypes() {
// Common MIME types
mimeTypes[".html"] = "text/html";
mimeTypes[".htm"] = "text/html";
mimeTypes[".css"] = "text/css";
mimeTypes[".js"] = "application/javascript";
mimeTypes[".json"] = "application/json";
mimeTypes[".txt"] = "text/plain";
mimeTypes[".jpg"] = "image/jpeg";
mimeTypes[".jpeg"] = "image/jpeg";
mimeTypes[".png"] = "image/png";
mimeTypes[".gif"] = "image/gif";
mimeTypes[".svg"] = "image/svg+xml";
mimeTypes[".ico"] = "image/x-icon";
mimeTypes[".pdf"] = "application/pdf";
mimeTypes[".xml"] = "application/xml";
}
std::string FileManager::findBestLocationMatch(const std::string& path) const {
// Defensive checks
if (path.empty()) {
return "/";
}
if (cachedLocations.empty()) {
return "/";
}
// Normalize the request path
std::string normalizedPath = path;
// Ensure path starts with '/'
if (normalizedPath[0] != '/') {
normalizedPath = "/" + normalizedPath;
}
// Remove trailing slash for comparison purposes
if (normalizedPath.length() > 1 && normalizedPath[normalizedPath.length() - 1] == '/') {
normalizedPath = normalizedPath.substr(0, normalizedPath.length() - 1);
}
debug("[findBestLocationMatch]: Normalized path: " + normalizedPath);
// First try exact match
if (cachedLocations.find(normalizedPath) != cachedLocations.end()) {
return normalizedPath;
}
// Try with trailing slash variant
std::string pathWithSlash = normalizedPath + '/';
if (cachedLocations.find(pathWithSlash) != cachedLocations.end()) {
return pathWithSlash;
}
// Try with path without trailing slash
if (normalizedPath[normalizedPath.length() - 1] == '/') {
std::string pathWithoutSlash = normalizedPath.substr(0, normalizedPath.length() - 1);
if (cachedLocations.find(pathWithoutSlash) != cachedLocations.end()) {
return pathWithoutSlash;
}
}
// If still no match, find the best prefix match
std::string bestMatch = "/";
size_t longestMatchLength = 0;
for (std::map<std::string, Location>::const_iterator it = cachedLocations.begin();
it != cachedLocations.end(); ++it) {
std::string locationPath = it->first;
// Ensure location path starts with '/'
if (locationPath[0] != '/') {
locationPath = "/" + locationPath;
}
// Remove trailing slash for comparison
if (locationPath.length() > 1 && locationPath[locationPath.length() - 1] == '/') {
locationPath = locationPath.substr(0, locationPath.length() - 1);
}
// Simple prefix matching
if (normalizedPath == locationPath ||
(normalizedPath.find(locationPath) == 0 &&
(locationPath == "/" ||
normalizedPath.length() == locationPath.length() ||
normalizedPath[locationPath.length()] == '/'))) {
if (locationPath.length() > longestMatchLength) {
bestMatch = it->first; // Use the original key
longestMatchLength = locationPath.length();
debug("[findBestLocationMatch]: New best match: " + bestMatch +
" (length: " + Utils::to_string(longestMatchLength) + ")");
}
}
}
debug("[findBestLocationMatch]: Best match for " + path + " is " + bestMatch);
return bestMatch;
}
// Non-const version - simply calls the const version
std::string FileManager::findBestLocationMatch(const std::string& path) {
// Call the const version using const_cast to avoid code duplication
return const_cast<const FileManager*>(this)->findBestLocationMatch(path);
}
bool FileManager::createDirectory(const std::string& path) {
debug("[createDirectory]: Attempting to create directory: " + path);
// Create directory with 0755 permissions (user: rwx, group: r-x, others: r-x)
if (mkdir(path.c_str(), 0755) == 0) {
debug("[createDirectory]: Directory created successfully: " + path);
return true;
}
// Check if directory already exists
if (errno == EEXIST) {
bool isDir = isDirectory(path);
debug("[createDirectory]: Directory already exists: " + path + ", isDir: " + (isDir ? "true" : "false"));
return isDir;
}
debug("[createDirectory]: Failed to create directory: " + path);
return false;
}
void FileManager::updateConfig(const Config& newConfig) {
debug("[FileManager]: Updating configuration to " + newConfig.get_server_name());
try {
// First, make a deep copy of the new config to work with
Config tempConfig(newConfig);
// Clear all cached locations before changing anything
cachedLocations.clear();
// Now assign the new config
config = tempConfig;
// Get a fresh reference to all locations from the updated config
const std::map<std::string, Location>& locations = config.get_all_Locations();
// Copy each location using a safer approach
for (std::map<std::string, Location>::const_iterator it = locations.begin();
it != locations.end(); ++it) {
// Create a new location and insert it into the map
cachedLocations.insert(std::make_pair(it->first, Location(it->second)));
}
debug("[FileManager]: Updated configuration with " +
Utils::to_string(cachedLocations.size()) + " locations");
}
catch (const std::exception& e) {
debug("[FileManager]: Exception updating configuration: " + std::string(e.what()));
}
}
std::string FileManager::resolveFilePath(const std::string& requestUri, const std::string& method) {
debug("[resolveFilePath]: Resolving path for: " + requestUri + " (Method: " + method + ")");
// Prevent path traversal attacks
if (detectPathTraversal(requestUri)) {
debug("[resolveFilePath]: Potential path traversal detected");
return "?forbidden";
}
// Normalize the path
std::string normalizedUri = normalizePath(requestUri);
// Find the best matching location
std::string bestMatch = findBestLocationMatch(normalizedUri);
if (bestMatch.empty()) {
debug("[resolveFilePath]: No location match found");
return "?notfound";
}
// Retrieve the location
std::map<std::string, Location>::const_iterator locIt = cachedLocations.find(bestMatch);
if (locIt == cachedLocations.end()) {
debug("[resolveFilePath]: Location not found in cache");
return "?notfound";
}
const Location& location = locIt->second;
// Check if this location has an upload path
bool hasUploadPath = !location.get_upload_path().empty();
//debug("[resolveFilePath]: Location has upload_path: " + (hasUploadPath ? "yes" : "no"));
// Handle upload locations specifically for POST and DELETE
if (hasUploadPath) {
//debug("[resolveFilePath]: Location has upload_path configured: " + location.get_upload_path());
// For POST requests, just return the URI for special handling
if (method == "POST") {
debug("[resolveFilePath]: POST request to upload location");
return requestUri;
}
// For DELETE requests, handle file deletion
if (method == "DELETE") {
std::string uploadPath = location.get_upload_path();
std::string filename = normalizedUri.substr(normalizedUri.find_last_of("/") + 1);
std::string specificPath = uploadPath + "/" + filename;
debug("[resolveFilePath]: DELETE request for uploaded file: " + specificPath);
return specificPath;
}
}
// For GET requests and other methods, use the location's root path
std::string rootPath = location.get_root();
debug("[resolveFilePath]: Root path from location: " + rootPath);
if (!rootPath.empty() && rootPath[0] != '/') {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
rootPath = std::string(cwd) + "/" + rootPath;
debug("[resolveFilePath]: Converted relative root to: " + rootPath);
}
}
if (!rootPath.empty() && rootPath[rootPath.length() - 1] != '/') {
rootPath += '/';
}
std::string relativePath = "";
// Handle special location blocks first
if (bestMatch != "/" && bestMatch.length() > 1) {
// For specific location blocks like "/css", "/js", etc.
debug("[resolveFilePath]: Found specific location match: " + bestMatch);
// Check if the request URI exactly matches the location or contains additional path components
if (normalizedUri.length() > bestMatch.length()) {
// Extract the part after the location path (e.g., for "/js/script.js", extract "script.js")
relativePath = normalizedUri.substr(bestMatch.length());
if (relativePath[0] == '/') {
relativePath = relativePath.substr(1); // Remove leading slash
}
} else {
// The URI exactly matches the location path (e.g., "/js" matches "/js")
relativePath = ""; // Empty relative path
}
} else {
// For the root location ("/"), try to find specialized locations first
bool foundSpecialized = false;
// Check if the URI starts with a path that matches a more specific location
for (std::map<std::string, Location>::const_iterator it = cachedLocations.begin();
it != cachedLocations.end(); ++it) {
std::string locPath = it->first;
// Skip the root location
if (locPath == "/") {
continue;
}
// Check if this location is a prefix of the request URI
if (normalizedUri.find(locPath) == 0) {
// If we have /js as location and /js/script.js as URI, use the js location
debug("[resolveFilePath]: Found specialized location for URI: " + locPath);
// Get the corresponding location block
const Location& specLocation = it->second;
// Use this location's root path instead
rootPath = specLocation.get_root();
debug("[resolveFilePath]: Using specialized root path: " + rootPath);
// Make it absolute if needed
if (!rootPath.empty() && rootPath[0] != '/') {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
rootPath = std::string(cwd) + "/" + rootPath;
debug("[resolveFilePath]: Converted specialized root to: " + rootPath);
}
}
// Ensure it ends with a slash
if (!rootPath.empty() && rootPath[rootPath.length() - 1] != '/') {
rootPath += '/';
}
// Get the part after the location path
if (normalizedUri.length() > locPath.length()) {
relativePath = normalizedUri.substr(locPath.length());
if (relativePath[0] == '/') {
relativePath = relativePath.substr(1);
}
}
foundSpecialized = true;
break;
}
}
// If no specialized location found, handle as regular root location
if (!foundSpecialized) {
// For the root location, preserve the original path structure but strip any prefixes
// like "/webserv/websites/var/www/html" that might match the root path
// Skip the leading slash
relativePath = normalizedUri.substr(1);
// Check if the URI starts with a prefix that matches the root path
std::string rootDir = rootPath;
if (!rootDir.empty() && rootDir[rootDir.size() - 1] == '/') {
rootDir.erase(rootDir.size() - 1); // Remove trailing slash for comparison
}
// Get just the directory name from the root path
std::string rootDirName = rootDir;
size_t lastSlash = rootDirName.find_last_of('/');
if (lastSlash != std::string::npos) {
rootDirName = rootDirName.substr(lastSlash + 1);
}
// If the URI starts with the root dir name (e.g., "chihuahua" or "webserv"), strip it
if (relativePath.find(rootDirName) == 0) {
debug("[resolveFilePath]: Stripping root dir name from path: " + rootDirName);
relativePath = relativePath.substr(rootDirName.length());
if (!relativePath.empty() && relativePath[0] == '/') {
relativePath = relativePath.substr(1);
}
}
}
}
debug("[resolveFilePath]: Relative path: " + relativePath);
std::string fullPath = rootPath + relativePath;
fullPath = normalizePath(fullPath);
debug("[resolveFilePath]: Full normalized path: " + fullPath);
// Special case: For locations with upload_path, check if we're trying to access an uploaded file
if (hasUploadPath && method == "GET") {
std::string uploadPath = location.get_upload_path();
// Make upload path absolute if needed
if (!uploadPath.empty() && uploadPath[0] != '/') {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
uploadPath = std::string(cwd) + "/" + uploadPath;
}
}
// If there's a relative path, check if it exists in the upload directory
if (!relativePath.empty()) {
std::string uploadFilePath = uploadPath + "/" + relativePath;
debug("[resolveFilePath]: Checking for file in upload directory: " + uploadFilePath);
if (fileExists(uploadFilePath)) {
debug("[resolveFilePath]: File found in upload directory");
return uploadFilePath;
}
}
// If we're accessing exactly the upload location (e.g., /uploads with no subpath)
// and we want to list the directory, check if upload_path exists as a directory
if (relativePath.empty() && isDirectory(uploadPath)) {
debug("[resolveFilePath]: Checking upload directory for autoindex: " + uploadPath);
// If autoindex is enabled, return the upload directory for listing
if (location.is_autoindex()) {
debug("[resolveFilePath]: Autoindex enabled for upload directory");
return uploadPath + "?directory";
}
}
}
// Check for CGI requests
bool isCgiRequest = false;
for (std::map<std::string, Location>::const_iterator it = cachedLocations.begin();
it != cachedLocations.end(); ++it) {
const Location& loc = it->second;
if (requestUri.find(it->first) == 0 && loc.is_cgi()) {
isCgiRequest = true;
debug("[resolveFilePath]: CGI request detected for location: " + it->first);
break;
}
}
if (isCgiRequest) {
debug("[resolveFilePath]: CGI request, using full path");
std::string cgiPath = rootPath + requestUri;
cgiPath = normalizePath(cgiPath);
debug("[resolveFilePath]: Returning full path for CGI: " + cgiPath);
return cgiPath;
}
if (!isPathSafe(fullPath)) {
debug("[resolveFilePath]: Unsafe path detected");
return "?forbidden";
}
if (isDirectory(fullPath)) {
debug("[resolveFilePath]: Path is a directory: " + fullPath);
//debug("[resolveFilePath]: Location autoindex: " + (location.is_autoindex() ? "on" : "off"));
if (method == "DELETE") {
debug("[resolveFilePath]: DELETE request on directory - checking if deletion is allowed");
return fullPath;
}
if (fullPath[fullPath.length() - 1] != '/') {
fullPath += '/';
}
std::vector<std::string> indexFiles;
if (!location.get_index().empty()) {
indexFiles.push_back(location.get_index());
}
indexFiles.push_back("index.html");
indexFiles.push_back("index.htm");
for (std::vector<std::string>::iterator it = indexFiles.begin(); it != indexFiles.end(); ++it) {
std::string indexPath = fullPath + *it;
if (fileExists(indexPath) && !isDirectory(indexPath)) {
debug("[resolveFilePath]: Found index file: " + indexPath);
return indexPath;
}
}
if (location.is_autoindex()) {
debug("[resolveFilePath]: Autoindex is enabled, returning directory marker");
return fullPath + "?directory";
} else {
debug("[resolveFilePath]: Autoindex is disabled, access forbidden");
return "?forbidden";
}
}
return fullPath;
}
bool FileManager::isPathSafe(const std::string& filePath) {
debug("[isPathSafe]: Checking path safety for: " + filePath);
// Check if the path is empty
if (filePath.empty()) {
debug("[isPathSafe]: Path is empty");
return false;
}
// Normalize the path
std::string normalizedPath = normalizePath(filePath);
debug("[isPathSafe]: Normalized path to check: " + normalizedPath);
// make sure that normalizedPath doesn't end with a slash
if (normalizedPath.length() > 1 && normalizedPath[normalizedPath.length() - 1] == '/') {
normalizedPath = normalizedPath.substr(0, normalizedPath.length() - 1);
debug("[isPathSafe]: Corrected trailing slash in normalized path: " + normalizedPath);
}
// Use an static array for suspicious patterns
static const char* suspiciousPatterns[] = {
"..", "./", "//", "\\", "~", "$", "|", ">", "<", "&", ";", "?", "*", "[", "]", "'", "\"", "`"
};
static const size_t numPatterns = sizeof(suspiciousPatterns) / sizeof(suspiciousPatterns[0]);
// Look for suspicious patterns
for (size_t i = 0; i < numPatterns; ++i) {
if (normalizedPath.find(suspiciousPatterns[i]) != std::string::npos) {
debug("[isPathSafe]: Suspicious pattern found: " + std::string(suspiciousPatterns[i]));
// don't return, some patterns are legitimate in certain contexts
}
}
// Check if the path is inside a root directory
bool foundMatch = false;
std::string matchedRoot;
// Check all the cached locations
for (std::map<std::string, Location>::const_iterator it = cachedLocations.begin();
it != cachedLocations.end(); ++it) {
std::string rootPath = it->second.get_root();
if (!rootPath.empty()) {
if (rootPath[0] != '/') {
char cwd[PATH_MAX];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
std::string currentDir(cwd);
rootPath = currentDir + "/" + rootPath;
debug("[isPathSafe]: Converted relative path to absolute: " + rootPath);
}
}
std::string normalizedRoot = normalizePath(rootPath);
// ELiminate slash if exists
if (normalizedRoot.length() > 1 && normalizedRoot[normalizedRoot.length() - 1] == '/') {
normalizedRoot = normalizedRoot.substr(0, normalizedRoot.length() - 1);
debug("[isPathSafe]: Corrected trailing slash in normalized root: " + normalizedRoot);
}
debug("[isPathSafe]: Checking with normalized root: " + normalizedRoot);
// Check if the path starts with the normalized root
if (normalizedPath == normalizedRoot ||
(normalizedPath.length() > normalizedRoot.length() &&
normalizedPath.substr(0, normalizedRoot.length()) == normalizedRoot &&
normalizedPath[normalizedRoot.length()] == '/')) {
foundMatch = true;
matchedRoot = normalizedRoot;
debug("[isPathSafe]: Path is within root directory: " + matchedRoot);
break;
}
}
}
if (!foundMatch) {
debug("[isPathSafe]: Path is not within any configured root directory");
return false;
}
// Verify if the file exists
if (access(normalizedPath.c_str(), F_OK) != 0) {
debug("[isPathSafe]: File does not exist: " + normalizedPath);
return true; // Allow non-existent files in safe paths
}
// Additional checks can be added here
if (isImportantFile(normalizedPath)) {
debug("[isPathSafe]: Important file requested: " + normalizedPath);
// Maybe more checks in the future
}
debug("[isPathSafe]: Path is safe: " + normalizedPath);
return true;
}
bool FileManager::createBackup(const std::string& filePath) {
std::string backupPath = filePath + ".backup." + getCurrentTimestamp();
debug("[createBackup]: Attempting to create backup: " + backupPath);
// Check if source file exists
if (access(filePath.c_str(), F_OK) != 0) {
debug("[createBackup]: Source file does not exist: " + filePath);
return false;
}
// Get file size
struct stat fileStat;
if (stat(filePath.c_str(), &fileStat) != 0) {
debug("[createBackup]: Cannot stat source file: " + filePath);
return false;
}
size_t fileSize = static_cast<size_t>(fileStat.st_size);
debug("[createBackup]: Source file size: " + Utils::to_string(fileSize) + " bytes");
// Handle empty files
if (fileSize == 0) {
debug("[createBackup]: Source file is empty, creating empty backup");
std::ofstream backupFile(backupPath.c_str(), std::ios::binary);
if (!backupFile.is_open()) {
debug("[createBackup]: Failed to create empty backup file");
return false;
}
backupFile.close();
return access(backupPath.c_str(), F_OK) == 0;
}
// For non-empty files, use the most robust method
std::ifstream src(filePath.c_str(), std::ios::binary);
if (!src.is_open()) {
debug("[createBackup]: Failed to open source file: " + filePath);
return false;
}
std::ofstream dst(backupPath.c_str(), std::ios::binary);
if (!dst.is_open()) {
debug("[createBackup]: Failed to create backup file: " + backupPath);
src.close();
return false;
}
// Method 1: Try the simple rdbuf() method first (works for most files)
bool success = false;
try {
dst << src.rdbuf();
// Check if streams are still good
if (!src.bad() && !dst.bad()) {
success = true;
debug("[createBackup]: Backup created using rdbuf() method");
} else {
debug("[createBackup]: rdbuf() method failed, trying chunked copy");
success = false;
}
} catch (const std::exception& e) {
debug("[createBackup]: Exception with rdbuf(): " + std::string(e.what()));
success = false;
}
// Method 2: If rdbuf() fails, try chunked copy (more reliable for problematic files)
if (!success) {
// Reset file streams
src.close();
dst.close();
src.open(filePath.c_str(), std::ios::binary);
dst.open(backupPath.c_str(), std::ios::binary | std::ios::trunc);
if (!src.is_open() || !dst.is_open()) {
debug("[createBackup]: Failed to reopen files for chunked copy");
unlink(backupPath.c_str());
return false;
}
// Copy in chunks for better reliability
const size_t CHUNK_SIZE = 8192; // 8KB chunks
char buffer[CHUNK_SIZE];
size_t totalCopied = 0;
while (src.read(buffer, CHUNK_SIZE) || src.gcount() > 0) {
std::streamsize bytesRead = src.gcount();
dst.write(buffer, bytesRead);
if (dst.fail()) {
debug("[createBackup]: Write failed during chunked copy");
src.close();
dst.close();
unlink(backupPath.c_str());
return false;
}
totalCopied += bytesRead;
}
debug("[createBackup]: Chunked copy completed, " + Utils::to_string(totalCopied) + " bytes copied");
success = (totalCopied == fileSize);
}
src.close();
dst.close();
if (!success) {
debug("[createBackup]: Both copy methods failed");
unlink(backupPath.c_str());
return false;
}
// Verify backup file size matches original
struct stat backupStat;
if (stat(backupPath.c_str(), &backupStat) == 0) {
if (static_cast<size_t>(backupStat.st_size) == fileSize) {
debug("[createBackup]: Backup verified successfully: " +
Utils::to_string(backupStat.st_size) + " bytes");
return true;
} else {
debug("[createBackup]: Size mismatch - original: " + Utils::to_string(fileSize) +
", backup: " + Utils::to_string(backupStat.st_size));
unlink(backupPath.c_str());
return false;
}
}
debug("[createBackup]: Cannot verify backup file");
unlink(backupPath.c_str());
return false;
}
std::string FileManager::getFileTypeDescription(const std::string& filePath) const {
std::string extension = "";
size_t dotPos = filePath.find_last_of(".");
if (dotPos != std::string::npos) {
extension = filePath.substr(dotPos + 1);
// Convert to lowercase for comparison
for (size_t i = 0; i < extension.size(); i++) {
extension[i] = tolower(extension[i]);
}
}
// Categorize file types
if (extension == "txt" || extension == "md" || extension == "log") {
return "text file";
} else if (extension == "jpg" || extension == "jpeg" || extension == "png" ||
extension == "gif" || extension == "bmp" || extension == "svg") {
return "image file";
} else if (extension == "pdf" || extension == "doc" || extension == "docx") {
return "document file";
} else if (extension == "html" || extension == "css" || extension == "js") {
return "web file";
} else if (extension == "zip" || extension == "tar" || extension == "gz") {
return "archive file";
} else if (extension == "exe" || extension == "bin") {
return "executable file";
} else if (extension.empty()) {
return "file with no extension";
} else {
return "file (." + extension + ")";
}
}
void FileManager::logDeletion(const std::string& filePath, const std::string& clientIp) {
std::ofstream logFile("deletion_log.txt", std::ios::app);
if (logFile.is_open()) {
std::string fileType = getFileTypeDescription(filePath);
logFile << getCurrentTimestamp() << " - " << fileType << " deleted: " << filePath
<< " by client: " << clientIp << std::endl;
logFile.close();
}
}
bool FileManager::isImportantFile(const std::string& filePath) {
for (std::vector<std::string>::const_iterator it = importantExtensions.begin();
it != importantExtensions.end(); ++it) {
if (filePath.length() >= it->length() &&
filePath.substr(filePath.length() - it->length()) == *it) {
return true;
}
}
return false;
}
std::string FileManager::getCurrentTimestamp() {
time_t now = time(NULL);
char timestamp[20];
strftime(timestamp, sizeof(timestamp), "%Y%m%d_%H%M%S", localtime(&now));
return std::string(timestamp);
}
std::string FileManager::generateHttpResponse(const std::string& path) {
std::string rootDirectory;
std::string contentType = "text/plain";
std::string filePath;
// Find best location match
std::map<std::string, Location> locations = config.get_all_Locations();
std::string bestLocation = findBestLocationMatch(path);
rootDirectory = config.find_location(bestLocation).get_root();
filePath = rootDirectory + path;
// Get content type based on file extension
contentType = getMimeType(filePath);
std::ifstream file(filePath.c_str(), std::ios::binary);
if (!file.is_open()) {
std::ifstream errorFile("public/404.html");
std::stringstream errorBuffer;
if (errorFile.is_open()) {
errorBuffer << errorFile.rdbuf(); // Load the 404.html file
} else {
errorBuffer << "<h1>404 Not Found</h1>"; // Default hardcoded error message
}
std::string errorContent = errorBuffer.str();
std::ostringstream errorResponse;
errorResponse << "HTTP/1.1 404 Not Found\r\n"
<< "Content-Type: text/html\r\n"
<< "Content-Length: " << errorContent.size() << "\r\n"
<< "Connection: close\r\n"
<< "\r\n"
<< errorContent;
return errorResponse.str();
}
std::stringstream buffer;
buffer << file.rdbuf();
std::string fileContent = buffer.str();
file.close();
std::ostringstream response;
response << "HTTP/1.1 200 OK\r\n"
<< "Content-Type: " << contentType << "\r\n"
<< "Content-Length: " << fileContent.size() << "\r\n"
<< "\r\n"
<< fileContent;
return response.str();
}
std::string FileManager::getMimeType(const std::string& filePath) {
// Get file extension
size_t dotPos = filePath.find_last_of('.');
if (dotPos == std::string::npos) {
return "text/plain"; // Default to text/plain if no extension
}
std::string extension = filePath.substr(dotPos);
// Look up extension in the MIME types map
std::map<std::string, std::string>::const_iterator it = mimeTypes.find(extension);
if (it != mimeTypes.end()) {
return it->second;
}
// Default content type if not found
return "application/octet-stream";
}
bool FileManager::fileExists(const std::string& filePath) {
struct stat fileStat;
return (stat(filePath.c_str(), &fileStat) == 0);
}
bool FileManager::isDirectory(const std::string& filePath) {
struct stat fileStat;
if (stat(filePath.c_str(), &fileStat) != 0) {
return false;
}
return S_ISDIR(fileStat.st_mode);
}
std::string FileManager::readFile(const std::string& filePath) {
std::ifstream file(filePath.c_str(), 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);
// Use a vector for binary data handling
std::vector<char> buffer(size);
if (size > 0) {
file.read(&buffer[0], size);
}
return std::string(buffer.begin(), buffer.end());
}
bool FileManager::writeFile(const std::string& filePath, const std::string& content) {
std::ofstream file(filePath.c_str(), std::ios::binary);
if (!file.is_open()) {
return false;
}
file << content;
return !file.fail();
}
bool FileManager::deleteFile(const std::string& filePath) {
debug("[deleteFile]: Attempting to delete file: " + filePath);
// Check if file exists first
if (!fileExists(filePath)) {
debug("[deleteFile]: File does not exist: " + filePath);
return false;
}
// Check write permissions on the file
if (access(filePath.c_str(), W_OK) != 0) {
debug("[deleteFile]: No write permission for file: " + filePath);
return false;
}
// Check write permissions on the parent directory
std::string parentDir = filePath.substr(0, filePath.find_last_of('/'));
if (!parentDir.empty() && access(parentDir.c_str(), W_OK) != 0) {
debug("[deleteFile]: No write permission for parent directory: " + parentDir);
return false;
}
// Create backup before deleting (your existing backup logic)
if (!createBackup(filePath)) {
debug("[deleteFile]: Backup creation failed, aborting deletion");
return false;
}
// Try to delete the file
int result = unlink(filePath.c_str()); // Use unlink() instead of remove()
if (result == 0) {
debug("[deleteFile]: File deleted successfully: " + filePath);
return true;
} else {
debug("[deleteFile]: Failed to delete file: " + filePath +
", errno: " + Utils::to_string(errno) + " (" + strerror(errno) + ")");
switch (errno) {
case EACCES:
debug("[deleteFile]: Permission denied");
break;
case EBUSY:
debug("[deleteFile]: File is busy or in use");
break;
case ENOENT:
debug("[deleteFile]: File not found");
break;
case EPERM:
debug("[deleteFile]: Operation not permitted");
break;
case EROFS:
debug("[deleteFile]: Read-only file system");
break;
default:
debug("[deleteFile]: Unknown error: " + Utils::to_string(errno));
break;
}
return false;
}
}
std::string FileManager::normalizePath(const std::string& path) {
debug("[normalizePath]: Normalizing path: " + path);
if (path.empty()) {
return path;
}
// Convert backslashes to forward slashes
std::string result = path;
size_t i = 0;
while ((i = result.find('\\', i)) != std::string::npos) {
result[i] = '/';
}
// Eliminate double slashes
i = 0;
while ((i = result.find("//", i)) != std::string::npos) {
result.erase(i, 1);
}
// Manual implementation to handle './' and '../'
std::string simplified;
bool isAbsolute = (result[0] == '/');
// Separate the path into components
std::string::size_type start = 0;
std::string::size_type end = 0;
std::vector<std::string> components;
while ((end = result.find('/', start)) != std::string::npos) {
std::string component = result.substr(start, end - start);
if (!component.empty() && component != "." && component != "..") {
simplified += "/" + component;
} else if (component == "..") {
// Eliminate the last component if there is one
std::string::size_type lastSlash = simplified.rfind('/');
if (lastSlash != std::string::npos && simplified.length() > 1) {
simplified.erase(lastSlash);
}
}
start = end + 1;
}
// Handle the last component
std::string lastComponent = result.substr(start);
if (!lastComponent.empty() && lastComponent != "." && lastComponent != "..") {
simplified += "/" + lastComponent;
} else if (lastComponent == "..") {
// Eliminate the last component if there is one
std::string::size_type lastSlash = simplified.rfind('/');
if (lastSlash != std::string::npos && simplified.length() > 1) {
simplified.erase(lastSlash);
}
}
// If the rout was absolute, add the leading '/'
if (isAbsolute && (simplified.empty() || simplified[0] != '/')) {
simplified = "/" + simplified;
} else if (simplified.empty()) {
simplified = "/";
}
// Handle the special case where the resulting path is empty
if (simplified.empty()) {