-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathVirtualServer.cpp
1100 lines (949 loc) · 42.9 KB
/
VirtualServer.cpp
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 <fcntl.h>
#include "VirtualServer.hpp"
#include "EventHandler.hpp"
#include "EventContext.hpp"
#include "constant.hpp"
static void insertToStringMap(StringMap& envMap, std::string key, std::string value);
using HTTP::Status;
// HTTP status code
const Status Status::_array[] = {
{ "000", "default" },
{ "200", "ok" },
{ "201", "created" },
{ "301", "moved permanently" },
{ "308", "Permanent Redirect" },
{ "400", "bad request" },
{ "404", "not found" },
{ "405", "method not allowed" },
{ "411", "length required" },
{ "413", "payload too large" },
{ "500", "internal server error" },
};
static void updateContentType(const std::string& name, std::string& type);
static void updateExtension(const std::string& name, std::string& extension);
static void updateBodyString(HTTP::Status::Index index, const char* description, std::string& bodyString);
// Default constructor of VirtualServer.
// - Parameters
// portNumber: The port number.
// serverName: The server name.
// clientMaxBodySize: The client max body size
VirtualServer::VirtualServer()
: _portNumber(0),
_name(""),
_clientMaxBodySize(DEFAULT_CLIENT_MAX_BODY_SIZE)
{
}
// Constructor of VirtualServer.
// - Parameters
// portNumber: The port number.
// serverName: The server name.
// clientMaxBodySize: The client max body size
VirtualServer::VirtualServer(port_t portNumber, const std::string& name)
: _portNumber(portNumber),
_name(name),
_clientMaxBodySize(DEFAULT_CLIENT_MAX_BODY_SIZE) {
}
// update error page of virtual server.
// - Parameters
// statusCode: status code in std::string.
// filePath: the path of file to read.
// - Return: upon successful completion a value of 0 is returned.
// otherwise, a value of -1 is returned.
int VirtualServer::updateErrorPage(EventHandler& eventHandler, const std::string& statusCode, const std::string& filePath) {
const int targetFileFD = open(filePath.c_str(), O_RDONLY);
if (targetFileFD == -1)
return -1;
if (fcntl(targetFileFD, F_SETFL, O_NONBLOCK) == -1) {
close(targetFileFD);
return -1;
}
std::pair<const std::string&, VirtualServer&>* tempData = new std::pair<const std::string&, VirtualServer&>(statusCode, *this);
eventHandler.addEvent(EVFILT_READ, targetFileFD, EventContext::EV_SetVirtualServerErrorPage, tempData);
return 0;
}
// event function reading a file and setting error page.
// - Parameters context: context of event.
// - Return: result of event.
EventContext::EventResult VirtualServer::eventSetVirtualServerErrorPage(EventContext& context) {
char buf[BUF_SIZE];
ssize_t readByteCount;
const int targetFileFD = context.getIdent();
std::pair<const std::string&, VirtualServer&>* data = static_cast<std::pair<const std::string&, VirtualServer&>*>(context.getData());
const std::string& statusCode = data->first;
readByteCount = read(targetFileFD, buf, BUF_SIZE - 1);
if (readByteCount == -1) {
delete data;
delete &context;
close(targetFileFD);
return EventContext::ER_Done;
}
buf[readByteCount] = '\0';
this->_errorPage[statusCode].append(buf);
if (readByteCount == BUF_SIZE - 1)
return EventContext::ER_Continue;
else {
delete data;
delete &context;
close(targetFileFD);
return EventContext::ER_Done;
}
}
// Process request from client.
// - Parameters
// clientConnection: The connection of client requesting process.
// kqueueFD: The kqueue fd is where to add write event for response.
// - Return: See the type definition.
VirtualServer::ReturnCode VirtualServer::processRequest(Connection& clientConnection, EventHandler& eventHandler) {
const Request& request = clientConnection.getRequest();
ReturnCode returnCode;
if (request.isParsingFail()) {
returnCode = this->set400Response(clientConnection);
if (returnCode == RC_ERROR)
returnCode = this->set500Response(clientConnection);
return returnCode;
}
else if (request.isLengthRequired()) {
returnCode = this->set411Response(clientConnection);
if (returnCode == RC_ERROR)
returnCode = this->set500Response(clientConnection);
return returnCode;
}
switch(request.getMethod()) {
case HTTP::RM_GET:
returnCode = processGET(clientConnection, eventHandler);
break;
case HTTP::RM_POST:
returnCode = processPOST(clientConnection, eventHandler);
break;
case HTTP::RM_DELETE:
returnCode = processDELETE(clientConnection);
break;
case HTTP::RM_PUT:
returnCode = set201Response(clientConnection);
break;
default:
returnCode = set405Response(clientConnection, NULL);
break;
}
if (returnCode == RC_ERROR)
returnCode = this->set500Response(clientConnection);
return returnCode;
}
// get matching location for request.
// - Parameters request: request to search.
// - Return: matching location, if no location match, NULL would be returned.
const Location* VirtualServer::getMatchingLocation(const Request& request) {
const std::string& targetResourceURI = request.getTargetResourceURI();
std::map<std::string, const Location*, std::greater<std::string> > matchingLongestRoute;
for (std::vector<Location*>::const_iterator iter = this->_location.begin(); iter != this->_location.end(); ++iter) {
const Location* const & locationPointer = *iter;
if (locationPointer->isRouteMatch(targetResourceURI))
matchingLongestRoute.insert(make_pair(locationPointer->getRoute(), locationPointer));
}
if (matchingLongestRoute.size())
return matchingLongestRoute.begin()->second;
return NULL;
}
// Detect CGI file using file extension
bool VirtualServer::detectCGI(Connection& clientConnection, const Location& location, const std::string& targetResourceURI) {
std::string targetExtension;
std::vector<std::string> cgiExtensionOnLocation = location.getCGIExtension();
std::vector<std::string>::iterator findResult;
updateExtension(targetResourceURI, targetExtension);
findResult = std::find(
cgiExtensionOnLocation.begin(),
cgiExtensionOnLocation.end(),
targetExtension
);
if ( findResult == cgiExtensionOnLocation.end()) {
return false;
} else {
clientConnection.parseCGIurl(targetResourceURI, targetExtension);
this->fillCGIEnvMap(clientConnection, location);
return true;
}
}
// Process GET request.
// - Parameters request: The request to process.
// - Return(None)
VirtualServer::ReturnCode VirtualServer::processGET(Connection& clientConnection, EventHandler& eventHandler) {
const Request& request = clientConnection.getRequest();
const std::string& targetResourceURI = request.getTargetResourceURI();
struct stat buf;
std::string targetRepresentationURI;
if (this->_others.find("return") != this->_others.end()) {
if (this->_others.find("return")->second.front().compare("308") == 0)
return this->set308Response(clientConnection, this->_others);
return this->set301Response(clientConnection, this->_others);
}
const Location* locationPointer = this->getMatchingLocation(request);
if (locationPointer == NULL)
return this->set404Response(clientConnection);
const Location& location = *locationPointer;
const std::map<std::string, std::vector<std::string> > &locOthers = location.getOtherDirective();
if (locOthers.find("return") != locOthers.end()) {
if (locOthers.find("return")->second.front().compare("308") == 0)
return this->set308Response(clientConnection, locOthers);
return this->set301Response(clientConnection, locOthers);
}
if (!location.isRequestMethodAllowed(request.getMethod()))
return this->set405Response(clientConnection, &location);
int targetClientMaxBodysize = location.getClientMaxBodySize();
if (targetClientMaxBodysize < 0)
targetClientMaxBodysize = this->_clientMaxBodySize;
if (request.getBody().length() > static_cast<std::string::size_type>(targetClientMaxBodysize))
return this->set413Response(clientConnection);
location.updateRepresentationPath(targetResourceURI, targetRepresentationURI);
if (this->detectCGI(clientConnection, location, targetResourceURI) == true) {
return this->passCGI(clientConnection, location);
}
if (stat(targetRepresentationURI.c_str(), &buf) == 0
&& (buf.st_mode & S_IFREG) != 0) {
this->appendStatusLine(clientConnection, Status::I_200);
this->appendDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Type: ");
std::string type;
updateContentType(targetRepresentationURI, type);
clientConnection.appendResponseMessage(type);
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << buf.st_size;
clientConnection.appendResponseMessage(oss.str().c_str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Last-Modified: ");
const struct timespec lastModified = buf.st_mtimespec;
const struct tm tm = *gmtime(&lastModified.tv_sec);
char lastModifiedString[BUF_SIZE];
strftime(lastModifiedString, BUF_SIZE, "%a, %d %b %Y %H:%M:%S GMT", &tm);
clientConnection.appendResponseMessage(lastModifiedString);
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
if (buf.st_size == 0)
return RC_SUCCESS;
const int targetFileFD = open(targetRepresentationURI.c_str(), O_RDONLY);
if (targetFileFD == -1)
return RC_ERROR;
if (fcntl(targetFileFD, F_SETFL, O_NONBLOCK) == -1) {
close(targetFileFD);
return RC_ERROR;
}
eventHandler.addEvent(EVFILT_READ, targetFileFD, EventContext::EV_GETResponse, &clientConnection);
clientConnection.initResponseBodyBySize(buf.st_size);
return RC_IN_PROGRESS;
}
const std::string absoluteIndexPath = targetRepresentationURI + "/" + location.getIndex();
if (stat(absoluteIndexPath.c_str(), &buf) == 0
&& (buf.st_mode & S_IFREG) != 0) {
this->appendStatusLine(clientConnection, Status::I_200);
this->appendDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Type: ");
std::string type;
updateContentType(location.getIndex(), type);
clientConnection.appendResponseMessage(type);
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << buf.st_size;
clientConnection.appendResponseMessage(oss.str().c_str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Last-Modified: ");
const struct timespec lastModified = buf.st_mtimespec;
const struct tm tm = *gmtime(&lastModified.tv_sec);
char lastModifiedString[BUF_SIZE];
strftime(lastModifiedString, BUF_SIZE, "%a, %d %b %Y %H:%M:%S GMT", &tm);
clientConnection.appendResponseMessage(lastModifiedString);
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
if (buf.st_size == 0)
return RC_SUCCESS;
const int targetFileFD = open(absoluteIndexPath.c_str(), O_RDONLY);
if (targetFileFD == -1)
return RC_ERROR;
if (fcntl(targetFileFD, F_SETFL, O_NONBLOCK) == -1) {
close(targetFileFD);
return RC_ERROR;
}
eventHandler.addEvent(EVFILT_READ, targetFileFD, EventContext::EV_GETResponse, &clientConnection);
clientConnection.initResponseBodyBySize(buf.st_size);
return RC_IN_PROGRESS;
}
if (location.getAutoIndex()
&& stat(targetRepresentationURI.c_str(), &buf) == 0
&& (buf.st_mode & S_IFDIR) != 0)
return this->setListResponse(clientConnection, targetRepresentationURI.c_str());
return this->set404Response(clientConnection);
}
// event function reading a file and responding of GET request.
// - Parameters context: context of event.
// - Return: result of event.
EventContext::EventResult VirtualServer::eventGETResponse(EventContext& context, EventHandler& eventHandler) {
char buf[BUF_SIZE];
ssize_t readByteCount;
const int targetFileFD = context.getIdent();
Connection& clientConnection = *static_cast<Connection*>(context.getData());
readByteCount = read(targetFileFD, buf, BUF_SIZE);
if (readByteCount == -1) {
delete &context;
close(targetFileFD);
return EventContext::ER_Done;
}
clientConnection.memcpyResponseMessage(buf, readByteCount);
if (!clientConnection.isResponseReadAllFile())
return EventContext::ER_Continue;
else {
delete &context;
close(targetFileFD);
const int clientSocketFD = clientConnection.getIdent();
eventHandler.addEvent(EVFILT_WRITE, clientSocketFD, EventContext::EV_Response, &clientConnection);
return EventContext::ER_Done;
}
}
// Process POST request.
// - Parameters request: The request to process.
// - Return(None)
VirtualServer::ReturnCode VirtualServer::processPOST(Connection& clientConnection, EventHandler& eventHandler) {
const Request& request = clientConnection.getRequest();
const std::string& targetResourceURI = request.getTargetResourceURI();
std::string targetRepresentationURI;
if (this->_others.find("return") != this->_others.end()) {
if (this->_others.find("return")->second.front().compare("308") == 0)
return this->set308Response(clientConnection, this->_others);
return this->set301Response(clientConnection, this->_others);
}
const Location* locationPointer = this->getMatchingLocation(request);
if (locationPointer == NULL)
return this->set400Response(clientConnection);
const Location& location = *locationPointer;
const std::map<std::string, std::vector<std::string> > &locOthers = location.getOtherDirective();
if (locOthers.find("return") != locOthers.end()) {
if (locOthers.find("return")->second.front().compare("308") == 0)
return this->set308Response(clientConnection, locOthers);
return this->set301Response(clientConnection, locOthers);
}
if (!location.isRequestMethodAllowed(request.getMethod()))
return this->set405Response(clientConnection, &location);
int targetClientMaxBodysize = location.getClientMaxBodySize();
if (targetClientMaxBodysize < 0)
targetClientMaxBodysize = this->_clientMaxBodySize;
if (request.getBody().length() > static_cast<std::string::size_type>(targetClientMaxBodysize))
return this->set413Response(clientConnection);
location.updateRepresentationPath(targetResourceURI, targetRepresentationURI);
if (this->detectCGI(clientConnection, location, targetResourceURI) == true) {
return this->passCGI(clientConnection, location);
}
const int targetFileFD = open(targetRepresentationURI.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (targetFileFD == -1)
return RC_ERROR;
if (fcntl(targetFileFD, F_SETFL, O_NONBLOCK) == -1) {
close(targetFileFD);
return RC_ERROR;
}
eventHandler.addEvent(EVFILT_WRITE, targetFileFD, EventContext::EV_POSTResponse, &clientConnection);
return RC_IN_PROGRESS;
}
// event function writing a file and responding of POST request.
// - Parameters context: context of event.
// - Return: result of event.
EventContext::EventResult VirtualServer::eventPOSTResponse(EventContext& context, EventHandler& eventHandler) {
typedef std::pair<std::string, const char*> ElementType;
typedef std::map<int, ElementType> SendBeginMapType;
static SendBeginMapType sendBeginMap;
const int targetFileFD = context.getIdent();
Connection& clientConnection = *static_cast<Connection*>(context.getData());
ElementType* element;
const SendBeginMapType::iterator iter = sendBeginMap.find(targetFileFD);
if (iter == sendBeginMap.end()) {
element = &sendBeginMap[targetFileFD];
element->first = clientConnection.getRequest().getBody();
element->second = &element->first[0];
}
else {
element = &iter->second;
}
const char* const sendBegin = element->second;
std::size_t lengthToSend = std::strlen(sendBegin);
ssize_t writeByteCount;
writeByteCount = write(targetFileFD, sendBegin, lengthToSend);
if (static_cast<std::size_t>(writeByteCount) != lengthToSend) {
element->second += writeByteCount;
return EventContext::ER_Continue;
}
sendBeginMap.erase(targetFileFD);
delete &context;
close(targetFileFD);
this->appendStatusLine(clientConnection, Status::I_201);
std::string bodyString;
this->updateBodyString(Status::I_201, "File created.", bodyString);
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << bodyString.length();
clientConnection.appendResponseMessage(oss.str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
const int clientSocketFD = clientConnection.getIdent();
eventHandler.addEvent(EVFILT_WRITE, clientSocketFD, EventContext::EV_Response, &clientConnection);
return EventContext::ER_Done;
}
// Process DELETE request.
// - Parameters request: The request to process.
// - Return(None)
VirtualServer::ReturnCode VirtualServer::processDELETE(Connection& clientConnection) {
const Request& request = clientConnection.getRequest();
const std::string& targetResourceURI = request.getTargetResourceURI();
struct stat buf;
std::string targetRepresentationURI;
if (this->_others.find("return") != this->_others.end()) {
if (this->_others.find("return")->second.front().compare("308") == 0)
return this->set308Response(clientConnection, this->_others);
return this->set301Response(clientConnection, this->_others);
}
const Location* locationPointer = this->getMatchingLocation(request);
if (locationPointer == NULL)
return this->set404Response(clientConnection);
const Location& location = *locationPointer;
const std::map<std::string, std::vector<std::string> > &locOthers = location.getOtherDirective();
if (locOthers.find("return") != locOthers.end()) {
if (locOthers.find("return")->second.front().compare("308") == 0)
return this->set308Response(clientConnection, locOthers);
return this->set301Response(clientConnection, locOthers);
}
if (!location.isRequestMethodAllowed(request.getMethod()))
return this->set405Response(clientConnection, &location);
int targetClientMaxBodysize = location.getClientMaxBodySize();
if (targetClientMaxBodysize < 0)
targetClientMaxBodysize = this->_clientMaxBodySize;
if (request.getBody().length() > static_cast<std::string::size_type>(targetClientMaxBodysize))
return this->set413Response(clientConnection);
location.updateRepresentationPath(targetResourceURI, targetRepresentationURI);
if (stat(targetRepresentationURI.c_str(), &buf) == 0) {
if (unlink(targetRepresentationURI.c_str()) == -1)
return RC_ERROR;
this->appendStatusLine(clientConnection, Status::I_200);
std::string bodyString;
this->updateBodyString(Status::I_200, "File deleted.", bodyString);
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << bodyString.length();
clientConnection.appendResponseMessage(oss.str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
return this->set404Response(clientConnection);
}
// Set status line to response of clientConnection.
// - Parameters clientConnection: The client connection.
// - Return(None)
void VirtualServer::appendStatusLine(Connection& clientConnection, Status::Index index) {
clientConnection.appendResponseMessage("HTTP/1.1 ");
clientConnection.appendResponseMessage(HTTP::getStatusCodeBy(index));
clientConnection.appendResponseMessage(" ");
clientConnection.appendResponseMessage(HTTP::getStatusReasonBy(index));
clientConnection.appendResponseMessage("\r\n");
}
// append default header fields.
void VirtualServer::appendDefaultHeaderFields(Connection& clientConnection) {
clientConnection.appendResponseMessage("Server: crash-webserve\r\n");
clientConnection.appendResponseMessage("Date: ");
clientConnection.appendResponseMessage(this->makeDateHeaderField());
clientConnection.appendResponseMessage("\r\n");
}
// append default header fields for error code.
void VirtualServer::appendContentDefaultHeaderFields(Connection& clientConnection) {
this->appendDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Type: text/html\r\n");
}
// update body string.
void VirtualServer::updateBodyString(HTTP::Status::Index index, const char* description, std::string& bodyString) const {
const char* statusCode = getStatusCodeBy(index);
const std::map<std::string, std::string>::const_iterator errorPageIterator = this->_errorPage.find(statusCode);
if (errorPageIterator == this->_errorPage.end())
::updateBodyString(index, description, bodyString);
else
bodyString = errorPageIterator->second;
}
// set response message with 201 status.
// - Parameters clientConnection: The client connection.
// - Return(None)
VirtualServer::ReturnCode VirtualServer::set201Response(Connection& clientConnection) {
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_201);
std::string bodyString;
this->updateBodyString(Status::I_201, "file created", bodyString);
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << bodyString.length();
clientConnection.appendResponseMessage(oss.str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
// set response message with 301 status.
// - Parameters clientConnection: The client connection.
// - Return(None)
VirtualServer::ReturnCode VirtualServer::set301Response(Connection& clientConnection, const std::map<std::string, std::vector<std::string> >& locOther) {
std::string bodyString;
std::stringstream ss;
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_301);
this->appendDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("Content-Length: ");
this->updateBodyString(Status::I_301, NULL, bodyString);
ss << bodyString.size();
clientConnection.appendResponseMessage(ss.str().c_str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Content-Type: text/html");
clientConnection.appendResponseMessage("\r\n");
// location
clientConnection.appendResponseMessage("Location: ");
clientConnection.appendResponseMessage(this->makeLocationHeaderField(locOther)); // $request_uri
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
// set response message with 308 status.
// - Parameters clientConnection: The client connection.
// - Return(None)
VirtualServer::ReturnCode VirtualServer::set308Response(Connection& clientConnection, const std::map<std::string, std::vector<std::string> >& locOther) {
std::string bodyString;
std::stringstream ss;
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_308);
this->appendDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("Content-Length: ");
this->updateBodyString(Status::I_308, NULL, bodyString);
ss << bodyString.size();
clientConnection.appendResponseMessage(ss.str().c_str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Content-Type: text/html");
clientConnection.appendResponseMessage("\r\n");
// location
clientConnection.appendResponseMessage("Location: ");
clientConnection.appendResponseMessage(this->makeLocationHeaderField(locOther));
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
// set response message with 400 status.
// - Parameters clientConnection: The client connection.
// - Return: upon successful completion a value of 0 is returned.
// otherwise, a value of -1 is returned.
VirtualServer::ReturnCode VirtualServer::set400Response(Connection& clientConnection) {
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_400);
std::string bodyString;
this->updateBodyString(Status::I_400, NULL, bodyString);
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << bodyString.length();
clientConnection.appendResponseMessage(oss.str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
// set response message with 404 status.
// - Parameters clientConnection: The client connection.
// - Return(None)
VirtualServer::ReturnCode VirtualServer::set404Response(Connection& clientConnection) {
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_404);
std::string bodyString;
this->updateBodyString(Status::I_404, NULL, bodyString);
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << bodyString.length();
clientConnection.appendResponseMessage(oss.str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
// set response message with 405 status.
// - Parameters clientConnection: The client connection.
// - Return(None)
VirtualServer::ReturnCode VirtualServer::set405Response(Connection& clientConnection, const Location* location) {
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_405);
std::string bodyString;
std::string reqBody = clientConnection.getRequest().getBody();
this->updateBodyString(Status::I_405, reqBody.c_str(), bodyString);
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << bodyString.length();
clientConnection.appendResponseMessage(oss.str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
if (location != NULL) {
clientConnection.appendResponseMessage("Allow: ");
std::string tAllowMethod = "";
if (location->isRequestMethodAllowed(HTTP::RM_GET))
tAllowMethod += "GET, ";
if (location->isRequestMethodAllowed(HTTP::RM_POST))
tAllowMethod += "POST, ";
if (location->isRequestMethodAllowed(HTTP::RM_DELETE))
tAllowMethod += "DELETE, ";
tAllowMethod = tAllowMethod.substr(0, tAllowMethod.find_last_of(","));
clientConnection.appendResponseMessage(tAllowMethod);
clientConnection.appendResponseMessage("\r\n");
}
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
// set response message with 411 status.
// - Parameters clientConnection: The client connection.
// - Return: upon successful completion a value of 0 is returned.
// otherwise, a value of -1 is returned.
VirtualServer::ReturnCode VirtualServer::set411Response(Connection& clientConnection) {
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_411);
std::string bodyString;
this->updateBodyString(Status::I_411, NULL, bodyString);
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << bodyString.length();
clientConnection.appendResponseMessage(oss.str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
// set response message with 413 status.
// - Parameters clientConnection: The client connection.
// - Return: upon successful completion a value of 0 is returned.
// otherwise, a value of -1 is returned.
VirtualServer::ReturnCode VirtualServer::set413Response(Connection& clientConnection) {
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_413);
std::string bodyString;
this->updateBodyString(Status::I_413, NULL, bodyString);
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << bodyString.length();
clientConnection.appendResponseMessage(oss.str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
// set response message with 500 status.
// - Parameters clientConnection: The client connection.
// - Return(None)
VirtualServer::ReturnCode VirtualServer::set500Response(Connection& clientConnection) {
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_500);
std::string bodyString;
this->updateBodyString(Status::I_500, NULL, bodyString);
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << bodyString.length();
clientConnection.appendResponseMessage(oss.str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage(bodyString);
return RC_SUCCESS;
}
// set body for directory listing.
VirtualServer::ReturnCode VirtualServer::setListResponse(Connection& clientConnection, const std::string& path) {
clientConnection.clearResponseMessage();
this->appendStatusLine(clientConnection, Status::I_200);
DIR* dir;
dir = opendir(path.c_str());
if (dir == NULL)
return RC_ERROR;
int contentLength = 100;
while (true) {
const struct dirent* entry = readdir(dir);
if (entry == NULL)
break;
if (entry->d_namlen == 1 && strcmp(entry->d_name, ".") == 0)
continue;
const bool isEntryDirectory = (entry->d_type == DT_DIR);
contentLength += (entry->d_namlen + isEntryDirectory) * 2 + 17;
}
closedir(dir);
contentLength += 26;
this->appendContentDefaultHeaderFields(clientConnection);
clientConnection.appendResponseMessage("Content-Length: ");
std::ostringstream oss;
oss << contentLength;
clientConnection.appendResponseMessage(oss.str().c_str());
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("Connection: keep-alive\r\n");
clientConnection.appendResponseMessage("\r\n");
clientConnection.appendResponseMessage("<html>\r\n<head><title>Index of /</title></head>\r\n<body bgcolor=\"white\">\r\n<h1>Index of /</h1><hr><pre>");
dir = opendir(path.c_str());
if (dir == NULL)
return RC_ERROR;
while (true) {
const struct dirent* entry = readdir(dir);
if (entry == NULL)
break;
if (entry->d_namlen == 1 && strcmp(entry->d_name, ".") == 0)
continue;
const bool isEntryDirectory = (entry->d_type == DT_DIR);
std::string name;
if (!isEntryDirectory)
name = entry->d_name;
else {
name += entry->d_name;
name += "/";
}
clientConnection.appendResponseMessage("<a href=\"");
clientConnection.appendResponseMessage(name);
clientConnection.appendResponseMessage("\">");
clientConnection.appendResponseMessage(name);
clientConnection.appendResponseMessage("</a>\r\n");
}
closedir(dir);
clientConnection.appendResponseMessage("</pre><hr></body></html>\r\n");
return RC_SUCCESS;
}
// Find the current time based on GMT
// - Parameters(None)
// - Return
// Current time based on GMT(std::string)
std::string VirtualServer::makeDateHeaderField() {
char cDate[1000];
time_t rr = time(0);
struct tm tm = *gmtime(&rr);
strftime(cDate, sizeof(cDate), "%a, %d %b %Y %H:%M:%S GMT", &tm);
std::string dateStr = cDate;
return dateStr;
}
// Make Location Field (redirection path)
// - Parameters
// locOther : etc directive set of connected locations
// - Return
// get redirection path. if not find, get null string
std::string VirtualServer::makeLocationHeaderField(const std::map<std::string, std::vector<std::string> >& locOther) {
std::map<std::string, std::vector<std::string> >::const_iterator otherIter = locOther.find("return");
if (otherIter != locOther.end() && otherIter->second.size() == 2)
return otherIter->second.back();
return "";
}
// set 'type' of 'name'
// - Parameters
// name: name of file
// type: type to set
// - Return(None)
static void updateContentType(const std::string& name, std::string& type) {
std::string extension;
updateExtension(name, extension);
if (std::strcmp(extension.c_str(), ".txt") == 0)
type = "text/plain";
else if (std::strcmp(extension.c_str(), ".html") == 0)
type = "text/html";
else
type = "application/octet-stream";
}
// set 'extension' of 'name'
// - Parameters
// name: name of file
// type: type to set
// - Return(None)
static void updateExtension(const std::string& name, std::string& extension) {
const std::string::size_type extensionBeginPosition = name.rfind('.'); // NOTE : http://localhost/first/test.cgi/bin/var?name=ccc&value=4.5 <- last comma?
const std::string::size_type extensionEndPosition = name.find_first_of(std::string("/?"), extensionBeginPosition); // NOTE: except fragment
extension.clear();
if (extensionBeginPosition != std::string::npos)
extension = name.substr(extensionBeginPosition, extensionEndPosition - extensionBeginPosition);
}
// generate body string with index, description.
// - Parameters
// index: index of status code.
// description: additional description to display.
// If you don't need additional description, pass NULL.
// bodyString: string to store generated body string.
// - Return(None)
static void updateBodyString(HTTP::Status::Index index, const char* description, std::string& bodyString) {
const Status& status = Status::_array[index];
bodyString.clear();
bodyString += "<html>\r\n<head><title>";
bodyString += status._statusCode;
bodyString += ' ';
bodyString += status._reasonPhrase;
bodyString += "</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>";
bodyString += status._statusCode;
bodyString += ' ';
bodyString += status._reasonPhrase;
bodyString += "</h1></center>\r\n<hr><center>";
bodyString += description != NULL ? description : "crash-webserve";
bodyString += "</center>\r\n</body>\r\n</html>\r\n";
}
// Get value from Request header by the key.
// - Parameters:
// request: Request class to get the value.
// key: searching key.
// - Return:
// Value of the key if exists, empty string otherwise.
std::string VirtualServer::getHeaderValue(const Request& request, std::string key) {
const std::string* value;
value = request.getFirstHeaderFieldValueByName(key);
if (value) {
return *value;
} else {
return "";
}
}
// Just makes inserting code simple to read.
// - Parameters:
// key: key.
// value: matching value.
inline void insertToStringMap(StringMap& envMap, std::string key, std::string value) {
if (value.empty())
return ;
envMap.insert(std::make_pair(key, value));
}
// Add the certain environmental value to _CGIEnvironmentMap
// (For enhancing code readability.)
// - Parameters:
// type: from where it getting the environment.
// key: environment key
// value: environment value
// - Return ( None )
void VirtualServer::fillCGIEnvMap(Connection& clientConnection, Location location) {
StringMap& em = this->_CGIEnvironmentMap;
const Request& request = clientConnection.getRequest();
const std::vector<std::string> uriInfo = clientConnection.getRequest().getTargetToken();
std::string scriptName;
location.updateRepresentationCGIPath(uriInfo[0], scriptName);
insertToStringMap(em, "SERVER_SOFTWARE", "FTServer/0.1");
insertToStringMap(em, "SERVER_NAME", "NoName");
insertToStringMap(em, "GATEWAY_INTERFACE", "CGI/1.1");
insertToStringMap(em, "SERVER_PROTOCOL", "HTTP/1.1");
insertToStringMap(em, "SERVER_PORT", clientConnection.getPortString());
insertToStringMap(em, "REQUEST_METHOD", request.getMethodString());
insertToStringMap(em, "PATH_INFO", uriInfo[1].empty() ? "/" : uriInfo[1]);
insertToStringMap(em, "PATH_TRANSLATED", location.getRoot() + uriInfo[1]);
insertToStringMap(em, "SCRIPT_NAME", "/" + scriptName);
insertToStringMap(em, "QUERY_STRING", uriInfo[2]);
insertToStringMap(em, "REMOTE_HOST", "");
insertToStringMap(em, "REMOTE_ADDR", "");
insertToStringMap(em, "AUTH_TYPE", this->getHeaderValue(request, "authorization"));
insertToStringMap(em, "REMOTE_USER", this->getHeaderValue(request, "authorization"));
insertToStringMap(em, "REMOTE_IDENT", this->getHeaderValue(request, "authorization"));
insertToStringMap(em, "CONTENT_TYPE", this->getHeaderValue(request, "content-type"));
insertToStringMap(em, "CONTENT_LENGTH", this->getHeaderValue(request, "content-length"));
}
// Make an envivonments array for CGI Process
// - Return: envp, the array to pass through 3rd param on execve().
char** VirtualServer::makeCGIEnvironmentArray() {
char** result;
std::string element;