File: proxy.rb

package info (click to toggle)
ruby-proxifier 1.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 112 kB
  • sloc: ruby: 341; makefile: 3
file content (63 lines) | stat: -rw-r--r-- 1,462 bytes parent folder | download | duplicates (3)
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
require "socket"
require "uri"
require "uri/socks"

module Proxifier
  class Proxy
    class << self
      def proxify?(host, no_proxy = nil)
        return true unless no_proxy

        dont_proxy = no_proxy.split(",")
        dont_proxy.none? { |h| host =~ /#{h}\Z/ }
      end
    end

    attr_reader :url, :options

    def initialize(url, options = {})
      url = URI.parse(uri) unless url.is_a?(URI::Generic)
      @url, @options = url, options
    end

    def open(host, port, local_host = nil, local_port = nil)
      return TCPSocket.new(host, port, local_host, local_port) unless proxify?(host)

      socket = TCPSocket.new(self.host, self.port, local_host, local_port)

      begin
        proxify(socket, host, port)
      rescue
        socket.close
        raise
      end

      socket
    end

    def proxify?(host)
      self.class.proxify?(host, options[:no_proxy])
    end

    def proxify(socket, host, port)
      do_proxify(socket, host, port)
    end

    %w(host port user password query version).each do |attr|
      class_eval "def #{attr}; url.#{attr} end"
    end

    def query_options
      @query_options ||= query ? Hash[query.split("&").map { |q| q.split("=") }] : {}
    end

    %w(no_proxy).each do |option|
      class_eval "def #{option}; options[:#{option}] end"
    end

    protected
      def do_proxify(socket, host, port)
        raise NotImplementedError, "#{self} must implement do_proxify"
      end
  end
end