Class: FakeS3::Servlet

Inherits:
WEBrick::HTTPServlet::AbstractServlet
  • Object
show all
Defined in:
lib/fakes3/server.rb

Instance Method Summary collapse

Constructor Details

#initialize(server, store, hostname) ⇒ Servlet

Returns a new instance of Servlet.



59
60
61
62
63
64
65
# File 'lib/fakes3/server.rb', line 59

def initialize(server,store,hostname)
  super(server)
  @store = store
  @hostname = hostname
  @port = server.config[:Port]
  @root_hostnames = [hostname,'localhost','s3.amazonaws.com','s3.localhost']
end

Instance Method Details

#do_DELETE(request, response) ⇒ Object



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/fakes3/server.rb', line 338

def do_DELETE(request, response)
  s_req = normalize_request(request)

  case s_req.type
  when Request::DELETE_OBJECTS
    bucket_obj = @store.get_bucket(s_req.bucket)
    keys = XmlParser.delete_objects(s_req.webrick_request)
    @store.delete_objects(bucket_obj,keys,s_req.webrick_request)
  when Request::DELETE_OBJECT
    bucket_obj = @store.get_bucket(s_req.bucket)
    @store.delete_object(bucket_obj,s_req.object,s_req.webrick_request)
  when Request::DELETE_BUCKET
    @store.delete_bucket(s_req.bucket)
  end

  response.status = 204
  response.body = ""
end

#do_GET(request, response) ⇒ Object



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
# File 'lib/fakes3/server.rb', line 74

def do_GET(request, response)
  s_req = normalize_request(request)

  case s_req.type
  when 'LIST_BUCKETS'
    response.status = 200
    response['Content-Type'] = 'application/xml'
    buckets = @store.buckets
    response.body = XmlAdapter.buckets(buckets)
  when 'LS_BUCKET'
    bucket_obj = @store.get_bucket(s_req.bucket)
    if bucket_obj
      response.status = 200
      response['Content-Type'] = "application/xml"
      query = {
        :marker => s_req.query["marker"] ? s_req.query["marker"].to_s : nil,
        :prefix => s_req.query["prefix"] ? s_req.query["prefix"].to_s : nil,
        :max_keys => s_req.query["max-keys"] ? s_req.query["max-keys"].to_i : nil,
        :delimiter => s_req.query["delimiter"] ? s_req.query["delimiter"].to_s : nil
      }
      bq = bucket_obj.query_for_range(query)
      response.body = XmlAdapter.bucket_query(bq)
    else
      response.status = 404
      response.body = XmlAdapter.error_no_such_bucket(s_req.bucket)
      response['Content-Type'] = "application/xml"
    end
  when 'GET_ACL'
    response.status = 200
    response.body = XmlAdapter.acl
    response['Content-Type'] = 'application/xml'
  when 'GET'
    real_obj = @store.get_object(s_req.bucket, s_req.object, request)
    if !real_obj
      response.status = 404
      response.body = XmlAdapter.error_no_such_key(s_req.object)
      response['Content-Type'] = "application/xml"
      return
    end

    if_none_match = request["If-None-Match"]
    if if_none_match == "\"#{real_obj.md5}\"" or if_none_match == "*"
      response.status = 304
      return
    end

    if_modified_since = request["If-Modified-Since"]
    if if_modified_since
      time = Time.httpdate(if_modified_since)
      if time >= Time.iso8601(real_obj.modified_date)
        response.status = 304
        return
      end
    end

    response.status = 200
    response['Content-Type'] = real_obj.content_type

    if real_obj.content_encoding
      response.header['X-Content-Encoding'] = real_obj.content_encoding
      response.header['Content-Encoding'] = real_obj.content_encoding
    end

    response['Content-Disposition'] = real_obj.content_disposition if real_obj.content_disposition
    stat = File::Stat.new(real_obj.io.path)

    response['Last-Modified'] = Time.iso8601(real_obj.modified_date).httpdate
    response.header['ETag'] = "\"#{real_obj.md5}\""
    response['Accept-Ranges'] = "bytes"
    response['Last-Ranges'] = "bytes"
    response['Access-Control-Allow-Origin'] = '*'

    real_obj..each do |header, value|
      response.header['x-amz-meta-' + header] = value
    end

    content_length = stat.size

    # Added Range Query support
    range = request.header["range"].first
    if range
      response.status = 206
      if range =~ /bytes=(\d*)-(\d*)/
        start = $1.to_i
        finish = $2.to_i
        finish_str = ""
        if finish == 0
          finish = content_length - 1
          finish_str = "#{finish}"
        else
          finish_str = finish.to_s
        end

        bytes_to_read = finish - start + 1
        response['Content-Range'] = "bytes #{start}-#{finish_str}/#{content_length}"
        real_obj.io.pos = start
        response.body = real_obj.io.read(bytes_to_read)
        return
      end
    end
    response['Content-Length'] = File::Stat.new(real_obj.io.path).size
    response['Content-Disposition'] = 'attachment'
    if s_req.http_verb == 'HEAD'
      response.body = ""
     real_obj.io.close
    else
      response.body = real_obj.io
    end
  end
