Class: Excon::Connection

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/excon/connection.rb

Constant Summary

Constants included from Utils

Utils::CONTROL, Utils::DELIMS, Utils::ESCAPED, Utils::NONASCII, Utils::UNESCAPED, Utils::UNWISE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils

#connection_uri, #escape_uri, #port_string, #query_string, #request_uri, #split_header_value, #unescape_form, #unescape_uri

Constructor Details

#initialize(params = {}) ⇒ Connection

Initializes a new Connection instance

@param [Hash<Symbol, >] params One or more optional params
  @option params [String] :body Default text to be sent over a socket. Only used if :body absent in Connection#request params
  @option params [Hash<Symbol, String>] :headers The default headers to supply in a request. Only used if params[:headers] is not supplied to Connection#request
  @option params [String] :host The destination host's reachable DNS name or IP, in the form of a String. IPv6 addresses must be wrapped (e.g. [::1]).  See URI#host.
  @option params [String] :hostname Same as host, but usable for socket connections. IPv6 addresses must not be wrapped (e.g. ::1).  See URI#hostname.
  @option params [String] :path Default path; appears after 'scheme://host:port/'. Only used if params[:path] is not supplied to Connection#request
  @option params [Fixnum] :port The port on which to connect, to the destination host
  @option params [Hash]   :query Default query; appended to the 'scheme://host:port/path/' in the form of '?key=value'. Will only be used if params[:query] is not supplied to Connection#request
  @option params [String] :scheme The protocol; 'https' causes OpenSSL to be used
  @option params [String] :socket The path to the unix socket (required for 'unix://' connections)
  @option params [String] :ciphers Only use the specified SSL/TLS cipher suites; use OpenSSL cipher spec format e.g. 'HIGH:!aNULL:!3DES' or 'AES256-SHA:DES-CBC3-SHA'
  @option params [String] :proxy Proxy server; e.g. 'http://myproxy.com:8888'
  @option params [Fixnum] :retry_limit Set how many times we'll retry a failed request.  (Default 4)
  @option params [Fixnum] :retry_interval Set how long to wait between retries. (Default 0)
  @option params [Class] :instrumentor Responds to #instrument as in ActiveSupport::Notifications
  @option params [String] :instrumentor_name Name prefix for #instrument events.  Defaults to 'excon'


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
# File 'lib/excon/connection.rb', line 62

def initialize(params = {})
  @data = Excon.defaults.dup
  # merge does not deep-dup, so make sure headers is not the original
  @data[:headers] = @data[:headers].dup

  # the same goes for :middlewares
  @data[:middlewares] = @data[:middlewares].dup

  params = validate_params(:connection, params)
  @data.merge!(params)

  setup_proxy

  if  ENV.has_key?('EXCON_STANDARD_INSTRUMENTOR')
    @data[:instrumentor] = Excon::StandardInstrumentor
  end

  if @data[:debug] || ENV.has_key?('EXCON_DEBUG')
    @data[:debug_request] = @data[:debug_response] = true
    @data[:instrumentor] = Excon::StandardInstrumentor
  end

  if @data[:scheme] == UNIX
    if @data[:host]
      raise ArgumentError, "The `:host` parameter should not be set for `unix://` connections.\n" +
                           "When supplying a `unix://` URI, it should start with `unix:/` or `unix:///`."
    elsif !@data[:socket]
      raise ArgumentError, 'You must provide a `:socket` for `unix://` connections'
    else
      @socket_key = "#{@data[:scheme]}://#{@data[:socket]}"
    end
  else
    @socket_key = "#{@data[:scheme]}://#{@data[:host]}#{port_string(@data)}"
  end
  reset
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



6
7
8
# File 'lib/excon/connection.rb', line 6

def data
  @data
end

Instance Method Details

#batch_requests(pipeline_params, limit = nil) ⇒ Object

Sends the supplied requests to the destination host using pipelining in batches of @limit [Numeric] requests. This is your soft file descriptor limit by default, typically 256.

@pipeline_params [Array<Hash>] pipeline_params An array of one or more optional params, override defaults set in Connection.new, see #request for details


318
319
320
321
322
323
324
325
326
327
# File 'lib/excon/connection.rb', line 318

def batch_requests(pipeline_params, limit = nil)
  limit ||= Process.respond_to?(:getrlimit) ? Process.getrlimit(:NOFILE).first : 256
  responses = []

  pipeline_params.each_slice(limit) do |params|
    responses.concat(requests(params))
  end

  responses
end

#connectionObject



8
9
10
11
# File 'lib/excon/connection.rb', line 8

def connection
  Excon.display_warning('Excon::Connection#connection is deprecated use Excon::Connection#data instead.')
  @data
end

#connection=(new_params) ⇒ Object



12
13
14
15
# File 'lib/excon/connection.rb', line 12

def connection=(new_params)
  Excon.display_warning('Excon::Connection#connection= is deprecated. Use of this method may cause unexpected results.')
  @data = new_params
end

#error_call(datum) ⇒ Object



99
100
101
102
103
# File 'lib/excon/connection.rb', line 99

