Class: EventMachine::HttpClient

Inherits:
Connection
  • Object
show all
Includes:
Deferrable, HttpEncoding
Defined in:
lib/em-http/client.rb

Constant Summary collapse

TRANSFER_ENCODING =
"TRANSFER_ENCODING"
CONTENT_ENCODING =
"CONTENT_ENCODING"
CONTENT_LENGTH =
"CONTENT_LENGTH"
KEEP_ALIVE =
"CONNECTION"
"SET_COOKIE"
LOCATION =
"LOCATION"
HOST =
"HOST"
CRLF =
"\r\n"

Constants included from HttpEncoding

EventMachine::HttpEncoding::BASIC_AUTH_ENCODING, EventMachine::HttpEncoding::FIELD_ENCODING, EventMachine::HttpEncoding::HTTP_REQUEST_HEADER

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from HttpEncoding

#encode_basic_auth, #encode_cookie, #encode_field, #encode_headers, #encode_host, #encode_param, #encode_query, #encode_request, #escape, #munge_header_keys, #unescape

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



183
184
185
# File 'lib/em-http/client.rb', line 183

def errors
  @errors
end

#methodObject

Returns the value of attribute method.



182
183
184
# File 'lib/em-http/client.rb', line 182

def method
  @method
end

#optionsObject

Returns the value of attribute options.



182
183
184
# File 'lib/em-http/client.rb', line 182

def options
  @options
end

#responseObject (readonly)

Returns the value of attribute response.



183
184
185
# File 'lib/em-http/client.rb', line 183

def response
  @response
end

#response_headerObject (readonly)

Returns the value of attribute response_header.



183
184
185
# File 'lib/em-http/client.rb', line 183

def response_header
  @response_header
end

#uriObject

Returns the value of attribute uri.



182
183
184
# File 'lib/em-http/client.rb', line 182

def uri
  @uri
end

Instance Method Details

#connection_completedObject

start HTTP request once we establish connection to host



200
201
202
203
204
205
206
# File 'lib/em-http/client.rb', line 200

def connection_completed
  ssl = @options[:tls] || @options[:ssl] || {}
  start_tls(ssl) if @uri.scheme == "https" or @uri.port == 443

  send_request_header
  send_request_body
end

#dispatchObject

Response processing



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
# File 'lib/em-http/client.rb', line 317

def dispatch
  while case @state
    when :response_header
      parse_response_header
    when :chunk_header
      parse_chunk_header
    when :chunk_body
      process_chunk_body
    when :chunk_footer
      process_chunk_footer
    when :response_footer
      process_response_footer
    when :body
      process_body
    when :finished, :invalid
      break
    else raise RuntimeError, "invalid state: #{@state}"
    end
  end
end

#normalize_bodyObject



232
233
234
235
236
237
238
# File 'lib/em-http/client.rb', line 232

def normalize_body
  if @options[:body].is_a? Hash
    @options[:body].to_params
  else
    @options[:body]
  end
end

#on_body_data(data) ⇒ Object

Called when part of the body has been read



284
285
286
287
288
289
290
291
292
293
294
# File 'lib/em-http/client.rb', line 284

def on_body_data(data)
  if @content_decoder
    begin
      @content_decoder << data
    rescue HttpDecoders::DecoderError
      on_error "Content-decoder error"
    end
  else
    on_decoded_body_data(data)
  end
end

#on_decoded_body_data(data) ⇒ Object



296
297
298
299
300
301
302
# File 'lib/em-http/client.rb', line 296

def on_decoded_body_data(data)
  if @stream
    @stream.call(data)
  else
    @response << data
  end
end

#on_error(msg, dns_error = false) ⇒ Object

request failed, invoke errback



219
220
221
222
223
224
225
# File 'lib/em-http/client.rb', line 219

def on_error(msg, dns_error = false)
  @errors = msg
  
  # no connection signature on DNS failures
  # fail the connection directly
  dns_error == true ? fail(self) : unbind
end

#on_request_completeObject

request is done, invoke the callback



209
210
211
212
213
214
215
216
# File 'lib/em-http/client.rb', line 209

def on_request_complete
  begin
    @content_decoder.finalize! if @content_decoder
  rescue HttpDecoders::DecoderError
    on_error "Content-decoder error"
  end
  unbind
end

#parse_chunk_headerObject



408
409
410
411
412
413
414
415
416
# File 'lib/em-http/client.rb', line 408

def parse_chunk_header
  return false unless parse_header(@chunk_header)

  @bytes_remaining = @chunk_header.chunk_size
  @chunk_header = HttpChunkHeader.new

  @state = @bytes_remaining > 0 ? :chunk_body : :response_footer
  true
end

#parse_header(header) ⇒ Object



338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'lib/em-http/client.rb', line 338

def parse_header(header)
  return false if @data.empty?

  begin
    @parser_nbytes = @parser.execute(header, @data.to_str, @parser_nbytes)
  rescue EventMachine::HttpClientParserError
    @state = :invalid
    on_error "invalid HTTP format, parsing fails"
  end

  return false unless @parser.finished?

  # Clear parsed data from the buffer
  @data.read(@parser_nbytes)
  @parser.reset
  @parser_nbytes = 0

  true
end

#parse_response_headerObject



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
# File 'lib/em-http/client.rb', line 358

