-
Notifications
You must be signed in to change notification settings - Fork 17
/
S3Simulator.cpp
374 lines (325 loc) · 10.9 KB
/
S3Simulator.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
// --------------------------------------------------------------------------
//
// File
// Name: S3Simulator.cpp
// Purpose: Amazon S3 client helper implementation class
// Created: 09/01/2009
//
// --------------------------------------------------------------------------
#include "Box.h"
#include <algorithm>
#include <cstring>
// #include <cstdio>
// #include <ctime>
#include <openssl/hmac.h>
#include "HTTPRequest.h"
#include "HTTPResponse.h"
#include "autogen_HTTPException.h"
#include "IOStream.h"
#include "Logging.h"
#include "S3Simulator.h"
#include "Utils.h" // for ObjectExists_* (object_exists_t)
#include "decode.h"
#include "encode.h"
#include "MemLeakFindOn.h"
// --------------------------------------------------------------------------
//
// Function
// Name: HTTPServer::GetConfigVerify()
// Purpose: Returns additional configuration options for the
// S3 simulator. Currently the access key, secret key
// and store directory can be configured.
// Created: 09/01/09
//
// --------------------------------------------------------------------------
const ConfigurationVerify* S3Simulator::GetConfigVerify() const
{
static ConfigurationVerifyKey verifyserverkeys[] =
{
HTTPSERVER_VERIFY_SERVER_KEYS(ConfigurationVerifyKey::NoDefaultValue) // no default addresses
};
static ConfigurationVerify verifyserver[] =
{
{
"Server",
0,
verifyserverkeys,
ConfigTest_Exists | ConfigTest_LastEntry,
0
}
};
static ConfigurationVerifyKey verifyrootkeys[] =
{
ConfigurationVerifyKey("AccessKey", ConfigTest_Exists),
ConfigurationVerifyKey("SecretKey", ConfigTest_Exists),
ConfigurationVerifyKey("StoreDirectory", ConfigTest_Exists),
HTTPSERVER_VERIFY_ROOT_KEYS
};
static ConfigurationVerify verify =
{
"root",
verifyserver,
verifyrootkeys,
ConfigTest_Exists | ConfigTest_LastEntry,
0
};
return &verify;
}
// --------------------------------------------------------------------------
//
// Function
// Name: S3Simulator::Handle(HTTPRequest &rRequest,
// HTTPResponse &rResponse)
// Purpose: Handles any incoming S3 request, by checking
// authorization and then dispatching to one of the
// private Handle* methods.
// Created: 09/01/09
//
// --------------------------------------------------------------------------
void S3Simulator::Handle(HTTPRequest &rRequest, HTTPResponse &rResponse)
{
// if anything goes wrong, return a 500 error
rResponse.SetResponseCode(HTTPResponse::Code_InternalServerError);
rResponse.SetContentType("text/plain");
std::string bucket_name;
try
{
const Configuration& rConfig(GetConfiguration());
std::string access_key = rConfig.GetKeyValue("AccessKey");
std::string secret_key = rConfig.GetKeyValue("SecretKey");
std::ostringstream buffer_to_sign;
buffer_to_sign << rRequest.GetMethodName() << "\n";
if(true)
{
std::string md5, date;
rRequest.GetHeader("content-md5", &md5);
rRequest.GetHeader("date", &date);
std::string host = rRequest.GetHostName();
std::string s3suffix = ".s3.amazonaws.com";
if (host.size() > s3suffix.size())
{
std::string suffix = host.substr(host.size() - s3suffix.size(),
s3suffix.size());
if (suffix == s3suffix)
{
bucket_name = host.substr(0, host.size() - s3suffix.size());
}
}
buffer_to_sign << md5 << "\n";
buffer_to_sign << rRequest.GetContentType() << "\n";
buffer_to_sign << date << "\n";
// header names are already in lower case, i.e. canonical form
std::vector<HTTPRequest::Header> headers =
rRequest.GetHeaders().GetExtraHeaders();
std::sort(headers.begin(), headers.end());
for (std::vector<HTTPRequest::Header>::iterator
i = headers.begin(); i != headers.end(); i++)
{
if (i->first.substr(0, 5) == "x-amz")
{
buffer_to_sign << i->first << ":" <<
i->second << "\n";
}
}
if (! bucket_name.empty())
{
buffer_to_sign << "/" << bucket_name;
}
buffer_to_sign << rRequest.GetRequestURI();
}
std::string string_to_sign = buffer_to_sign.str();
unsigned char digest_buffer[EVP_MAX_MD_SIZE];
unsigned int digest_size = sizeof(digest_buffer);
/* unsigned char* mac = */ HMAC(EVP_sha1(),
secret_key.c_str(), secret_key.size(),
(const unsigned char*)string_to_sign.c_str(),
string_to_sign.size(), digest_buffer, &digest_size);
std::string digest((const char *)digest_buffer, digest_size);
std::string expected_auth, actual_auth;
base64::encoder encoder;
if(true)
{
expected_auth = "AWS " + access_key + ":" + encoder.encode(digest);
if(!rRequest.GetHeader("authorization", &actual_auth))
{
THROW_EXCEPTION_MESSAGE(HTTPException,
AuthenticationFailed, "Missing Authorization header");
}
}
// The Base64 encoder tends to add a newline onto the end of the encoded
// string, which we don't want, so remove it here.
if(expected_auth[expected_auth.size() - 1] == '\n')
{
expected_auth = expected_auth.substr(0, expected_auth.size() - 1);
}
if(actual_auth != expected_auth)
{
THROW_EXCEPTION_MESSAGE(HTTPException,
AuthenticationFailed, "Authentication code mismatch: " <<
"expected " << expected_auth << " but received " <<
actual_auth);
}
if(rRequest.GetMethod() == HTTPRequest::Method_GET)
{
HandleGet(rRequest, rResponse);
}
else if(rRequest.GetMethod() == HTTPRequest::Method_PUT)
{
HandlePut(rRequest, rResponse);
}
else
{
THROW_EXCEPTION_MESSAGE(HTTPException, BadRequest,
"Unsupported Amazon S3 Method: " <<
rRequest.GetMethodName());
}
}
catch (BoxException &ce)
{
SendInternalErrorResponse(ce.what(), rResponse);
// Override the default status code 500 for a few specific exceptions.
if(EXCEPTION_IS_TYPE(ce, CommonException, OSFileOpenError))
{
rResponse.SetResponseCode(HTTPResponse::Code_NotFound);
}
else if(EXCEPTION_IS_TYPE(ce, CommonException, AccessDenied))
{
rResponse.SetResponseCode(HTTPResponse::Code_Forbidden);
}
else if(EXCEPTION_IS_TYPE(ce, HTTPException, AuthenticationFailed))
{
rResponse.SetResponseCode(HTTPResponse::Code_Unauthorized);
}
else if(EXCEPTION_IS_TYPE(ce, HTTPException, BadRequest))
{
rResponse.SetResponseCode(HTTPResponse::Code_BadRequest);
}
}
catch (std::exception &e)
{
SendInternalErrorResponse(e.what(), rResponse);
}
catch (...)
{
SendInternalErrorResponse("Unknown exception", rResponse);
}
if (rResponse.GetResponseCode() != HTTPResponse::Code_OK &&
rResponse.GetResponseCode() != HTTPResponse::Code_NotModified &&
rResponse.GetResponseCode() != HTTPResponse::Code_NoContent &&
rResponse.GetSize() == 0)
{
// Looks like an error response with no error message specified,
// so write a default one.
std::ostringstream s;
s << rResponse.GetResponseCode();
SendInternalErrorResponse(s.str().c_str(), rResponse);
}
BOX_NOTICE(rResponse.GetResponseCode() << " " << rRequest.GetMethodName() << " " <<
rRequest.GetRequestURI());
return;
}
// --------------------------------------------------------------------------
//
// Function
// Name: S3Simulator::HandleGet(HTTPRequest &rRequest,
// HTTPResponse &rResponse)
// Purpose: Handles an S3 GET request, i.e. downloading an
// existing object.
// Created: 09/01/09
//
// --------------------------------------------------------------------------
void S3Simulator::HandleGet(HTTPRequest &rRequest, HTTPResponse &rResponse)
{
std::string path = GetConfiguration().GetKeyValue("StoreDirectory");
path += rRequest.GetRequestURI();
std::auto_ptr<FileStream> apFile;
apFile.reset(new FileStream(path));
rResponse.SetResponseCode(HTTPResponse::Code_OK);
if(true)
{
apFile->CopyStreamTo(rResponse);
// We allow the HTTPResponse to set the response size itself in this case,
// but we must add the ETag header. TODO: proper support for streaming
// responses will require us to set the content-length here, because we
// know it but the HTTPResponse does not.
rResponse.AddHeader("ETag", "\"828ef3fdfa96f00ad9f27c383fc9ac7f\"");
}
// http://docs.amazonwebservices.com/AmazonS3/2006-03-01/UsingRESTOperations.html
rResponse.AddHeader("x-amz-id-2", "qBmKRcEWBBhH6XAqsKU/eg24V3jf/kWKN9dJip1L/FpbYr9FDy7wWFurfdQOEMcY");
rResponse.AddHeader("x-amz-request-id", "F2A8CCCA26B4B26D");
rResponse.AddHeader("Date", "Wed, 01 Mar 2006 12:00:00 GMT");
rResponse.AddHeader("Last-Modified", "Sun, 1 Jan 2006 12:00:00 GMT");
rResponse.AddHeader("Server", "AmazonS3");
}
// --------------------------------------------------------------------------
//
// Function
// Name: S3Simulator::HandlePut(HTTPRequest &rRequest,
// HTTPResponse &rResponse)
// Purpose: Handles an S3 PUT request, i.e. uploading data to
// create or replace an object.
// Created: 09/01/09
//
// --------------------------------------------------------------------------
void S3Simulator::HandlePut(HTTPRequest &rRequest, HTTPResponse &rResponse)
{
std::string base_path = GetConfiguration().GetKeyValue("StoreDirectory");
std::auto_ptr<FileStream> apFile;
// Amazon S3 has no explicit directories or directory creation operation, but we
// are using the filesystem for storage, so we need to ensure that any directories
// used in the file's path actually exist before we can create the file itself.
std::string file_uri = rRequest.GetRequestURI();
for(std::string::size_type next_slash = file_uri.find('/', 1);
next_slash != std::string::npos;
next_slash = file_uri.find('/', next_slash + 1))
{
std::string parent_dir_path = base_path + file_uri.substr(0, next_slash);
object_exists_t what_exists = ObjectExists(parent_dir_path);
if(what_exists == ObjectExists_NoObject)
{
// Does not exist, need to create it
mkdir(parent_dir_path.c_str(), 0755);
}
else if(what_exists == ObjectExists_Dir)
{
// Directory already exists, nothing to do
}
else
{
THROW_EXCEPTION_MESSAGE(HTTPException, BadRequest,
"Cannot create directory: something else already exists "
"with this name: " << parent_dir_path);
}
}
std::string file_path = base_path + file_uri;
try
{
apFile.reset(new FileStream(file_path, O_CREAT | O_TRUNC | O_RDWR));
}
catch (CommonException &ce)
{
if (ce.GetSubType() == CommonException::OSFileOpenError)
{
rResponse.SetResponseCode(HTTPResponse::Code_NotFound);
}
else if (ce.GetSubType() == CommonException::AccessDenied)
{
rResponse.SetResponseCode(HTTPResponse::Code_Forbidden);
}
throw;
}
if (rRequest.IsExpectingContinue())
{
rResponse.SendContinue();
}
rRequest.ReadContent(*apFile, GetTimeout());
// http://docs.amazonwebservices.com/AmazonS3/2006-03-01/RESTObjectPUT.html
rResponse.AddHeader("x-amz-id-2", "LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7");
rResponse.AddHeader("x-amz-request-id", "F2A8CCCA26B4B26D");
rResponse.AddHeader("Date", "Wed, 01 Mar 2006 12:00:00 GMT");
rResponse.AddHeader("Last-Modified", "Sun, 1 Jan 2006 12:00:00 GMT");
rResponse.AddHeader("ETag", "\"828ef3fdfa96f00ad9f27c383fc9ac7f\"");
rResponse.SetContentType("");
rResponse.AddHeader("Server", "AmazonS3");
rResponse.SetResponseCode(HTTPResponse::Code_OK);
}