end

#do_multipartPUT(request, response) ⇒ Object



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
# File 'lib/fakes3/server.rb', line 214

def do_multipartPUT(request, response)
  s_req = normalize_request(request)
  query = CGI::parse(request.request_uri.query)

  part_number   = query['partNumber'].first
  upload_id     = query['uploadId'].first
  part_name     = "#{upload_id}_#{s_req.object}_part#{part_number}"

  # store the part
  if s_req.type == Request::COPY
    real_obj = @store.copy_object(
      s_req.src_bucket, s_req.src_object,
      s_req.bucket    , part_name,
      request
    )

    response['Content-Type'] = "text/xml"
    response.body = XmlAdapter.copy_object_result real_obj
  else
    bucket_obj  = @store.get_bucket(s_req.bucket)
    if !bucket_obj
      bucket_obj = @store.create_bucket(s_req.bucket)
    end
    real_obj    = @store.store_object(
      bucket_obj, part_name,
      request
    )

    response.body   = ""
    response.header['ETag']  = "\"#{real_obj.md5}\""
  end

  response['Access-Control-Allow-Origin']   = '*'
  response['Access-Control-Allow-Headers']  = 'Authorization, Content-Length'
  response['Access-Control-Expose-Headers'] = 'ETag'

  response.status = 200
end

#do_OPTIONS(request, response) ⇒ Object



357
358
359
360
361
362
363
# File 'lib/fakes3/server.rb', line 357

def do_OPTIONS(request, response)
  super
  response['Access-Control-Allow-Origin']   = '*'
  response['Access-Control-Allow-Methods']  = 'PUT, POST, HEAD, GET, OPTIONS'
  response['Access-Control-Allow-Headers']  = 'Accept, Content-Type, Authorization, Content-Length, ETag, X-CSRF-Token, Content-Disposition'
  response['Access-Control-Expose-Headers'] = 'ETag'
end

#do_POST(request, response) ⇒ Object



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
# File 'lib/fakes3/server.rb', line 253