def parse_response_header
  return false unless parse_header(@response_header)

  unless @response_header.http_status and @response_header.http_reason
    @state = :invalid
    on_error "no HTTP response"
    return false
  end

  # correct location header - some servers will incorrectly give a relative URI
  if @response_header.location
    begin
      location = URI.parse @response_header.location
      if location.relative?
        location = (@uri.merge location).to_s
        @response_header[LOCATION] = location
      end
    rescue
      on_error "Location header format error"
      return false
    end
  end

  # shortcircuit on HEAD requests 
  if @method == "HEAD"
    @state = :finished
    on_request_complete
  end

  if @response_header.chunked_encoding?
    @state = :chunk_header
  elsif @response_header.content_length
    @state = :body
    @bytes_remaining = @response_header.content_length 
  else
    @state = :body
    @bytes_remaining = nil
  end

  if decoder_class = HttpDecoders.decoder_for_encoding(response_header[CONTENT_ENCODING])
    begin
      @content_decoder = decoder_class.new do |s| on_decoded_body_data(s) end
    rescue HttpDecoders::DecoderError
      on_error "Content-decoder error"
    end
  end
  
  true
end

#post_initObject



185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/em-http/client.rb', line 185

def post_init
  @parser = HttpClientParser.new
  @data = EventMachine::Buffer.new
  @response_header = HttpResponseHeader.new
  @chunk_header = HttpChunkHeader.new

  @state = :response_header
  @parser_nbytes = 0
  @response = ''
  @errors = ''
  @content_decoder = nil
  @stream = nil
end

#process_bodyObject



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
# File 'lib/em-http/client.rb', line 464

def process_body
  if @bytes_remaining.nil?
    on_body_data @data.read
    return false
  end

  if @bytes_remaining.zero?
    @state = :finished
    on_request_complete
    return false
  end

  if @data.size < @bytes_remaining
    @bytes_remaining -= @data.size
    on_body_data @data.read
    return false
  end

  on_body_data @data.read(@bytes_remaining)
  @bytes_remaining = 0

  # If Keep-Alive is enabled, the server may be pushing more data to us
  # after the first request is complete. Hence, finish first request, and
  # reset state.
  if @response_header.keep_alive?
    @data.clear # hard reset, TODO: add support for keep-alive connections!
    @state = :finished
    on_request_complete

  else
    if @data.empty?
      @state = :finished
      on_request_complete
    else
      @state = :invalid
      on_error "garbage at end of body"
    end
  end

  false
end

#process_chunk_bodyObject



418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/em-http/client.rb', line 418

def process_chunk_body
  if @data.size < @bytes_remaining
    @bytes_remaining -= @data.size
    on_body_data @data.read
    return false
  end

  on_body_data @data.read(@bytes_remaining)
  @bytes_remaining = 0

  @state = :chunk_footer
  true
end


432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/em-http/client.rb', line 432

def process_chunk_footer
  return false if @data.size < 2

  if @data.read(2) == CRLF
    @state = :chunk_header
  else
    @state = :invalid
    on_error "non-CRLF chunk footer"
  end

  true
end


445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
# File 'lib/em-http/client.rb', line 445

def process_response_footer
  return false if @data.size < 2

  if @data.read(2) == CRLF
    if @data.empty?
      @state = :finished
      on_request_complete
    else
      @state = :invalid
      on_error "garbage at end of chunked response"
    end
  else
    @state = :invalid
    on_error "non-CRLF response footer"
  end

  false
end

#receive_data(data) ⇒ Object



278
279
280
281
# File 'lib/em-http/client.rb', line 278

def receive_data(data)
  @data << data
  dispatch
end

#send_request_bodyObject



272
273
274
275
276
# File 'lib/em-http/client.rb', line 272

def send_request_body
  return unless @options[:body]
  body = normalize_body
  send_data body
end

#send_request_headerObject



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
# File 'lib/em-http/client.rb', line 240

def send_request_header
  query   = @options[:query]
  head    = @options[:head] ? munge_header_keys(@options[:head]) : {}
  body    = normalize_body

  # Set the Host header if it hasn't been specified already
  head['host'] ||= encode_host

  # Set the Content-Length if body is given
  head['content-length'] =  body.length if body

  # Set the User-Agent if it hasn't been specified
  head['user-agent'] ||= "EventMachine HttpClient"

  # Set the cookie header if provided
  if cookie = head.delete('cookie')
    head['cookie'] = encode_cookie(cookie)
  end

  # Set content-type header if missing and body is a Ruby hash
  if not head['content-type'] and options[:body].is_a? Hash
    head['content-type'] = "application/x-www-form-urlencoded"
  end

  # Build the request
  request_header = encode_request(@method, @uri.path, query)
  request_header << encode_headers(head)
  request_header << CRLF

  send_data request_header
end

#stream(&blk) ⇒ Object

assign a stream processing block



228
229
230
# File 'lib/em-http/client.rb', line 228

def stream(&blk)
  @stream = blk
end

#unbindObject



304
305
306
307
308
309
310
311
# File 'lib/em-http/client.rb', line 304

def unbind
  if @state == :finished || (@state == :body && @bytes_remaining.nil?)
    succeed(self) 
  else
    fail(self)
  end
  close_connection
end