def error_call(datum)
  if datum[:error]
    raise(datum[:error])
  end
end

#inspectObject



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/excon/connection.rb', line 354

def inspect
  vars = instance_variables.inject({}) do |accum, var|
    accum.merge!(var.to_sym => instance_variable_get(var))
  end
  if vars[:'@data'][:headers].has_key?('Authorization')
    vars[:'@data'] = vars[:'@data'].dup
    vars[:'@data'][:headers] = vars[:'@data'][:headers].dup
    vars[:'@data'][:headers]['Authorization'] = REDACTED
  end
  if vars[:'@data'][:password]
    vars[:'@data'] = vars[:'@data'].dup
    vars[:'@data'][:password] = REDACTED
  end
  inspection = '#<Excon::Connection:'
  inspection += (object_id << 1).to_s(16)
  vars.each do |key, value|
    inspection += " #{key}=#{value.inspect}"
  end
  inspection += '>'
  inspection
end

#loggerObject



35
36
37
38
39
# File 'lib/excon/connection.rb', line 35

def logger
  if @data[:instrumentor] && @data[:instrumentor].respond_to?(:logger)
    @data[:instrumentor].logger
  end
end

#logger=(logger) ⇒ Object



40
41
42
43
# File 'lib/excon/connection.rb', line 40

def logger=(logger)
  Excon::LoggingInstrumentor.logger = logger
  @data[:instrumentor] = Excon::LoggingInstrumentor
end

#paramsObject



17
18
19
20
# File 'lib/excon/connection.rb', line 17

def params
  Excon.display_warning('Excon::Connection#params is deprecated use Excon::Connection#data instead.')
  @data
end

#params=(new_params) ⇒ Object



21
22
23
24
# File 'lib/excon/connection.rb', line 21

def params=(new_params)
  Excon.display_warning('Excon::Connection#params= is deprecated. Use of this method may cause unexpected results.')
  @data = new_params
end

#proxyObject



26
27
28
29
# File 'lib/excon/connection.rb', line 26

def proxy
  Excon.display_warning('Excon::Connection#proxy is deprecated use Excon::Connection#data[:proxy] instead.')
  @data[:proxy]
end

#proxy=(new_proxy) ⇒ Object



30
31
32
33
# File 'lib/excon/connection.rb', line 30

def proxy=(new_proxy)
  Excon.display_warning('Excon::Connection#proxy= is deprecated. Use of this method may cause unexpected results.')
  @data[:proxy] = new_proxy
end

#request(params = {}, &block) ⇒ Object

Sends the supplied request to the destination host.

@yield [chunk] @see Response#self.parse
@param [Hash<Symbol, >] params One or more optional params, override defaults set in Connection.new
  @option params [String] :body text to be sent over a socket
  @option params [Hash<Symbol, String>] :headers The default headers to supply in a request
  @option params [String] :path appears after 'scheme://host:port/'
  @option params [Hash]   :query appended to the 'scheme://host:port/path/' in the form of '?key=value'


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
# File 'lib/excon/connection.rb', line 225

