# File lib/rye/hop.rb, line 246
246:     def connect(reconnect=true)
247:       raise Rye::NoHost unless @rye_host
248:       return if @rye_ssh && !reconnect
249:       disconnect if @rye_ssh 
250:       if @rye_via
251:         debug "Opening connection to #{@rye_host} as #{@rye_user}, via #{@rye_via.host}"
252:       else
253:         debug "Opening connection to #{@rye_host} as #{@rye_user}"
254:       end
255:       highline = HighLine.new # Used for password prompt
256:       retried = 0
257:       @rye_opts[:keys].compact!  # A quick fix in Windows. TODO: Why is there a nil?
258:       begin
259:         if @rye_via
260:           # tell the +Rye::Hop+ what and where to setup,
261:           # it returns the local port used
262:           @rye_localport = @rye_via.fetch_port(@rye_host, @rye_opts[:port].nil? ? 22 : @rye_opts[:port] )
263:           @rye_ssh = Net::SSH.start("localhost", @rye_user, @rye_opts.merge(:port => @rye_localport) || {}) 
264:         else
265:           @rye_ssh = Net::SSH.start(@rye_host, @rye_user, @rye_opts || {}) 
266:         end
267:         debug "starting the port forward thread"
268:         port_loop
269:       rescue Net::SSH::HostKeyMismatch => ex
270:         STDERR.puts ex.message
271:         print "\a" if @rye_info # Ring the bell
272:         if highline.ask("Continue? ").strip.match(/\Ay|yes|sure|ya\z/i)
273:           @rye_opts[:paranoid] = false
274:           retry
275:         else
276:           raise Net::SSH::HostKeyMismatch
277:         end
278:       rescue Net::SSH::AuthenticationFailed => ex
279:         print "\a" if retried == 0 && @rye_info # Ring the bell once
280:         retried += 1
281:         if STDIN.tty? && retried <= 3
282:           STDERR.puts "Passwordless login failed for #{@rye_user}"
283:           @rye_opts[:password] = highline.ask("Password: ") { |q| q.echo = '' }.strip
284:           @rye_opts[:auth_methods] ||= []
285:           @rye_opts[:auth_methods].push *['keyboard-interactive', 'password']
286:           retry
287:         else
288:           raise Net::SSH::AuthenticationFailed
289:         end
290:       end
291:       
292:       # We add :auth_methods (a Net::SSH joint) to force asking for a
293:       # password if the initial (key-based) authentication fails. We
294:       # need to delete the key from @rye_opts otherwise it lingers until
295:       # the next connection (if we switch_user is called for example).
296:       @rye_opts.delete :auth_methods if @rye_opts.has_key?(:auth_methods)
297:       
298:       self
299:     end