def do_POST(request,response)
  if request.query_string === 'delete'
    return do_DELETE(request, response)
  end

  s_req = normalize_request(request)
  key   = request.query['key']
  query = CGI::parse(request.request_uri.query || "")

  if query.has_key?('uploads')
    upload_id = SecureRandom.hex

    response.body = <<-eos.strip
      <?xml version="1.0" encoding="UTF-8"?>
      <InitiateMultipartUploadResult>
        <Bucket>#{ s_req.bucket }</Bucket>
        <Key>#{ key }</Key>
        <UploadId>#{ upload_id }</UploadId>
      </InitiateMultipartUploadResult>
    eos
  elsif query.has_key?('uploadId')
    upload_id  = query['uploadId'].first
    bucket_obj = @store.get_bucket(s_req.bucket)
    real_obj   = @store.combine_object_parts(
      bucket_obj,
      upload_id,
      s_req.object,
      parse_complete_multipart_upload(request),
      request
    )

    response.body = XmlAdapter.complete_multipart_result real_obj
  elsif request.content_type =~ /^multipart\/form-data; boundary=(.+)/
    key = request.query['key']

    success_action_redirect = request.query['success_action_redirect']
    success_action_status   = request.query['success_action_status']

    filename = 'default'
    filename = $1 if request.body =~ /filename="(.*)"/
    key      = key.gsub('${filename}', filename)

    bucket_obj = @store.get_bucket(s_req.bucket) || @store.create_bucket(s_req.bucket)
    real_obj   = @store.store_object(bucket_obj, key, s_req.webrick_request)

    response['Etag'] = "\"#{real_obj.md5}\""

    if success_action_redirect
      object_params = [ [ :bucket, s_req.bucket ], [ :key, key ] ]
      location_uri = URI.parse(success_action_redirect)
      original_location_params = URI.decode_www_form(String(location_uri.query))
      location_uri.query = URI.encode_www_form(original_location_params + object_params)

      response.status      = 303
      response.body        = ""
      response['Location'] = location_uri.to_s
    else
      response.status = success_action_status || 204
      if response.status == "201"

        str = request.inspect
        port = str[str.index('@port')+6..str[str.index('@port')..str.length].index(',')+str.index('@port')-1]
        host = str[str.index('@host')+7..str[str.index('@host')..str.length].index(',')+str.index('@host')-2]
        response.body = <<-eos.strip
          <?xml version="1.0" encoding="UTF-8"?>
          <PostResponse>
            <Location>http://#{host}:#{port}/#{s_req.bucket}/#{key}</Location>
            <Bucket>#{s_req.bucket}</Bucket>
            <Key>#{key}</Key>
            <inspect>#{str}</inspect>
            <ETag>#{response['Etag']}</ETag>
          </PostResponse>
        eos
      end
    end
  else
    raise WEBrick::HTTPStatus::BadRequest
  end

  response['Content-Type']                  = 'text/xml'
  response['Access-Control-Allow-Origin']   = '*'
  response['Access-Control-Allow-Headers']  = 'Authorization, Content-Length'
  response['Access-Control-Expose-Headers'] = 'ETag'
end

#do_PUT(request, response) ⇒ Object



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
# File 'lib/fakes3/server.rb', line 185

def do_PUT(request, response)
  s_req = normalize_request(request)
  query = CGI::parse(request.request_uri.query || "")

  return do_multipartPUT(request, response) if query['uploadId'].first

  response.status = 200
  response.body = ""
  response['Content-Type'] = "text/xml"
  response['Access-Control-Allow-Origin'] = '*'

  case s_req.type
  when Request::COPY
    object = @store.copy_object(s_req.src_bucket, s_req.src_object, s_req.bucket, s_req.object, request)
    response.body = XmlAdapter.copy_object_result(object)
  when Request::STORE
    bucket_obj = @store.get_bucket(s_req.bucket)
    if !bucket_obj
      # Lazily create a bucket.  TODO fix this to return the proper error
      bucket_obj = @store.create_bucket(s_req.bucket)
    end

    real_obj = @store.store_object(bucket_obj, s_req.object, s_req.webrick_request)
    response.header['ETag'] = "\"#{real_obj.md5}\""
  when Request::CREATE_BUCKET
    @store.create_bucket(s_req.bucket)
  end
end

#validate_request(request) ⇒ Object



67
68
69
70
71
72
# File 'lib/fakes3/server.rb', line 67

def validate_request(request)
  req = request.webrick_request
  return if req.nil?
  return if not req.header.has_key?('expect')
  req.continue if req.header['expect'].first=='100-continue'
end