def request(params={}, &block)
  params = validate_params(:request, params)
  # @data has defaults, merge in new params to override
  datum = @data.merge(params)
  datum[:headers] = @data[:headers].merge(datum[:headers] || {})

  if datum[:user] || datum[:password]
    user, pass = Utils.unescape_uri(datum[:user].to_s), Utils.unescape_uri(datum[:password].to_s)
    datum[:headers]['Authorization'] ||= 'Basic ' + ["#{user}:#{pass}"].pack('m').delete(Excon::CR_NL)
  end

  if datum[:scheme] == UNIX
    datum[:headers]['Host']   ||= ''
  else
    datum[:headers]['Host']   ||= datum[:host] + port_string(datum)
  end
  datum[:retries_remaining] ||= datum[:retry_limit]

  # if path is empty or doesn't start with '/', insert one
  unless datum[:path][0, 1] == '/'
    datum[:path] = datum[:path].dup.insert(0, '/')
  end

  if block_given?
    Excon.display_warning('Excon requests with a block are deprecated, pass :response_block instead.')
    datum[:response_block] = Proc.new
  end

  datum[:connection] = self

  datum[:stack] = datum[:middlewares].map do |middleware|
    lambda {|stack| middleware.new(stack)}
  end.reverse.inject(self) do |middlewares, middleware|
    middleware.call(middlewares)
  end
  datum = datum[:stack].request_call(datum)

  unless datum[:pipeline]
    datum = response(datum)

    if datum[:persistent]
      if key = datum[:response][:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
        if datum[:response][:headers][key].casecmp('close') == 0
          reset
        end
      end
    else
      reset
    end

    Excon::Response.new(datum[:response])
  else
    datum
  end
rescue => error
  reset
  datum[:error] = error
  if datum[:stack]
    datum[:stack].error_call(datum)
  else
    raise error
  end
end

#request_call(datum) ⇒ Object



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
# File 'lib/excon/connection.rb', line 105

def request_call(datum)
  begin
    if datum.has_key?(:response)
      # we already have data from a middleware, so bail
      return datum
    else
      socket.data = datum
      # start with "METHOD /path"
      request = datum[:method].to_s.upcase + ' '
      if datum[:proxy] && datum[:scheme] != HTTPS
        request << datum[:scheme] << '://' << datum[:host] << port_string(datum)
      end
      request << datum[:path]

      # add query to path, if there is one
      request << query_string(datum)

      # finish first line with "HTTP/1.1\r\n"
      request << HTTP_1_1

      if datum.has_key?(:request_block)
        datum[:headers]['Transfer-Encoding'] = 'chunked'
      else
        body = datum[:body].is_a?(String) ? StringIO.new(datum[:body]) : datum[:body]

        # The HTTP spec isn't clear on it, but specifically, GET requests don't usually send bodies;
        # if they don't, sending Content-Length:0 can cause issues.
        unless datum[:method].to_s.casecmp('GET') == 0 && body.nil?
          unless datum[:headers].has_key?('Content-Length')
            datum[:headers]['Content-Length'] = detect_content_length(body)
          end
        end
      end

      # add headers to request
      datum[:headers].each do |key, values|
        [values].flatten.each do |value|
          request << key.to_s << ': ' << value.to_s << CR_NL
        end
      end

      # add additional "\r\n" to indicate end of headers
      request << CR_NL

      if datum.has_key?(:request_block)
        socket.write(request) # write out request + headers
        while true # write out body with chunked encoding
          chunk = datum[:request_block].call
          if FORCE_ENC
            chunk.force_encoding('BINARY')
          end
          if chunk.length > 0
            socket.write(chunk.length.to_s(16) << CR_NL << chunk << CR_NL)
          else
            socket.write(String.new("0#{CR_NL}#{CR_NL}"))
            break
          end
        end
      elsif body.nil?
        socket.write(request) # write out request + headers
      else # write out body
        if body.respond_to?(:binmode)
          body.binmode
        end
        if body.respond_to?(:rewind)
          body.rewind  rescue nil
        end

        # if request + headers is less than chunk size, fill with body
        if FORCE_ENC
          request.force_encoding('BINARY')
        end
        chunk = body.read([datum[:chunk_size] - request.length, 0].max)
        if chunk
          if FORCE_ENC
            chunk.force_encoding('BINARY')
          end
          socket.write(request << chunk)
        else
          socket.write(request) # write out request + headers
        end

        while chunk = body.read(datum[:chunk_size])
          socket.write(chunk)
        end
      end
    end
  rescue => error
    case error
    when Excon::Errors::StubNotFound, Excon::Errors::Timeout
      raise(error)
    else
      raise_socket_error(error)
    end
  end

  datum
end

#requests(pipeline_params) ⇒ Object

Sends the supplied requests to the destination host using pipelining.

@pipeline_params [Array<Hash>] pipeline_params An array of one or more optional params, override defaults set in Connection.new, see #request for details


291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/excon/connection.rb', line 291

def requests(pipeline_params)
  pipeline_params.each {|params| params.merge!(:pipeline => true, :persistent => true) }
  pipeline_params.last.merge!(:persistent => @data[:persistent])

  responses = pipeline_params.map do |params|
    request(params)
  end.map do |datum|
    Excon::Response.new(response(datum)[:response])
  end

  if @data[:persistent]
    if key = responses.last[:headers].keys.detect {|k| k.casecmp('Connection') == 0 }
      if responses.last[:headers][key].casecmp('close') == 0
        reset
      end
    end
  else
    reset
  end

  responses
end

#resetObject



329
330
331
332
333
# File 'lib/excon/connection.rb', line 329

def reset
  if old_socket = sockets.delete(@socket_key)
    old_socket.close rescue nil
  end
end

#response_call(datum) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/excon/connection.rb', line 204

def response_call(datum)
  # ensure response_block is yielded to and body is empty from middlewares
  if datum.has_key?(:response_block) && !(datum[:response][:body].nil? || datum[:response][:body].empty?)
    response_body = datum[:response][:body].dup
    datum[:response][:body] = ''
    content_length = remaining = response_body.bytesize
    while remaining > 0
      datum[:response_block].call(response_body.slice!(0, [datum[:chunk_size], remaining].min), [remaining - datum[:chunk_size], 0].max, content_length)
      remaining -= datum[:chunk_size]
    end
  end
  datum
end

#retry_limitObject



349
350
351
352
# File 'lib/excon/connection.rb', line 349

def retry_limit
  Excon.display_warning('Excon::Connection#retry_limit is deprecated, use Excon::Connection#data[:retry_limit].')
  @data[:retry_limit] ||= DEFAULT_RETRY_LIMIT
end

#retry_limit=(new_retry_limit) ⇒ Object



344
345
346
347
# File 'lib/excon/connection.rb', line 344

def retry_limit=(new_retry_limit)
  Excon.display_warning('Excon::Connection#retry_limit= is deprecated, pass :retry_limit to the initializer.')
  @data[:retry_limit] = new_retry_limit
end