Class: Hydra5::Proxy

Inherits:
Object
  • Object
show all
Defined in:
lib/hydra5/proxy.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Proxy

Returns a new instance of Proxy.



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/hydra5/proxy.rb', line 15

def initialize(options)
  @listen = options.delete(:listen) || 8080
  @user = options.delete(:user) || 'root'
  @key = options.delete(:key)
  @log = Logger.new

  @hosts = options.delete(:hosts)
  @hosts = @hosts.inject({}) {|h,k| h[@hosts.index(k)] = k; h}

  @log.info "Establishing #{@hosts.size} SOCKS5 tunnels"
  @@live = {}
  @pids = []
end

Instance Method Details

#start!Object



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
# File 'lib/hydra5/proxy.rb', line 29

def start!
  EM.epoll
  EM.run do
    @hosts.each do |index, host|
      tunnel = <<-CMD
      ssh #{@user}@#{host} -D #{7000 + index} -NT
      -o StrictHostKeyChecking=no
      -o ServerAliveInterval=300
      -o ConnectTimeout=5
      -o ExitOnForwardFailure=yes
      -i #{@key}
      CMD

      @pids << EM.system(tunnel) do |cmd, out|
        @log.error ["Connection closed", out, @hosts[index]]
        @@live.delete(index)

        if @@live.empty?
          @log.info "No live tunnels left, exiting"
          exit
        end
      end

      @@live[index] = host
    end

    at_exit do
      pids = @pids.join(' ')
      unless system("kill #{pids}")
        @log.error "Could not kill all tunnels: #{pids}"
      end
    end

    @log.info "Starting proxy on port #{@listen}"

    ::Proxy.start(:host => "0.0.0.0", :port => @listen, :debug => @verbose) do |conn|
      tunnel = @@live.keys.shuffle.first

      puts "routing connection to #{@@live[tunnel]}"
      conn.server :srv, :host => "127.0.0.1", :port => 7000 + tunnel, :relay_client => true, :relay_server => true
    end
  end
end