/
testhttpserver.cpp
1657 lines (1420 loc) · 59.8 KB
/
testhttpserver.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
// --------------------------------------------------------------------------
//
// File
// Name: testhttpserver.cpp
// Purpose: Test code for HTTP server class
// Created: 26/3/04
//
// --------------------------------------------------------------------------
#include "Box.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif
#include <boost/foreach.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <openssl/x509.h>
#include <openssl/hmac.h>
#include "autogen_HTTPException.h"
#include "HTTPQueryDecoder.h"
#include "HTTPRequest.h"
#include "HTTPResponse.h"
#include "HTTPServer.h"
#include "HTTPTest.h"
#include "IOStreamGetLine.h"
#include "MD5Digest.h"
#include "S3Client.h"
#include "S3Simulator.h"
#include "ServerControl.h"
#include "SimpleDBClient.h"
#include "Test.h"
#include "ZeroStream.h"
#include "decode.h"
#include "encode.h"
#include "MemLeakFindOn.h"
#define SHORT_TIMEOUT 5000
#define LONG_TIMEOUT 300000
using boost::property_tree::ptree;
class TestWebServer : public HTTPServer
{
public:
TestWebServer()
: HTTPServer(LONG_TIMEOUT)
{ }
~TestWebServer() { }
virtual void Handle(HTTPRequest &rRequest, HTTPResponse &rResponse);
};
// Build a nice HTML response, so this can also be tested neatly in a browser
void TestWebServer::Handle(HTTPRequest &rRequest, HTTPResponse &rResponse)
{
// Test redirection mechanism
if(rRequest.GetRequestURI() == "/redirect")
{
rResponse.SetAsRedirect("/redirected");
return;
}
// Set a cookie?
if(rRequest.GetRequestURI() == "/set-cookie")
{
rResponse.SetCookie("SetByServer", "Value1");
}
#define DEFAULT_RESPONSE_1 "<html>\n<head><title>TEST SERVER RESPONSE</title></head>\n<body><h1>Test response</h1>\n<p><b>URI:</b> "
#define DEFAULT_RESPONSE_3 "</p>\n<p><b>Query string:</b> "
#define DEFAULT_RESPONSE_4 "</p>\n<p><b>Method:</b> "
#define DEFAULT_RESPONSE_5 "</p>\n<p><b>Decoded query:</b><br>"
#define DEFAULT_RESPONSE_6 "</p>\n<p><b>Content type:</b> "
#define DEFAULT_RESPONSE_7 "</p>\n<p><b>Content length:</b> "
#define DEFAULT_RESPONSE_8 "</p>\n<p><b>Cookies:</b><br>\n"
#define DEFAULT_RESPONSE_2 "</p>\n</body>\n</html>\n"
rResponse.SetResponseCode(HTTPResponse::Code_OK);
rResponse.SetContentType("text/html");
rResponse.Write(DEFAULT_RESPONSE_1, sizeof(DEFAULT_RESPONSE_1) - 1);
const std::string &ruri(rRequest.GetRequestURI());
rResponse.Write(ruri.c_str(), ruri.size());
rResponse.Write(DEFAULT_RESPONSE_3, sizeof(DEFAULT_RESPONSE_3) - 1);
const std::string &rquery(rRequest.GetQueryString());
rResponse.Write(rquery.c_str(), rquery.size());
rResponse.Write(DEFAULT_RESPONSE_4, sizeof(DEFAULT_RESPONSE_4) - 1);
{
const char *m = "????";
switch(rRequest.GetMethod())
{
case HTTPRequest::Method_GET: m = "GET "; break;
case HTTPRequest::Method_HEAD: m = "HEAD"; break;
case HTTPRequest::Method_POST: m = "POST"; break;
default: m = "UNKNOWN";
}
rResponse.Write(m, 4);
}
rResponse.Write(DEFAULT_RESPONSE_5, sizeof(DEFAULT_RESPONSE_5) - 1);
{
const HTTPRequest::Query_t &rquery(rRequest.GetQuery());
for(HTTPRequest::Query_t::const_iterator i(rquery.begin()); i != rquery.end(); ++i)
{
rResponse.Write("\nPARAM:", 7);
rResponse.Write(i->first.c_str(), i->first.size());
rResponse.Write("=", 1);
rResponse.Write(i->second.c_str(), i->second.size());
rResponse.Write("<br>\n", 4);
}
}
rResponse.Write(DEFAULT_RESPONSE_6, sizeof(DEFAULT_RESPONSE_6) - 1);
const std::string &rctype(rRequest.GetContentType());
rResponse.Write(rctype.c_str(), rctype.size());
rResponse.Write(DEFAULT_RESPONSE_7, sizeof(DEFAULT_RESPONSE_7) - 1);
{
char l[32];
rResponse.Write(l, ::sprintf(l, "%d", rRequest.GetContentLength()));
}
rResponse.Write(DEFAULT_RESPONSE_8, sizeof(DEFAULT_RESPONSE_8) - 1);
const HTTPRequest::CookieJar_t *pcookies = rRequest.GetCookies();
if(pcookies != 0)
{
HTTPRequest::CookieJar_t::const_iterator i(pcookies->begin());
for(; i != pcookies->end(); ++i)
{
char t[512];
rResponse.Write(t, ::sprintf(t, "COOKIE:%s=%s<br>\n", i->first.c_str(), i->second.c_str()));
}
}
rResponse.Write(DEFAULT_RESPONSE_2, sizeof(DEFAULT_RESPONSE_2) - 1);
}
std::vector<std::string> get_entry_names(const std::vector<S3Client::BucketEntry> entries)
{
std::vector<std::string> entry_names;
for(std::vector<S3Client::BucketEntry>::const_iterator i = entries.begin();
i != entries.end(); i++)
{
entry_names.push_back(i->name());
}
return entry_names;
}
bool exercise_s3client(S3Client& client)
{
int num_failures_initial = num_failures;
HTTPResponse response = client.GetObject("/photos/puppy.jpg");
TEST_EQUAL(200, response.GetResponseCode());
std::string response_data((const char *)response.GetBuffer(),
response.GetSize());
TEST_EQUAL("omgpuppies!\n", response_data);
TEST_THAT(!response.IsKeepAlive());
// make sure that assigning to HTTPResponse does clear stream
response = client.GetObject("/photos/puppy.jpg");
TEST_EQUAL(200, response.GetResponseCode());
response_data = std::string((const char *)response.GetBuffer(),
response.GetSize());
TEST_EQUAL("omgpuppies!\n", response_data);
TEST_THAT(!response.IsKeepAlive());
response = client.GetObject("/nonexist");
TEST_EQUAL(404, response.GetResponseCode());
TEST_THAT(!response.IsKeepAlive());
FileStream fs("testfiles/dsfdsfs98.fd");
std::string digest;
{
MD5DigestStream digester;
fs.CopyStreamTo(digester);
fs.Seek(0, IOStream::SeekType_Absolute);
digester.Close();
digest = digester.DigestAsString();
TEST_EQUAL("dc3b8c5e57e71d31a0a9d7cbeee2e011", digest);
}
// The destination file should not exist before we upload it:
TEST_THAT(!FileExists("testfiles/store/newfile"));
response = client.PutObject("/newfile", fs);
TEST_EQUAL(200, response.GetResponseCode());
TEST_THAT(!response.IsKeepAlive());
TEST_EQUAL("\"" + digest + "\"", response.GetHeaders().GetHeaderValue("etag"));
// This will fail if the file was created in the wrong place:
TEST_THAT(FileExists("testfiles/store/newfile"));
response = client.GetObject("/newfile");
TEST_EQUAL(200, response.GetResponseCode());
TEST_EQUAL(4269, response.GetSize());
fs.Seek(0, IOStream::SeekType_Absolute);
TEST_THAT(fs.CompareWith(response));
TEST_EQUAL("\"" + digest + "\"", response.GetHeaders().GetHeaderValue("etag"));
// Test that GET requests set the Content-Length header correctly.
int actual_size = TestGetFileSize("testfiles/dsfdsfs98.fd");
TEST_THAT(actual_size > 0);
TEST_EQUAL(actual_size, response.GetContentLength());
// Try to get it again, with the etag of the existing copy, and check that we get
// a 304 Not Modified response.
response = client.GetObject("/newfile", digest);
TEST_EQUAL(HTTPResponse::Code_NotModified, response.GetResponseCode());
// There are no examples for 304 Not Modified responses to requests with
// If-None-Match (ETag match) so clients should not depend on this, so the
// S3Simulator should return 0 instead of the object size and no ETag, to ensure
// that any code which tries to use the Content-Length or ETag of such a response
// will fail.
TEST_EQUAL(0, response.GetContentLength());
TEST_EQUAL("", response.GetHeaders().GetHeaderValue("etag", false)); // !required
// Test that HEAD requests set the Content-Length header correctly. We need the
// actual object size, not 0, despite there being no content in the response.
// RFC 2616 section 4.4 says "1.Any response message which "MUST NOT" include a
// message-body (such as ... any response to a HEAD request) is always terminated
// by the first empty line after the header fields, regardless of the
// entity-header fields present in the message... If a Content-Length header field
// (section 14.13) is present, its decimal value in OCTETs represents both the
// entity-length and the transfer-length."
//
// Also the Amazon Simple Storage Service API Reference, section "HEAD Object"
// examples show the Content-Length being returned as non-zero for a HEAD request,
// and ETag being returned too.
response = client.HeadObject("/newfile");
TEST_EQUAL(actual_size, response.GetContentLength());
TEST_EQUAL(200, response.GetResponseCode());
// We really need the ETag header in response to HEAD requests!
TEST_EQUAL("\"" + digest + "\"",
response.GetHeaders().GetHeaderValue("etag", false)); // !required
// Check that there is NO body. The request should not have been treated as a
// GET request!
ZeroStream empty(0);
TEST_THAT(fs.CompareWith(response));
// Replace the file contents with a smaller file, check that it works and that
// the file is truncated at the end of the new data.
CollectInBufferStream test_data;
test_data.Write(std::string("hello"));
test_data.SetForReading();
response = client.PutObject("/newfile", test_data);
TEST_EQUAL(200, response.GetResponseCode());
TEST_EQUAL("\"5d41402abc4b2a76b9719d911017c592\"",
response.GetHeaders().GetHeaderValue("etag", false)); // !required
TEST_EQUAL(5, TestGetFileSize("testfiles/store/newfile"));
// This will fail if the file was created in the wrong place:
TEST_THAT(FileExists("testfiles/store/newfile"));
response = client.DeleteObject("/newfile");
TEST_EQUAL(HTTPResponse::Code_NoContent, response.GetResponseCode());
TEST_THAT(!FileExists("testfiles/store/newfile"));
// Try uploading a file in a subdirectory, which should create it implicitly
// and automatically.
TEST_EQUAL(0, ObjectExists("testfiles/store/sub"));
TEST_THAT(!FileExists("testfiles/store/sub/newfile"));
response = client.PutObject("/sub/newfile", fs);
TEST_EQUAL(200, response.GetResponseCode());
response = client.GetObject("/sub/newfile");
TEST_EQUAL(200, response.GetResponseCode());
TEST_THAT(fs.CompareWith(response));
response = client.DeleteObject("/sub/newfile");
TEST_EQUAL(HTTPResponse::Code_NoContent, response.GetResponseCode());
TEST_THAT(!FileExists("testfiles/store/sub/newfile"));
// There is no way to explicitly delete a directory either, so we must do that
// ourselves
TEST_THAT(rmdir("testfiles/store/sub") == 0);
// Test the ListBucket command.
std::vector<S3Client::BucketEntry> actual_contents;
std::vector<std::string> actual_common_prefixes;
TEST_EQUAL(3, client.ListBucket(&actual_contents, &actual_common_prefixes));
std::vector<std::string> actual_entry_names =
get_entry_names(actual_contents);
std::vector<std::string> expected_contents;
expected_contents.push_back("dsfdsfs98.fd");
TEST_THAT(test_equal_lists(expected_contents, actual_entry_names));
std::vector<std::string> expected_common_prefixes;
expected_common_prefixes.push_back("photos/");
expected_common_prefixes.push_back("subdir/");
TEST_THAT(test_equal_lists(expected_common_prefixes, actual_common_prefixes));
// Test that max_keys works.
actual_contents.clear();
actual_common_prefixes.clear();
bool is_truncated;
TEST_EQUAL(2,
client.ListBucket(
&actual_contents, &actual_common_prefixes,
"", // prefix
"/", // delimiter
&is_truncated,
2)); // max_keys
TEST_THAT(is_truncated);
expected_contents.clear();
expected_contents.push_back("dsfdsfs98.fd");
actual_entry_names = get_entry_names(actual_contents);
TEST_THAT(test_equal_lists(expected_contents, actual_entry_names));
expected_common_prefixes.clear();
expected_common_prefixes.push_back("photos/");
TEST_THAT(test_equal_lists(expected_common_prefixes, actual_common_prefixes));
// Test that marker works.
actual_contents.clear();
actual_common_prefixes.clear();
TEST_EQUAL(2,
client.ListBucket(
&actual_contents, &actual_common_prefixes,
"", // prefix
"/", // delimiter
&is_truncated,
2, // max_keys
"photos")); // marker
TEST_THAT(!is_truncated);
expected_contents.clear();
actual_entry_names = get_entry_names(actual_contents);
TEST_THAT(test_equal_lists(expected_contents, actual_entry_names));
expected_common_prefixes.push_back("subdir/");
TEST_THAT(test_equal_lists(expected_common_prefixes, actual_common_prefixes));
// Test is successful if the number of failures has not increased.
return (num_failures == num_failures_initial);
}
std::string generate_query_string(const HTTPRequest& request)
{
std::vector<std::string> param_names;
std::map<std::string, std::string> param_values;
const HTTPRequest::Query_t& params(request.GetQuery());
for(HTTPRequest::Query_t::const_iterator i = params.begin();
i != params.end(); i++)
{
// We don't want to include the Signature parameter in the sorted query
// string, because the client didn't either when computing the signature!
if(i->first != "Signature")
{
param_names.push_back(i->first);
// This algorithm only supports non-repeated parameters, so
// assert that we don't already have a parameter with this name.
TEST_LINE_OR(param_values.find(i->first) == param_values.end(),
"Multiple values for parameter '" << i->first << "'",
return "");
param_values[i->first] = i->second;
}
}
std::sort(param_names.begin(), param_names.end());
std::ostringstream out;
for(std::vector<std::string>::iterator i = param_names.begin();
i != param_names.end(); i++)
{
if(i != param_names.begin())
{
out << "&";
}
out << HTTPQueryDecoder::URLEncode(*i) << "=" <<
HTTPQueryDecoder::URLEncode(param_values[*i]);
}
return out.str();
}
std::string calculate_s3_signature(const HTTPRequest& request,
const std::string& aws_secret_access_key)
{
// This code is very similar to that in S3Client::FinishAndSendRequest.
// TODO FIXME: factor out the common parts.
std::ostringstream buffer_to_sign;
buffer_to_sign << request.GetMethodName() << "\n" <<
request.GetHeaders().GetHeaderValue("Content-MD5",
false) << "\n" << // !required
request.GetContentType() << "\n" <<
request.GetHeaders().GetHeaderValue("Date",
true) << "\n"; // required
// TODO FIXME: add support for X-Amz headers (S3 DG page 38)
std::string bucket;
std::string host_header = request.GetHeaders().GetHeaderValue("Host",
true); // required
std::string s3suffix = ".s3.amazonaws.com";
if(host_header.size() > s3suffix.size())
{
std::string suffix = host_header.substr(host_header.size() -
s3suffix.size(), s3suffix.size());
if (suffix == s3suffix)
{
bucket = "/" + host_header.substr(0, host_header.size() -
s3suffix.size());
}
}
buffer_to_sign << bucket << request.GetRequestURI();
// TODO FIXME: add support for sub-resources. S3 DG page 36.
// Thanks to https://gist.github.com/tsupo/112188:
unsigned int digest_size;
unsigned char digest_buffer[EVP_MAX_MD_SIZE];
std::string string_to_sign = buffer_to_sign.str();
HMAC(EVP_sha1(),
aws_secret_access_key.c_str(), aws_secret_access_key.size(),
(const unsigned char *)string_to_sign.c_str(), string_to_sign.size(),
digest_buffer, &digest_size);
base64::encoder encoder;
std::string digest((const char *)digest_buffer, digest_size);
std::string auth_code = encoder.encode(digest);
if (auth_code[auth_code.size() - 1] == '\n')
{
auth_code = auth_code.substr(0, auth_code.size() - 1);
}
return auth_code;
}
// http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/HMACAuth.html
std::string calculate_simpledb_signature(const HTTPRequest& request,
const std::string& aws_secret_access_key)
{
// This code is very similar to that in S3Client::FinishAndSendRequest,
// but using EVP_sha256 instead of EVP_sha1. TODO FIXME: factor out the
// common parts.
std::string query_string = generate_query_string(request);
TEST_THAT_OR(query_string != "", return "");
std::ostringstream buffer_to_sign;
buffer_to_sign << request.GetMethodName() << "\n" <<
request.GetHeaders().GetHostNameWithPort() << "\n" <<
// The HTTPRequestURI component is the HTTP absolute path component
// of the URI up to, but not including, the query string. If the
// HTTPRequestURI is empty, use a forward slash ( / ).
request.GetRequestURI() << "\n" <<
query_string;
// Thanks to https://gist.github.com/tsupo/112188:
unsigned int digest_size;
unsigned char digest_buffer[EVP_MAX_MD_SIZE];
std::string string_to_sign = buffer_to_sign.str();
HMAC(EVP_sha256(),
aws_secret_access_key.c_str(), aws_secret_access_key.size(),
(const unsigned char *)string_to_sign.c_str(), string_to_sign.size(),
digest_buffer, &digest_size);
base64::encoder encoder;
std::string digest((const char *)digest_buffer, digest_size);
std::string auth_code = encoder.encode(digest);
if (auth_code[auth_code.size() - 1] == '\n')
{
auth_code = auth_code.substr(0, auth_code.size() - 1);
}
return auth_code;
}
bool add_simpledb_signature(HTTPRequest& request, const std::string& aws_secret_access_key)
{
std::string signature = calculate_simpledb_signature(request,
aws_secret_access_key);
request.SetParameter("Signature", signature);
return !signature.empty();
}
bool send_and_receive(HTTPRequest& request, HTTPResponse& response,
int expected_status_code = 200)
{
SocketStream sock;
sock.Open(Socket::TypeINET, "localhost", 1080);
request.Send(sock, LONG_TIMEOUT);
response.Reset();
response.Receive(sock, LONG_TIMEOUT);
std::string response_data((const char *)response.GetBuffer(),
response.GetSize());
TEST_EQUAL_LINE(expected_status_code, response.GetResponseCode(),
response_data);
return (response.GetResponseCode() == expected_status_code);
}
bool parse_xml_response(HTTPResponse& response, ptree& response_tree,
const std::string& expected_root_element)
{
std::string response_data((const char *)response.GetBuffer(),
response.GetSize());
std::auto_ptr<std::istringstream> ap_response_stream(
new std::istringstream(response_data));
read_xml(*ap_response_stream, response_tree,
boost::property_tree::xml_parser::trim_whitespace);
TEST_EQUAL_OR(expected_root_element, response_tree.begin()->first, return false);
TEST_LINE(++(response_tree.begin()) == response_tree.end(),
"There should only be one item in the response tree root");
return true;
}
bool send_and_receive_xml(HTTPRequest& request, ptree& response_tree,
const std::string& expected_root_element)
{
HTTPResponse response;
TEST_THAT_OR(send_and_receive(request, response), return false);
return parse_xml_response(response, response_tree, expected_root_element);
}
typedef std::multimap<std::string, std::string> multimap_t;
typedef multimap_t::value_type attr_t;
std::vector<std::string> simpledb_list_domains(const std::string& access_key,
const std::string& secret_key)
{
HTTPRequest request(HTTPRequest::Method_GET, "/");
request.SetHostName(SIMPLEDB_SIMULATOR_HOST);
request.AddParameter("Action", "ListDomains");
request.AddParameter("AWSAccessKeyId", access_key);
request.AddParameter("SignatureVersion", "2");
request.AddParameter("SignatureMethod", "HmacSHA256");
request.AddParameter("Timestamp", "2010-01-25T15:01:28-07:00");
request.AddParameter("Version", "2009-04-15");
TEST_THAT_OR(add_simpledb_signature(request, secret_key),
return std::vector<std::string>());
ptree response_tree;
TEST_THAT(send_and_receive_xml(request, response_tree, "ListDomainsResponse"));
std::vector<std::string> domains;
BOOST_FOREACH(ptree::value_type &v,
response_tree.get_child("ListDomainsResponse.ListDomainsResult"))
{
domains.push_back(v.second.data());
}
return domains;
}
HTTPRequest simpledb_get_attributes_request(const std::string& access_key,
const std::string& secret_key)
{
HTTPRequest request(HTTPRequest::Method_GET, "/");
request.SetHostName(SIMPLEDB_SIMULATOR_HOST);
request.AddParameter("Action", "GetAttributes");
request.AddParameter("DomainName", "MyDomain");
request.AddParameter("ItemName", "JumboFez");
request.AddParameter("AWSAccessKeyId", access_key);
request.AddParameter("SignatureVersion", "2");
request.AddParameter("SignatureMethod", "HmacSHA256");
request.AddParameter("Timestamp", "2010-01-25T15:01:28-07:00");
request.AddParameter("Version", "2009-04-15");
TEST_THAT(add_simpledb_signature(request, secret_key));
return request;
}
bool simpledb_get_attributes_error(const std::string& access_key,
const std::string& secret_key, int expected_status_code)
{
HTTPRequest request = simpledb_get_attributes_request(access_key, secret_key);
HTTPResponse response;
TEST_THAT_OR(send_and_receive(request, response, expected_status_code),
return false);
// Nothing else to check: there is no XML
return true;
}
bool simpledb_get_attributes(const std::string& access_key, const std::string& secret_key,
const multimap_t& const_attributes)
{
HTTPRequest request = simpledb_get_attributes_request(access_key, secret_key);
ptree response_tree;
TEST_THAT_OR(send_and_receive_xml(request, response_tree,
"GetAttributesResponse"), return false);
// Check that all attributes were written correctly
TEST_EQUAL_LINE(const_attributes.size(),
response_tree.get_child("GetAttributesResponse.GetAttributesResult").size(),
"Wrong number of attributes in response");
bool all_match = (const_attributes.size() ==
response_tree.get_child("GetAttributesResponse.GetAttributesResult").size());
multimap_t attributes = const_attributes;
multimap_t::iterator i = attributes.begin();
BOOST_FOREACH(ptree::value_type &v,
response_tree.get_child(
"GetAttributesResponse.GetAttributesResult"))
{
std::string name = v.second.get<std::string>("Name");
std::string value = v.second.get<std::string>("Value");
if(i == attributes.end())
{
TEST_EQUAL_LINE("", name, "Unexpected attribute name");
TEST_EQUAL_LINE("", value, "Unexpected attribute value");
all_match = false;
}
else
{
TEST_EQUAL_LINE(i->first, name, "Wrong attribute name");
TEST_EQUAL_LINE(i->second, value, "Wrong attribute value");
all_match &= (i->first == name);
all_match &= (i->second == value);
i++;
}
}
return all_match;
}
#define EXAMPLE_S3_ACCESS_KEY "0PN5J17HBGZHT7JJ3X82"
#define EXAMPLE_S3_SECRET_KEY "uV3F3YluFJax1cknvbcGwgjvx4QpvB+leU8dUj2o"
bool test_httpserver()
{
SETUP();
{
FileStream fs("testfiles/dsfdsfs98.fd");
MD5DigestStream digester;
fs.CopyStreamTo(digester);
fs.Seek(0, IOStream::SeekType_Absolute);
digester.Close();
std::string digest = digester.DigestAsString();
TEST_EQUAL("dc3b8c5e57e71d31a0a9d7cbeee2e011", digest);
}
// Test that HTTPRequest with parameters is encoded correctly
{
HTTPRequest request(HTTPRequest::Method_GET, "/newfile");
CollectInBufferStream request_buffer;
request.SendHeaders(request_buffer, IOStream::TimeOutInfinite);
request_buffer.SetForReading();
std::string request_str((const char *)request_buffer.GetBuffer(),
request_buffer.GetSize());
const std::string expected_str("GET /newfile HTTP/1.1\r\nConnection: close\r\n\r\n");
TEST_EQUAL(expected_str, request_str);
request.AddParameter("foo", "Bar");
request_buffer.Reset();
request.SendHeaders(request_buffer, IOStream::TimeOutInfinite);
request_str = std::string((const char *)request_buffer.GetBuffer(),
request_buffer.GetSize());
TEST_EQUAL("GET /newfile?foo=Bar HTTP/1.1\r\nConnection: close\r\n\r\n", request_str);
request.AddParameter("foo", "baz");
request_buffer.Reset();
request.SendHeaders(request_buffer, IOStream::TimeOutInfinite);
request_str = std::string((const char *)request_buffer.GetBuffer(),
request_buffer.GetSize());
TEST_EQUAL("GET /newfile?foo=Bar&foo=baz HTTP/1.1\r\nConnection: close\r\n\r\n", request_str);
request.SetParameter("whee", "bonk");
request_buffer.Reset();
request.SendHeaders(request_buffer, IOStream::TimeOutInfinite);
request_str = std::string((const char *)request_buffer.GetBuffer(),
request_buffer.GetSize());
TEST_EQUAL("GET /newfile?foo=Bar&foo=baz&whee=bonk HTTP/1.1\r\nConnection: close\r\n\r\n", request_str);
request.SetParameter("foo", "bolt");
request_buffer.Reset();
request.SendHeaders(request_buffer, IOStream::TimeOutInfinite);
request_str = std::string((const char *)request_buffer.GetBuffer(),
request_buffer.GetSize());
TEST_EQUAL("GET /newfile?foo=bolt&whee=bonk HTTP/1.1\r\nConnection: close\r\n\r\n", request_str);
HTTPRequest newreq = request;
TEST_EQUAL("bolt", newreq.GetParameterString("foo"));
TEST_EQUAL("bonk", newreq.GetParameterString("whee"));
TEST_EQUAL("blue", newreq.GetParameterString("colour", "blue"));
TEST_CHECK_THROWS(newreq.GetParameterString("colour"), HTTPException,
ParameterNotFound);
}
// Test that HTTPRequest can be written to and read from a stream.
for(int enable_continue = 0; enable_continue < 2; enable_continue++)
{
HTTPRequest request(HTTPRequest::Method_PUT, "/newfile");
request.SetHostName("quotes.s3.amazonaws.com");
// Write headers in lower case.
request.AddHeader("date", "Wed, 01 Mar 2006 12:00:00 GMT");
request.AddHeader("authorization",
"AWS " EXAMPLE_S3_ACCESS_KEY ":XtMYZf0hdOo4TdPYQknZk0Lz7rw=");
request.AddHeader("Content-Type", "text/plain");
request.SetClientKeepAliveRequested(true);
// First stream just the headers into a CollectInBufferStream, and check the
// exact contents written:
CollectInBufferStream request_buffer;
request.SendHeaders(request_buffer, IOStream::TimeOutInfinite,
(bool)enable_continue);
request_buffer.SetForReading();
std::string request_str((const char *)request_buffer.GetBuffer(),
request_buffer.GetSize());
std::string expected_str(
"PUT /newfile HTTP/1.1\r\n"
"Content-Type: text/plain\r\n"
"Host: quotes.s3.amazonaws.com\r\n"
"Connection: keep-alive\r\n"
"date: Wed, 01 Mar 2006 12:00:00 GMT\r\n"
"authorization: AWS " EXAMPLE_S3_ACCESS_KEY ":XtMYZf0hdOo4TdPYQknZk0Lz7rw=\r\n");
if(enable_continue == 1)
{
expected_str += "Expect: 100-continue\r\n";
}
TEST_EQUAL(expected_str + "\r\n", request_str);
// Now stream the entire request into the CollectInBufferStream. Because there
// isn't an HTTP server to respond to us, we can't use SendWithStream, so just
// send the headers and then the content separately:
request_buffer.Reset();
request.SendHeaders(request_buffer, IOStream::TimeOutInfinite,
(bool)enable_continue);
FileStream fs("testfiles/photos/puppy.jpg");
fs.CopyStreamTo(request_buffer);
request_buffer.SetForReading();
IOStreamGetLine getLine(request_buffer);
HTTPRequest request2;
TEST_THAT(request2.Receive(getLine, IOStream::TimeOutInfinite));
TEST_EQUAL(HTTPRequest::Method_PUT, request2.GetMethod());
TEST_EQUAL("PUT", request2.GetMethodName());
TEST_EQUAL("/newfile", request2.GetRequestURI());
TEST_EQUAL("quotes.s3.amazonaws.com", request2.GetHostName());
TEST_EQUAL(80, request2.GetHostPort());
TEST_EQUAL("", request2.GetQueryString());
TEST_EQUAL("text/plain", request2.GetContentType());
// Content-Length was not known when the stream was sent, so it should
// be unknown in the received stream too (certainly before it has all
// been read!)
TEST_EQUAL(-1, request2.GetContentLength());
const HTTPHeaders& headers(request2.GetHeaders());
TEST_EQUAL("Wed, 01 Mar 2006 12:00:00 GMT",
headers.GetHeaderValue("Date"));
TEST_EQUAL("AWS " EXAMPLE_S3_ACCESS_KEY ":XtMYZf0hdOo4TdPYQknZk0Lz7rw=",
headers.GetHeaderValue("Authorization"));
TEST_THAT(request2.GetClientKeepAliveRequested());
TEST_EQUAL((bool)enable_continue, request2.IsExpectingContinue());
CollectInBufferStream request_data;
request2.ReadContent(request_data, IOStream::TimeOutInfinite);
TEST_EQUAL(fs.GetPosition(), request_data.GetPosition());
request_data.SetForReading();
fs.Seek(0, IOStream::SeekType_Absolute);
TEST_THAT(fs.CompareWith(request_data, IOStream::TimeOutInfinite));
}
// Test that HTTPResponse can be written to and read from a stream.
// TODO FIXME: we should stream the response instead of buffering it, on both
// sides (send and receive).
{
// Stream it to a CollectInBufferStream
CollectInBufferStream response_buffer;
HTTPResponse response(&response_buffer);
FileStream fs("testfiles/photos/puppy.jpg");
// Write headers in lower case.
response.SetResponseCode(HTTPResponse::Code_OK);
response.AddHeader("date", "Wed, 01 Mar 2006 12:00:00 GMT");
response.AddHeader("authorization",
"AWS " EXAMPLE_S3_ACCESS_KEY ":XtMYZf0hdOo4TdPYQknZk0Lz7rw=");
response.AddHeader("content-type", "text/perl");
fs.CopyStreamTo(response);
response.Send();
response_buffer.SetForReading();
HTTPResponse response2;
response2.Receive(response_buffer);
TEST_EQUAL(200, response2.GetResponseCode());
TEST_EQUAL("text/perl", response2.GetContentType());
// TODO FIXME: Content-Length was not known when the stream was sent,
// so it should be unknown in the received stream too (certainly before
// it has all been read!) This is currently wrong because we read the
// entire response into memory immediately.
TEST_EQUAL(fs.GetPosition(), response2.GetContentLength());
HTTPHeaders& headers(response2.GetHeaders());
TEST_EQUAL("Wed, 01 Mar 2006 12:00:00 GMT",
headers.GetHeaderValue("Date"));
TEST_EQUAL("AWS " EXAMPLE_S3_ACCESS_KEY ":XtMYZf0hdOo4TdPYQknZk0Lz7rw=",
headers.GetHeaderValue("Authorization"));
CollectInBufferStream response_data;
// request2.ReadContent(request_data, IOStream::TimeOutInfinite);
response2.CopyStreamTo(response_data);
TEST_EQUAL(fs.GetPosition(), response_data.GetPosition());
response_data.SetForReading();
fs.Seek(0, IOStream::SeekType_Absolute);
TEST_THAT(fs.CompareWith(response_data, IOStream::TimeOutInfinite));
}
#ifndef WIN32
TEST_THAT(system("rm -rf *.memleaks") == 0);
#endif
// Start the server
int pid = StartDaemon(0, TEST_EXECUTABLE " server testfiles/httpserver.conf",
"testfiles/httpserver.pid");
TEST_THAT_OR(pid > 0, return 1);
// Run the request script
TEST_THAT(::system("perl testfiles/testrequests.pl") == 0);
#ifndef WIN32
signal(SIGPIPE, SIG_IGN);
#endif
#ifdef ENABLE_KEEPALIVE_SUPPORT // incomplete, need chunked encoding support
SocketStream sock;
sock.Open(Socket::TypeINET, "localhost", 1080);
for (int i = 0; i < 4; i++)
{
HTTPRequest request(HTTPRequest::Method_GET,
"/test-one/34/341s/234?p1=vOne&p2=vTwo");
if (i < 2)
{
// first set of passes has keepalive off by default,
// so when i == 1 the socket has already been closed
// by the server, and we'll get -EPIPE when we try
// to send the request.
request.SetClientKeepAliveRequested(false);
}
else
{
request.SetClientKeepAliveRequested(true);
}
if (i == 1)
{
sleep(1); // need time for our process to realise
// that the peer has died, otherwise no SIGPIPE :(
TEST_CHECK_THROWS(
request.Send(sock, SHORT_TIMEOUT),
ConnectionException, SocketWriteError);
sock.Close();
sock.Open(Socket::TypeINET, "localhost", 1080);
continue;
}
else
{
request.Send(sock, SHORT_TIMEOUT);
}
HTTPResponse response;
response.Receive(sock, SHORT_TIMEOUT);
TEST_THAT(response.GetResponseCode() == HTTPResponse::Code_OK);
TEST_THAT(response.GetContentType() == "text/html");
IOStreamGetLine getline(response);
std::string line;
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<html>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<head><title>TEST SERVER RESPONSE</title></head>",
line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<body><h1>Test response</h1>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<p><b>URI:</b> /test-one/34/341s/234</p>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<p><b>Query string:</b> p1=vOne&p2=vTwo</p>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<p><b>Method:</b> GET </p>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<p><b>Decoded query:</b><br>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("PARAM:p1=vOne<br>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("PARAM:p2=vTwo<br></p>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<p><b>Content type:</b> </p>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<p><b>Content length:</b> -1</p>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("<p><b>Cookies:</b><br>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("</p>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("</body>", line);
TEST_THAT(getline.GetLine(line));
TEST_EQUAL("</html>", line);
if(!response.IsKeepAlive())
{
BOX_TRACE("Server will close the connection, closing our end too.");
sock.Close();
sock.Open(Socket::TypeINET, "localhost", 1080);
}
else
{
BOX_TRACE("Server will keep the connection open for more requests.");
}
}
sock.Close();
#endif // ENABLE_KEEPALIVE_SUPPORT
// Kill it
TEST_THAT(StopDaemon(pid, "testfiles/httpserver.pid",
"generic-httpserver.memleaks", true));
// Copy testfiles/puppy.jpg to testfiles/store/photos/puppy.jpg
{
TEST_THAT(::mkdir("testfiles/store/photos", 0755) == 0);
FileStream in("testfiles/puppy.jpg", O_RDONLY);
FileStream out("testfiles/store/photos/puppy.jpg", O_CREAT | O_WRONLY);
in.CopyStreamTo(out);
}
// This is the example from the Amazon S3 Developers Guide, page 31.
// Correct, official signature should succeed, with lower-case headers.
{
// http://docs.amazonwebservices.com/AmazonS3/2006-03-01/RESTAuthentication.html
HTTPRequest request(HTTPRequest::Method_GET, "/photos/puppy.jpg");
request.SetHostName("johnsmith.s3.amazonaws.com");
request.AddHeader("date", "Tue, 27 Mar 2007 19:36:42 +0000");
std::string signature = calculate_s3_signature(request,
EXAMPLE_S3_SECRET_KEY);
TEST_EQUAL(signature, "xXjDGYUmKxnwqr5KXNPGldn5LbA=");
request.AddHeader("authorization",
"AWS " EXAMPLE_S3_ACCESS_KEY ":" + signature);
S3Simulator simulator;
simulator.Configure("testfiles/s3simulator.conf");
CollectInBufferStream response_buffer;
HTTPResponse response(&response_buffer);
simulator.Handle(request, response);
TEST_EQUAL(200, response.GetResponseCode());
std::string response_data((const char *)response.GetBuffer(),
response.GetSize());
TEST_EQUAL("omgpuppies!\n", response_data);
}
// Modified signature should fail.
{
// http://docs.amazonwebservices.com/AmazonS3/2006-03-01/RESTAuthentication.html
HTTPRequest request(HTTPRequest::Method_GET, "/photos/puppy.jpg");
request.SetHostName("johnsmith.s3.amazonaws.com");
request.AddHeader("date", "Tue, 27 Mar 2007 19:36:42 +0000");
request.AddHeader("authorization",
"AWS " EXAMPLE_S3_ACCESS_KEY ":xXjDGYUmKxnwqr5KXNPGldn5LbB=");
S3Simulator simulator;
simulator.Configure("testfiles/s3simulator.conf");
CollectInBufferStream response_buffer;
HTTPResponse response(&response_buffer);
simulator.Handle(request, response);
TEST_EQUAL(401, response.GetResponseCode());
std::string response_data((const char *)response.GetBuffer(),
response.GetSize());
TEST_EQUAL("<html><head>"
"<title>Internal Server Error</title></head>\n"
"<h1>Internal Server Error</h1>\n"
"<p>An error occurred while processing the request:</p>\n"
"<pre>HTTPException(AuthenticationFailed): "
"Authentication code mismatch: expected AWS 0PN5J17HBGZHT7JJ3X82"
":xXjDGYUmKxnwqr5KXNPGldn5LbA= but received AWS "