-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.cpp
More file actions
1052 lines (878 loc) · 39.4 KB
/
Copy pathClient.cpp
File metadata and controls
1052 lines (878 loc) · 39.4 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 "Client.hpp"
#include "Utils.hpp"
#include "Server.hpp"
#include <iostream>
#include <sys/socket.h>
#include <errno.h>
// Constructor
Client::Client(const Server &passiveServer, int clientFD)
: passiveServer(passiveServer),
clientFD(clientFD),
currentRequest(NULL),
state(STATE_IDLE), // Start in IDLE state, not READING_REQUEST
lastChunkSize(0),
lastActivityTime(time(NULL)),
responseBytesSent(0),
isMultiPart(false),
hasBeenServed(false),
keepAliveConnection(true), // Default to keep-alive
errorHasOccurred(false),
bodyComplete(false),
firstChunkProcessed(false),
location(NULL),
rawRequestData(""),
needFilenameExtraction(false)
{
debug("[Client]: Created new client with fd " + Utils::to_string(clientFD));
}
// Destructor - ensure proper cleanup
Client::~Client() {
debug("[Client]: Destroying client with fd " + Utils::to_string(clientFD));
// Clean up request if it exists
if (currentRequest) {
delete currentRequest;
currentRequest = NULL;
}
// Note: we don't close clientFD here as that's handled by ConnectionHandler
if (location) {
delete location;
location = NULL;
}
}
std::string Client::extractFilenameFromRawData(const std::string& rawData) {
debug("[Client]: Extracting filename from raw request data, size: " + Utils::to_string(rawData.size()));
// Show a preview of what we're working with (first 200 chars, cleaned)
std::string preview = rawData.substr(0, std::min(rawData.size(), static_cast<size_t>(200)));
debug("[Client]: Raw data preview: " + Utils::cleanForDebug(preview));
if (rawData.find("multipart/form-data") == std::string::npos) {
debug("[Client]: Not a multipart form data request");
return "uploaded_file";
}
// Look for filename in Content-Disposition header
size_t dispPos = rawData.find("filename=\"");
if (dispPos != std::string::npos) {
dispPos += 10; // Skip 'filename="'
size_t endPos = rawData.find("\"", dispPos);
if (endPos != std::string::npos && endPos > dispPos) {
std::string filename = rawData.substr(dispPos, endPos - dispPos);
debug("[Client]: Found quoted filename: '" + filename + "'");
// Clean the filename
filename = cleanFilename(filename);
if (!filename.empty() && filename != "uploaded_file") {
debug("[Client]: Successfully extracted filename: '" + filename + "'");
return filename;
}
}
}
// Try without quotes
dispPos = rawData.find("filename=");
if (dispPos != std::string::npos) {
dispPos += 9; // Skip 'filename='
// Find the end - could be semicolon, newline, or carriage return
size_t endPos = rawData.find_first_of(";\r\n ", dispPos);
if (endPos == std::string::npos) {
endPos = rawData.size();
}
if (endPos > dispPos) {
std::string filename = rawData.substr(dispPos, endPos - dispPos);
// Remove quotes if present
if (!filename.empty() && filename[0] == '"') {
filename = filename.substr(1);
if (!filename.empty() && filename[filename.size() - 1] == '"') {
filename = filename.substr(0, filename.size() - 1);
}
}
debug("[Client]: Found unquoted filename: '" + filename + "'");
filename = cleanFilename(filename);
if (!filename.empty() && filename != "uploaded_file") {
debug("[Client]: Successfully extracted filename: '" + filename + "'");
return filename;
}
}
}
// Look for Content-Disposition in the body
size_t bodyStart = rawData.find("\r\n\r\n");
if (bodyStart != std::string::npos) {
bodyStart += 4;
// Look for Content-Disposition in the body
size_t dispPosInBody = rawData.find("Content-Disposition:", bodyStart);
if (dispPosInBody != std::string::npos) {
// Look for filename in this Content-Disposition
size_t filenamePos = rawData.find("filename=\"", dispPosInBody);
if (filenamePos != std::string::npos && filenamePos < dispPosInBody + 500) {
filenamePos += 10;
size_t endPos = rawData.find("\"", filenamePos);
if (endPos != std::string::npos && endPos > filenamePos) {
std::string filename = rawData.substr(filenamePos, endPos - filenamePos);
debug("[Client]: Found filename in body: '" + filename + "'");
filename = cleanFilename(filename);
if (!filename.empty() && filename != "uploaded_file") {
debug("[Client]: Successfully extracted filename from body: '" + filename + "'");
return filename;
}
}
}
}
}
// If we still don't have a filename, we might need to extract it later when we have more data
extractedFilename = "uploaded_file"; // Use default for now
// Keep track of the fact that we need to try again later with more data
needFilenameExtraction = true;
debug("[Client]: No filename found, using default");
return "uploaded_file";
}
std::string Client::cleanFilename(const std::string& filename) {
if (filename.empty()) return "uploaded_file";
std::string cleaned = filename;
// Remove leading/trailing whitespace
while (!cleaned.empty() && (cleaned[0] == ' ' || cleaned[0] == '\t' ||
cleaned[0] == '\r' || cleaned[0] == '\n')) {
cleaned = cleaned.substr(1);
}
while (!cleaned.empty() && (cleaned[cleaned.size() - 1] == ' ' ||
cleaned[cleaned.size() - 1] == '\t' ||
cleaned[cleaned.size() - 1] == '\r' ||
cleaned[cleaned.size() - 1] == '\n')) {
cleaned = cleaned.substr(0, cleaned.size() - 1);
}
// Remove path separators (security)
size_t lastSlash = cleaned.find_last_of("/\\");
if (lastSlash != std::string::npos) {
cleaned = cleaned.substr(lastSlash + 1);
}
// Replace dangerous characters
std::string safeFilename;
for (size_t i = 0; i < cleaned.size(); i++) {
char c = cleaned[i];
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-') {
safeFilename += c;
} else {
safeFilename += '_';
}
}
// Ensure filename isn't empty and has reasonable length
if (safeFilename.empty() || safeFilename == "." || safeFilename == "_") {
return "uploaded_file";
}
if (safeFilename.length() > 255) {
safeFilename = safeFilename.substr(0, 255);
}
return safeFilename;
}
// Reset client for next request (preserving connection)
int Client::resetForNextRequest() {
debug("[Client]: Resetting client for next request, fd " + Utils::to_string(clientFD));
// Clean up previous request
if (currentRequest) {
delete currentRequest;
currentRequest = NULL;
}
// Reset buffers
totalBody.clear();
responseBuffer.clear();
responseBytesSent = 0;
rawRequestData.clear();
// Reset flags
isMultiPart = false;
bodyComplete = false;
hasBeenServed = false;
errorHasOccurred = false;
firstChunkProcessed = false; // Reset the flag
if (location) {
delete location;
location = NULL;
}
setState(STATE_IDLE);
return 0;
}
void Client::updateLastActivityTime() {
lastActivityTime = time(NULL);
}
// State management
void Client::setState(ClientState newState) {
debug("[Client]: State transition: " + stateToString(state) + " -> " + stateToString(newState) +
" (fd: " + Utils::to_string(clientFD) + ")");
state = newState;
}
ClientState Client::getState() const {
return state;
}
// Helper method to convert state to string for debugging
std::string Client::stateToString(ClientState state) const {
switch (state) {
case STATE_READING_REQUEST: return "READING_REQUEST";
case STATE_PROCESSING: return "PROCESSING";
case STATE_SENDING_RESPONSE: return "SENDING_RESPONSE";
case STATE_IDLE: return "IDLE";
case STATE_ERROR: return "ERROR";
default: return "UNKNOWN";
}
}
int Client::receiveRequest() {
debug("[Client]: Receiving data for client fd " + Utils::to_string(clientFD));
if (state == STATE_IDLE) {
setState(STATE_READING_REQUEST);
}
if (state != STATE_READING_REQUEST) {
debug("[Client]: receiveRequest called in incorrect state: " + stateToString(state));
return 0;
}
// Use a reasonably sized buffer for receiving
char buffer[16384];
// Non-blocking receive
ssize_t bytes_read = recv(clientFD, buffer, sizeof(buffer), MSG_DONTWAIT);
// Handle receive errors
if (bytes_read < 0) {
lastActivityTime = time(NULL);
lastChunkSize = bytes_read;
debug("[Client]: Error reading from socket: " + Utils::to_string(errno));
setError();
return 0;
// if (errno == EAGAIN || errno == EWOULDBLOCK) {
// debug("[Client]: No data available at the moment (EAGAIN/EWOULDBLOCK)");
// return 0;
// } else {
// debug("[Client]: Error reading from socket: " + Utils::to_string(errno));
// setError();
// return -1;
// }
}
// Handle zero-length reads (connection closed by peer)
if (bytes_read == 0) {
debug("[Client]: Connection closed by client");
// If we were in the middle of receiving a complete request, try to process it
if (currentRequest && isRequestComplete()) {
debug("[Client]: Connection closed but request appears complete, processing");
setState(STATE_PROCESSING);
return 1;
}
setError();
return -1;
}
// Add newly received data to our buffer
rawRequestData.append(buffer, bytes_read);
lastActivityTime = time(NULL);
lastChunkSize = bytes_read;
// Now process the data we have
if (!currentRequest) {
debug("[Client]: Creating new Request object");
// If we can't validate the headers yet, wait for more data
if (rawRequestData.find("\r\n\r\n") == std::string::npos) {
// Check if this is potentially an invalid request
if (rawRequestData.size() > 4096 ||
rawRequestData.find("\n\n") != std::string::npos ||
rawRequestData.find("\r\n\n") != std::string::npos) {
debug("[Client]: Likely invalid request format, sending 400 Bad Request");
ResponseBuilder builder;
builder.setStatus(400, "Bad Request");
builder.setContentType("text/plain");
builder.setBody("Invalid request format");
std::string response = builder.build();
setResponseBuffer(response);
setState(STATE_SENDING_RESPONSE);
return 0;
}
return(0);
}
std::string method, path, version;
HttpHeaders requestHeaders;
int errorCode = 0;
std::string errorMessage;
// Use validateHttpHeadersNoSend to check headers without sending
if (!passiveServer.validateHttpHeadersNoSend(rawRequestData.c_str(),
rawRequestData.length(),
method, path, version,
requestHeaders, errorCode, errorMessage)) {
// Validation failed, prepare error response
debug("[Client]: HTTP header validation failed: " + errorMessage);
// Create error response
ResponseBuilder builder;
if (errorCode == 405) {
builder.setHeader("Allow", "GET, POST, DELETE");
}
builder.setStatus(errorCode, errorMessage);
builder.setContentType("text/plain");
builder.setBody(errorMessage);
std::string response = builder.build();
setResponseBuffer(response);
setState(STATE_SENDING_RESPONSE);
return 0;
}
// Extract multipart filename if present
if (rawRequestData.find("multipart/form-data") != std::string::npos) {
extractedFilename = extractFilenameFromRawData(rawRequestData);
debug("[Client]: Extracted filename from multipart data: " + extractedFilename);
}
// Create Request object and validate headers
currentRequest = new Request(rawRequestData);
int result = currentRequest->preProcessRequest();
if (result != 0) {
debug("[Client]: Error preprocessing request headers");
return 0;
}
// Validate request method and other requirements
result = currentRequest->validateRequest();
if (result != 0) {
debug("[Client]: Request validation failed");
// Check if it's because of an unsupported method
std::string method = currentRequest->getMethod();
if (method != "GET" && method != "POST" && method != "DELETE") {
debug("[Client]: Unsupported method: " + method);
// Create and send 405 Method Not Allowed response
ResponseBuilder builder;
builder.setStatus(405, "Method Not Allowed");
builder.setHeader("Allow", "GET, POST, DELETE");
builder.setContentType("text/plain");
builder.setBody("Method " + method + " is not allowed");
std::string response = builder.build();
setResponseBuffer(response);
setState(STATE_SENDING_RESPONSE);
return 0;
}
// Other validation error
ResponseBuilder builder;
builder.setStatus(400, "Bad Request");
builder.setContentType("text/plain");
builder.setBody("Invalid request format");
std::string response = builder.build();
setResponseBuffer(response);
setState(STATE_SENDING_RESPONSE);
return 0;
}
// Request is valid, configure client
setParams();
// Extract the body from the raw request data
size_t headerEnd = rawRequestData.find("\r\n\r\n");
if (headerEnd != std::string::npos) {
headerEnd += 4; // Skip
if (headerEnd < rawRequestData.length()) {
// There's body data after the headers
totalBody = rawRequestData.substr(headerEnd);
debug("[Client]: Extracted body from request, size: " + Utils::to_string(totalBody.size()));
} else {
totalBody = ""; // Empty string
debug("[Client]: No body data in request yet");
}
}
// For multipart requests, we need special handling
if (isMultiPart) {
debug("[Client]: Request is multipart, need to handle body specially");
int multipartStatus = handleMultiPartBody();
if (multipartStatus == 0) {
// Body complete
debug("[Client]: Multipart body complete in first chunk");
setState(STATE_PROCESSING);
return 1; // Ready to process
} else if (multipartStatus < 0) {
// Error in multipart
debug("[Client]: Error in multipart body");
return 0;
} else {
// Need more data
debug("[Client]: Multipart body incomplete, waiting for more data");
return 0;
}
} else {
// Check if we've received the full request for non-multipart requests
if (isRequestComplete()) {
debug("[Client]: Non-multipart request complete, ready for processing");
setState(STATE_PROCESSING);
return 1; // Ready
} else {
debug("[Client]: Non-multipart request incomplete, waiting for more data");
return 0;
}
}
} else {
// Continui
size_t headerEnd = rawRequestData.find("\r\n\r\n");
if (headerEnd != std::string::npos) {
headerEnd += 4; // Skip
// Update body
totalBody = rawRequestData.substr(headerEnd);
debug("[Client]: Updated total body, new size: " + Utils::to_string(totalBody.size()));
}
// For multipart request
if (isMultiPart) {
debug("[Client]: Continuing multipart request, handling body");
int multipartStatus = handleMultiPartBody();
if (multipartStatus == 0) {
// Body complete
debug("[Client]: Multipart body complete after more data");
setState(STATE_PROCESSING);
return 1; // Ready
} else if (multipartStatus < 0) {
// Error
debug("[Client]: Error in multipart body");
return 0;
} else {
// Need more data
debug("[Client]: Multipart body still incomplete, waiting for more data");
return 0;
}
} else {
// For normal requests, check if complete
if (isRequestComplete()) {
debug("[Client]: Request now complete after more data, ready for processing");
setState(STATE_PROCESSING);
return 1;
} else {
debug("[Client]: Request still incomplete, waiting for more data");
return 0;
}
}
}
return 0;
}
bool Client::isRequestComplete() {
if (!currentRequest) {
return false;
}
if (currentRequest->getMethod() == "POST") {
HttpHeaders headers = currentRequest->getHeaders();
std::string contentLengthStr = headers.get("Content-Length");
if (!contentLengthStr.empty()) {
int contentLength = std::atoi(contentLengthStr.c_str());
debug("[Client]: Checking if request is complete: " +
Utils::to_string(totalBody.size()) + "/" +
Utils::to_string(contentLength) + " bytes");
return totalBody.size() >= static_cast<size_t>(contentLength);
}
}
return true;
}
// Non-blocking send method
int Client::sendResponse() {
if (state != STATE_SENDING_RESPONSE) {
debug("[Client]: sendResponse called in wrong state: " + stateToString(state));
return 0;
}
if (responseBuffer.empty()) {
debug("[Client]: No response buffer to send");
return 0;
}
if (responseBytesSent >= responseBuffer.size()) {
debug("[Client]: Response already fully sent");
// Response is complete
hasBeenServed = true;
// If keep-alive connection, reset for next request but keep connection open
if (keepAliveConnection) {
debug("[Client]: Connection is keep-alive, resetting for next request");
resetForNextRequest(); // This also sets state to IDLE
return 0; // Don't close the connection
} else {
// Not keep-alive, signal that we're done with this client
debug("[Client]: Connection is not keep-alive, can be closed");
return 1; // Signal to close connection
}
}
// Calculate what's left to send
const char* buffer = responseBuffer.c_str() + responseBytesSent;
size_t bytesRemaining = responseBuffer.size() - responseBytesSent;
// Try to send non-blockingly
ssize_t bytesSent = send(clientFD, buffer, bytesRemaining, MSG_DONTWAIT);
// Check for errors
if (bytesSent < 0) {
debug("[Client]: Error sending response: " + Utils::to_string(errno));
setError();
return 0;
// if (errno == EAGAIN || errno == EWOULDBLOCK) {
// // Would block, try again later
// debug("[Client]: Send would block, try again later");
// return 0;
// } else {
// // Actual error
// debug("[Client]: Error sending response: " + Utils::to_string(errno));
// setError();
// return -1;
// }
}
// Update bytes sent
responseBytesSent += bytesSent;
debug("[Client]: Sent " + Utils::to_string(bytesSent) + " bytes, " +
Utils::to_string(responseBytesSent) + "/" + Utils::to_string(responseBuffer.size()) + " total");
// Check if we're done
if (responseBytesSent >= responseBuffer.size()) {
debug("[Client]: Response fully sent");
hasBeenServed = true;
// If keep-alive connection, reset for next request but keep connection open
if (keepAliveConnection) {
debug("[Client]: Connection is keep-alive, resetting for next request");
resetForNextRequest(); // This also sets state to IDLE
return 0; // Don't close the connection
} else {
// Not keep-alive, signal that we're done with this client
debug("[Client]: Connection is not keep-alive, can be closed");
return 1; // Signal to close connection
}
}
// Still have more to send
return 0;
}
// Set response buffer for sending
void Client::setResponseBuffer(const std::string& response) {
responseBuffer = response;
responseBytesSent = 0;
debug("[Client]: Response buffer set, size: " + Utils::to_string(responseBuffer.size()) + " bytes");
// Update state to SENDING_RESPONSE
setState(STATE_SENDING_RESPONSE);
}
// Diagnostic version of setBody to understand what's happening
void Client::setBody(std::string buffer) {
debug("[Client]: Adding data to request body, buffer size: " + Utils::to_string(buffer.size()));
lastChunkSize = buffer.size();
if (!currentRequest) {
debug("[Client]: Cannot set body, no current request");
return;
}
// Special handling for binary data
bool hasBinaryBytes = false;
for (size_t i = 0; i < buffer.size(); i++) {
if (buffer[i] == '\0') {
hasBinaryBytes = true;
debug("[Client]: Buffer contains binary data with null bytes");
break;
}
}
if (!firstChunkProcessed) {
// **FIRST CHUNK ONLY** - Process HTTP headers
debug("[Client]: === FIRST CHUNK DIAGNOSTIC ===");
debug("[Client]: Buffer size: " + Utils::to_string(buffer.size()));
// Clean the buffer content for debug display
std::string bufferSample = buffer.substr(0, std::min(buffer.size(), static_cast<size_t>(300)));
debug("[Client]: Raw buffer content: " + Utils::cleanForDebug(bufferSample));
// Look for the header separator
size_t headerEnd = buffer.find("\r\n\r\n");
if (headerEnd != std::string::npos) {
debug("[Client]: Found header separator at position: " + Utils::to_string(headerEnd));
// Show what's before the separator (cleaned)
std::string httpHeaders = buffer.substr(0, headerEnd);
debug("[Client]: HTTP headers part: " + Utils::cleanForDebug(httpHeaders));
size_t bodyStart = headerEnd + 4;
if (bodyStart < buffer.size()) {
std::string bodyPartSample = buffer.substr(bodyStart, std::min(static_cast<size_t>(200), buffer.size() - bodyStart));
debug("[Client]: Body part starts with: " + Utils::cleanForDebug(bodyPartSample));
// Extract whatever body data we have in this first chunk
if (hasBinaryBytes) {
totalBody.clear();
for (size_t i = bodyStart; i < buffer.size(); i++) {
totalBody.push_back(buffer[i]);
}
debug("[Client]: Extracted binary body after headers, size: " + Utils::to_string(totalBody.size()));
} else {
totalBody = buffer.substr(bodyStart);
debug("[Client]: Extracted text body after headers, size: " + Utils::to_string(totalBody.size()));
}
} else {
debug("[Client]: Headers end at chunk boundary, no body data in first chunk");
// **CRITICAL**: Even if no body data, we need to initialize totalBody to indicate first chunk processed
totalBody = ""; // Initialize as empty string, not uninitialized
}
} else {
debug("[Client]: No header end marker found in first chunk, waiting for more data");
return;
}
// **CRITICAL**: Mark that we've processed the first chunk
firstChunkProcessed = true;
debug("[Client]: === END DIAGNOSTIC ===");
} else {
// **SUBSEQUENT CHUNKS** - All data is multipart body content
debug("[Client]: Subsequent chunk - appending raw multipart data (size: " + Utils::to_string(buffer.size()) + ")");
// Show what we're appending for debugging
std::string chunkPreview = buffer.substr(0, std::min(buffer.size(), static_cast<size_t>(100)));
debug("[Client]: Appending chunk preview: " + Utils::cleanForDebug(chunkPreview));
// Just append the raw data - NO header processing!
if (hasBinaryBytes) {
for (size_t i = 0; i < buffer.size(); i++) {
totalBody.push_back(buffer[i]);
}
} else {
totalBody.append(buffer);
}
debug("[Client]: Appended data to body, new total size: " + Utils::to_string(totalBody.size()));
}
// IMPROVED filename extraction - do this whenever we have enough data
if (isMultiPart && rawRequestData.size() > 200) {
std::string newFilename = extractFilenameFromRawData(rawRequestData);
if (newFilename != "uploaded_file" && newFilename != extractedFilename) {
debug("[Client]: Updated filename from '" + extractedFilename + "' to '" + newFilename + "'");
extractedFilename = newFilename;
}
}
debug("[Client]: Current extracted filename: '" + extractedFilename + "'");
}
bool Client::hasUploadTimedOut() const {
time_t currentTime = time(NULL);
time_t idleTime = currentTime - lastActivityTime;
return (idleTime > UPLOAD_TIMEOUT_SECONDS);
}
void Client::forceCompleteMultipartUpload() {
if (isMultiPart && !bodyComplete) {
debug("[Client]: Forcing completion of multipart upload");
bodyComplete = true;
setState(STATE_PROCESSING);
}
}
// Set client parameters based on request
void Client::setParams() {
if (!currentRequest) {
debug("[Client]: Cannot set params, no request object");
return;
}
// Get headers from the request
HttpHeaders headers = currentRequest->getHeaders();
// Check content type for multipart
std::string contentType = headers.get("Content-Type");
isMultiPart = (contentType.find("multipart/form-data") != std::string::npos);
// Extract boundary if multipart
if (isMultiPart) {
size_t boundaryPos = contentType.find("boundary=");
if (boundaryPos != std::string::npos) {
std::string boundaryValue = contentType.substr(boundaryPos + 9);
// Remove any trailing whitespace or quotes
boundaryValue.erase(boundaryValue.find_last_not_of(" \n\r\t\"") + 1);
// Remove any leading whitespace or quotes
boundaryValue.erase(0, boundaryValue.find_first_not_of(" \n\r\t\""));
// Store the boundary both with and without the prefix
//boundary = boundaryValue;
//boundaryWithPrefix = "--" + boundaryValue;
//debug("[Client]: Extracted boundary: '" + boundary + "' and prefix form: '" + boundaryWithPrefix + "'");
} else {
debug("[Client]: Multipart content type without boundary parameter");
isMultiPart = false; // Can't process multipart without boundary
}
}
// Check connection type for keep-alive
std::string connection = headers.get("Connection");
bool isHttp11 = (currentRequest->getVersion() == "HTTP/1.1");
// Set keep-alive property based on Connection header and HTTP version
// HTTP/1.1 defaults to keep-alive unless "Connection: close" is specified
// HTTP/1.0 defaults to close unless "Connection: keep-alive" is specified
if (isHttp11) {
keepAliveConnection = (connection.find("close") == std::string::npos);
} else {
keepAliveConnection = (connection.find("keep-alive") != std::string::npos);
}
// Find matching location for request
std::string requestUri = currentRequest->getUri();
std::cout << "[Client]: Finding best location match for URI: " << requestUri << std::endl;
std::string bestMatch = passiveServer.getFileManager().findBestLocationMatch(requestUri);
if (!bestMatch.empty()) {
std::cout << "[Client]: Best location match found: " << bestMatch << std::endl;
const std::map<std::string, Location>& locations = passiveServer.getConfig().get_all_Locations();
std::cout << "[Client]: Total locations available: " << locations.size() << std::endl;
std::map<std::string, Location>::const_iterator it = locations.find(bestMatch);
if (it != locations.end()) {
std::cout << "[Client]: Setting location for path: " << bestMatch << std::endl;
// Make a complete copy instead of using a pointer
if (location) {
delete location; // Delete any existing location
}
try {
// Create a deep copy of the location
location = new Location();
*location = it->second; // Use assignment operator instead of copy constructor
std::cout << "[Client]: Location permissions after copy - GET: "
<< (location->get_allowed() ? "yes" : "no")
<< ", POST: " << (location->post_allowed() ? "yes" : "no")
<< ", DELETE: " << (location->delete_allowed() ? "yes" : "no") << std::endl;
} catch (const std::exception& e) {
std::cout << "[Client]: Exception copying location: " << e.what() << std::endl;
location = NULL; // Ensure we don't have a dangling pointer
}
} else {
std::cout << "[Client]: Location not found in config: " << bestMatch << std::endl;
}
} else {
std::cout << "[Client]: No location match found for: " << requestUri << std::endl;
}
debug("[Client]: Params set - MultiPart: " + std::string(isMultiPart ? "yes" : "no") +
", KeepAlive: " + std::string(keepAliveConnection ? "yes" : "no") +
", Location: " + (location ? bestMatch : "none"));
}
// Handle error state
void Client::setError() {
debug("[Client]: Setting error state for client fd " + Utils::to_string(clientFD));
errorHasOccurred = true;
setState(STATE_ERROR);
}
// Handle multipart body data
int Client::handleMultiPartBody() {
if (!currentRequest) {
debug("[Client]: Cannot handle multipart body, no request object");
return -1;
}
// Get content length from headers
HttpHeaders headers = currentRequest->getHeaders();
std::string contentLengthStr = headers.get("Content-Length");
if (contentLengthStr.empty()) {
debug("[Client]: No Content-Length header for multipart request");
setError();
return -1;
}
// Parse content length
int contentLength = std::atoi(contentLengthStr.c_str());
// Calculate actual body size
size_t bodySize = totalBody.size();
debug("[Client]: Checking multipart body: " + Utils::to_string(bodySize) + "/" +
Utils::to_string(contentLength) + " bytes");
// If filename is still the default and we have enough data, try to extract it again
if (extractedFilename == "uploaded_file" && bodySize > 1000) {
// Look for Content-Disposition in the body
size_t dispPos = totalBody.find("Content-Disposition:");
if (dispPos != std::string::npos) {
// Look for filename in this Content-Disposition
size_t filenamePos = totalBody.find("filename=\"", dispPos);
if (filenamePos != std::string::npos && filenamePos < dispPos + 500) {
filenamePos += 10; // Skip 'filename="'
size_t endPos = totalBody.find("\"", filenamePos);
if (endPos != std::string::npos && endPos > filenamePos) {
std::string filename = totalBody.substr(filenamePos, endPos - filenamePos);
debug("[Client]: Found filename in multipart body: '" + filename + "'");
filename = cleanFilename(filename);
if (!filename.empty() && filename != "uploaded_file") {
debug("[Client]: Successfully extracted filename from body: '" + filename + "'");
extractedFilename = filename;
}
}
}
}
}
// Check if we've been waiting too long
time_t currentTime = time(NULL);
time_t idleTime = currentTime - lastActivityTime;
// Check for boundary markers
std::string boundary = "--" + currentRequest->getBoundary();
// Check if the last part of the buffer is a partial boundary
if (bodySize >= boundary.size() &&
totalBody.substr(totalBody.size() - boundary.size()) == boundary) {
debug("[Client]: Found potential partial boundary at end of buffer, waiting for more data");
return 1; // Need more data
}
// Check for end boundary patterns
std::string endBoundary1 = boundary + "--";
std::string endBoundary2 = boundary + "--\r\n";
std::string endBoundary3 = boundary + "--\n";
std::string endBoundary4 = "\r\n" + boundary + "--";
std::string endBoundary5 = "\n" + boundary + "--";
if (totalBody.find(endBoundary1) != std::string::npos ||
totalBody.find(endBoundary2) != std::string::npos ||
totalBody.find(endBoundary3) != std::string::npos ||
totalBody.find(endBoundary4) != std::string::npos ||
totalBody.find(endBoundary5) != std::string::npos) {
debug("[Client]: Found end boundary marker, body is complete!");
bodyComplete = true;
return 0;
}
// Check if we've received the full content length
if (bodySize >= static_cast<size_t>(contentLength)) {
debug("[Client]: Received full content length, marking as complete");
bodyComplete = true;
return 0;
}
// Add a check for binary data with potential null bytes
bool hasBinaryData = false;
for (size_t i = 0; i < std::min(totalBody.size(), static_cast<size_t>(1024)); i++) {
if (totalBody[i] == '\0') {
hasBinaryData = true;
debug("[Client]: Binary data detected with null bytes - using lenient checks");
break;
}
}
static size_t lastCheckedSize = 0;
if (bodySize > lastCheckedSize + 10240) { // 10KB progress
debug("[Client]: Upload progressing steadily, resetting idle timer");
lastActivityTime = currentTime; // Reset the idle timer
lastCheckedSize = bodySize;
}
if (lastChunkSize > 0 && idleTime < 10) { // Recently received data
debug("[Client]: Still receiving data actively, continuing upload");
return 1; // Need more data
}
if (hasBinaryData || idleTime > 10) {
if (bodySize >= static_cast<size_t>(contentLength * 0.98)) {
debug("[Client]: Nearly complete, accepting upload");
bodyComplete = true;
return 0;
}
}
// If we've been waiting for more than UPLOAD_TIMEOUT_SECONDS and have at least 95% of the data
if (idleTime > UPLOAD_TIMEOUT_SECONDS && bodySize >= static_cast<size_t>(contentLength * 0.95)) {
debug("[Client]: Upload timed out after " + Utils::to_string(idleTime) +
" seconds, but we have " + Utils::to_string(bodySize) + " of " +
Utils::to_string(contentLength) + " bytes, accepting as complete");
bodyComplete = true;
return 0;
}
if (lastChunkSize < 1000 && bodySize >= static_cast<size_t>(contentLength * 0.95)) {
debug("[Client]: Last chunk was small (" + Utils::to_string(lastChunkSize) +
" bytes) and we've received " + Utils::to_string(bodySize) + " out of " +
Utils::to_string(contentLength) + ", marking as complete");
bodyComplete = true;
return 0; // Body complete, ready to process
}
// For very slow uploads that might hit timeout but are still making progress
if (idleTime > UPLOAD_TIMEOUT_SECONDS/2 && lastChunkSize > 0) {
debug("[Client]: Slow upload in progress, extending timeout");
lastActivityTime = currentTime - UPLOAD_TIMEOUT_SECONDS/4; // Reset to 1/4 of timeout
}
debug("[Client]: Multipart body incomplete: " + Utils::to_string(bodySize) + "/" +
Utils::to_string(contentLength) + " bytes, waiting for more data");
return 1; // Need more data
}
// Get client status
int Client::getClientStatus() {
if (errorHasOccurred) {
return -1; // Error
}
if (isMultiPart && !bodyComplete && state == STATE_READING_REQUEST) {
return 1; // Incomplete, waiting for more data
}
return 0; // Ready to be processed
}
// Getters
int Client::getClientFD() const {