Files
metasploit-gs/lib/net/ssh/connection/channel.rb
T
Tod Beardsley 4bcbdc54c9 Cutting over rails3 to master.
This switches the Metasploit Framework to a Rails 3 backend. If you run
into new problems (especially around Active Record or your postgresql
gem) you should try first updating your Ruby installation to 1.9.3 and
use a more recent 'pg' gem.

If that fails, we'd love to see your bug report (just drop all the
detail you can into an issue on GitHub). In the meantime, you can
checkout the rails2 branch, which was branched from master immediately
before this cutover.

Squashed commit of the following:

commit 5802ec851580341c6717dfea529027c12678d35f
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 23:30:12 2012 -0500

    Enable MSF_BUNDLE_GEMS mode by default (set to N/F/0 to disable)

commit 8102f98dce9eb0c73c4374e40dce09af7b51d060
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 23:30:03 2012 -0500

    Add a method to expand win32 file paths

commit bda6479d154cf75572dd5de8b66bfde661a55de9
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 18:53:44 2012 -0500

    Fix 1.8.x compatibility

commit 101ce4eb17bfdf755ef8c0a5198174668b6cd6fd
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 18:40:59 2012 -0500

    Use verbose instead of stringio

commit 5db467ffb593488285576d183b1662093e454b3e
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 18:30:06 2012 -0500

    Hide the iconv warning, were stuck with it due to EBCDIC support

commit 63b9cb20eb6a61daf4effb4c8d2761c16ff0c4e0
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 18:29:58 2012 -0500

    Dont use GEM_HOME by default

commit ca49271c22c314a4465fff934334df18c704cbc0
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 18:23:34 2012 -0500

    Move Gemfile to root (there be dragons, lets find them) and catch failed bundler loads

commit 34af04076a068e9f60c5526045ddbba5fca359fd
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 18:18:29 2012 -0500

    Fallback to bundler when not running inside of a installer env

commit ed1066a4f3f12fae7d4afc03eb1ab70ffe2f9cf3
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 16:26:55 2012 -0500

    Remove a mess of gems that were not actually required

commit 21290a73926809e9049a59359449168f740d13d2
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 15:59:10 2012 -0500

    Hack around a gem() call that is well-intentioned but an obstacle in this case

commit 8e414a8bfab9641c81088d22f73033be5b37a700
Author: Tod Beardsley <todb@metasploit.com>
Date:   Sun Apr 15 15:06:08 2012 -0500

    Ruby, come on. Ducktype this. Please.

    Use interpolated strings to get the to_s behavior you don't get with
    just plussing.

commit 0fa92c58750f8f84edbecfaab72cd2da5062743f
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 15:05:42 2012 -0500

    Add new eventmachine/thin gems

commit 819d5e7d45e0a16741d3852df3ed110b4d7abc44
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 15:01:18 2012 -0500

    Purge (reimport in a second)

commit ea6f3f6c434537ca15b6c6674e31081e27ce7f86
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 14:54:42 2012 -0500

    Cleanup uncessary .so files (ext vs lib)

commit d219330a3cc563e9da9f01fade016c9ed8cda21c
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 14:53:02 2012 -0500

    PG gems built against the older installation environment

commit d6e590cfa331ae7b25313ff1471c6148a6b36f3b
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 14:06:35 2012 -0500

    Rename to include the version

commit a893de222b97ce1222a55324f1811b0262aae2d0
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 13:56:47 2012 -0500

    Detect older installation environments and load the arch-lib directories into the search path

commit 6444bba0a421921e2ebe2df2323277a586f9736f
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 13:49:25 2012 -0500

    Merge in windows gems

commit 95efbcfde220917bc7ee08e6083d7b383240d185
Author: Tod Beardsley <todb@metasploit.com>
Date:   Sun Apr 15 13:49:33 2012 -0500

    Report_vuln shouldn't use :include in finder

    find_or_create_by doesn't take :include as a param.

commit c5f99eb87f0874ef7d32fa42828841c9a714b787
Author: David Maloney <DMaloney@rapid7.com>
Date:   Sun Apr 15 12:44:09 2012 -0500

    One more msised Mdm namespace issue

commit 2184e2bbc3dd9b0993e8f21d2811a65a0c694d68
Author: David Maloney <DMaloney@rapid7.com>
Date:   Sun Apr 15 12:33:41 2012 -0500

    Fixes some mroe Mdm namespace confusion
    Fixes #6626

commit 10cee17f391f398bb2be3409137ff7348c7a66ee
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 03:40:44 2012 -0500

    Add robots gem (required by webscan)

commit 327e674c83850101364c9cca8f8d16da1de3dfb5
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 03:39:05 2012 -0500

    Fix missing error checks

commit a5a24641866e47e611d7636a3f19ba3b3ed10ac5
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 01:15:37 2012 -0500

    Reorder requires and add a method for injecting a new migration path

commit 250a5fa5ae8cb05807af022aa4168907772c15f8
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 00:56:09 2012 -0500

    Remove missing constant (use string) and add gemcache cleaner

commit 37ad6063fce0a41dddedb857fa49aa2c4834a508
Merge: d47ee82 4be0361
Author: Tod Beardsley <todb@metasploit.com>
Date:   Sun Apr 15 00:40:16 2012 -0500

    Merge branch 'master-clone' into rails3-clone

commit d47ee82ad7e66de53dd3d3a65649cc37299a2479
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 00:30:03 2012 -0500

    cleanup leftovers from gems

commit 6d883b5aa8a3a7ddbcde5bfd4521d57c5b30d3c2
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sun Apr 15 00:25:47 2012 -0500

    MDM update with purged DBSave module

commit 71e4f2d81f6da221b76150562a16c730888f5925
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 23:19:37 2012 -0500

    Add new mdm

commit 651cd5adac8211d65e0c8079371d8264e549533a
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 23:19:13 2012 -0500

    Update mdm

commit 0191a8bd0acec30ddb2a9e9c291111a12378537f
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 22:30:40 2012 -0500

    This fixes numerous cases of missed Mdm:: prefixes on db objects

commit a2a9bb3f2148622c135663dead80b3367b6f7695
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 18:30:18 2012 -0500

    Add eventmachine

commit 301ddeb12b906ed3c508613ca894347bedc3b499
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 18:18:12 2012 -0500

    A nicer error for folks who need to upgrade pg

commit fa6bde1e67b12e2d3d9978f59bbc98e0c1a1a707
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 17:54:55 2012 -0500

    Remove bundler requirements

commit 2e3ab9ed211303f1116e602b9a450141b71e56a4
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 17:35:38 2012 -0500

    Pull in eventmachine with actual .so's this time

commit 901fb33ff6b754ce2c2cfd51e3b0b669f6ec600b
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 17:19:12 2012 -0500

    Update deps, still need to add eventmachine

commit 6b0e17068e8caa0601f3ef81e8dbdb672758fcbe
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 13:07:06 2012 -0500

    Handle older installer environments and only allow binary gems when the
    environment specifically asks for it

commit b98eb7873a6342834840424699caa414a5cb172a
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 04:05:13 2012 -0500

    Bump version to -testing

commit 6ac508c4ba3fdc278aaf8cfe2c58d01de3395431
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 02:25:09 2012 -0500

    Remove msf3 subdir

commit a27dac5067635a95b4cbb773df1985f2a2dc2c5a
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 02:24:39 2012 -0500

    Remove the old busted external

commit 5fb5a0fc642b6c301934c319db854cc3145427a1
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 02:03:10 2012 -0500

    Add the gemcache loader

commit 09e2d89dfd09b9ac0c123fcc4e19816c86725627
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Apr 14 02:02:23 2012 -0500

    Purge gemfile/bundler configure in exchange for new gemcache setup

commit 3cc0264e1cfb027b515d7f24b95a74b023bd905c
Author: Tod Beardsley <todb@metasploit.com>
Date:   Thu Apr 12 14:11:45 2012 -0500

    Mode change on modicon_ladder.apx

commit c18b3d56efd639e461137acdc76b4b283fe978d4
Author: HD Moore <hd_moore@rapid7.com>
Date:   Thu Apr 12 01:38:56 2012 -0500

    The go faster button

commit ca2a67d51d6d4c7c3ca2e745f8b018279aef668a
Merge: 674ee09 b8129f9
Author: Tod Beardsley <todb@metasploit.com>
Date:   Mon Apr 9 15:50:33 2012 -0500

    Merge branch 'master-clone' into rails3-clone

    Picking up Packetfu upstream changes, all pretty minor

commit 674ee097ab8a6bc9608bf377479ccd0b87e7302b
Merge: e9513e5 a26e844
Author: Tod Beardsley <todb@metasploit.com>
Date:   Mon Apr 9 13:57:26 2012 -0500

    Merge branch 'master-clone' into rails3-clone

    Conflicts:
    	lib/msf/core/handler/reverse_http.rb
    	lib/msf/core/handler/reverse_https.rb
    	modules/auxiliary/scanner/discovery/udp_probe.rb
    	modules/auxiliary/scanner/discovery/udp_sweep.rb

    Resolved conflicts with the reverse_http handlers and the udp probe /
    scanners byt favoring the more recent changes (which happened to be the
    intent anyway). The reverse_http and reverse_https changes were mine so
    I know what the intent was, and @dmaloney-r7 changed udp_probe and
    udp_sweep to use pcAnywhere_stat instead of merely pcAnywhere, so the
    intent is clear there as well.

commit e9513e54f984fdb100c13b44a1724246779ccb76
Author: David Maloney <dmaloney@melodie.gateway.2wire.net>
Date:   Fri Apr 6 18:21:46 2012 -0500

    Some fixes to how services get reported to prevent issues with the web interface

commit adeb44e9aaf1a329a0e587d2b26e678398730422
Author: David Maloney <David_Maloney@rapid7.com>
Date:   Mon Apr 2 15:39:46 2012 -0500

    Some corrections to pcAnywhere discovery modules to distinguish between the two services

commit b13900176484fea8f5217a2ef925ae2ad9b7af47
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Mar 31 12:03:21 2012 -0500

    Enable additional migration-path parameters, use a temporary directory to bring the database online

commit 526b4c56883f461417f71269404faef38639917c
Author: David Maloney <David_Maloney@rapid7.com>
Date:   Wed Mar 28 23:24:56 2012 -0500

    A bunch of Mdsm fixes for .kind_of? calls, to make sure we ponit to the right place

commit 2cf3143370af808637d164ce59400605300f922c
Author: HD Moore <hd_moore@rapid7.com>
Date:   Mon Mar 26 16:22:09 2012 -0500

    Check for ruby 2.0 as well as 1.9 for encoding override

commit 4d0f51b76d89f00f7acbce6b1f00dc6e4c4545ee
Author: HD Moore <hd_moore@rapid7.com>
Date:   Mon Mar 26 15:36:04 2012 -0500

    Remove debug statement

commit f5d2335e7745aa1a354f4d6c8fc9d0b3876c472a
Author: HD Moore <hd_moore@rapid7.com>
Date:   Mon Mar 26 15:01:55 2012 -0500

    Be explicit about the Mdm namespace

commit bc8be225606d6ea38dd2a85ab4310c1c181a94ee
Author: hdm <hdm@hypo.(none)>
Date:   Mon Mar 26 11:49:51 2012 -0500

    Precalculate some uri strings in case the 1000-round generation fails

commit 4254f419723349ffb93e4aebdaeabbd7d66bf8c0
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Sat Mar 24 14:03:44 2012 -0500

    Removed some non-namespaced calls to Host

commit c8190e1bb8ad365fb0d7a1c4a9173e6c739be85c
Author: HD Moore <hd_moore@rapid7.com>
Date:   Tue Mar 20 00:37:00 2012 -0500

    Purge the rvmrc, this is causing major headaches

commit 76df18588917b7150a3bedf2569710a80bab51f8
Author: HD Moore <hd_moore@rapid7.com>
Date:   Tue Mar 20 00:31:52 2012 -0500

    Switch .rvmrc to the shipping 1.9.3 version

commit 7124971d00
Author: David Maloney <David_Maloney@rapid7.com>
Date:   Mon Mar 12 16:56:40 2012 -0500

    Adds mixin for looking up Mime Types by extension

commit b7ca835316
Merge: a0b0c75 6b9a219
Author: Matt Buck <techpeace@gmail.com>
Date:   Tue Mar 6 19:38:53 2012 -0600

    Merge from develop.

commit a0b0c7528d
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Tue Mar 6 11:08:59 2012 -0600

    Somehow migration file is new?

commit 84d2b3cb1a
Author: David Maloney <David_Maloney@rapid7.com>
Date:   Wed Feb 29 16:38:55 2012 -0600

    Added ability to specify headers to redirects in http server

commit e50d27cda8
Author: HD Moore <hd_moore@rapid7.com>
Date:   Sat Feb 4 04:44:50 2012 -0600

    Tweak the event dispatcher to enable customer events without a category
    and trigger http request events from the main exploit mixin.
    Experimental

commit 0e4fd2040d
Author: Matt Buck <Matthew_Buck@rapid7.com>
Date:   Thu Feb 2 22:09:05 2012 -0600

    Change Msm -> Mdm in migrations. This is what was preventing migrations from finishing on first boot.

commit c94a2961d0
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Wed Feb 1 12:48:48 2012 -0600

    Changed Gemfile to use new gem name

commit 245c2063f0
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Wed Feb 1 12:47:42 2012 -0600

    Did find/replace for final namespace of Mdm

commit 6ed9bf8430
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Tue Jan 24 10:47:44 2012 -0600

    Fix a bunch of namespace issues

commit 2fe08d9e42
Author: Matt Buck <Matthew_Buck@rapid7.com>
Date:   Fri Jan 20 14:37:37 2012 -0600

    Update Msm contstants in migrations for initial DB builds.

commit 4cc6b8fb04
Author: Matt Buck <Matthew_Buck@rapid7.com>
Date:   Fri Jan 20 14:37:25 2012 -0600

    Update Gemfile.lock.

commit 1cc655b678
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Thu Jan 19 11:48:29 2012 -0600

    Errant Workspaces needed namespace

commit 607a782855
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Tue Jan 17 15:44:02 2012 -0600

    Refactored all models to use the new namespace

    * Every model using DBManager::* namespace is now Msm namespace
    * Almost all of this in msf/base/core
    * Some in modules

commit a690cd959b
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Tue Jan 17 13:41:44 2012 -0600

    Move bundler setup

commit dae115cc8f
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Mon Jan 9 15:51:07 2012 -0600

    Moved ActiveSupport dep to gem

commit d32f8edb6e
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Mon Jan 9 14:40:05 2012 -0600

    Removed model require file

commit d0c74cff8c
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Tue Jan 3 16:06:10 2012 -0600

    Update some more finds

commit 4eb79ea6b5
Author: Trevor Rosen <Trevor_Rosen@rapid7.com>
Date:   Tue Jan 3 14:21:15 2012 -0600

    Yet another dumb commit

commit a75febcb59
Author: Trevor Rosen <trevor@catapult-creative.com>
Date:   Thu Dec 29 19:20:51 2011 -0600

    Fixing deletion

commit dc139ff2fd
Author: Trevor Rosen <trevor@catapult-creative.com>
Date:   Wed Dec 7 17:06:45 2011 -0600

    Fixed erroneous commit

commit 531c1e611c
Author: Trevor Rosen <trevor@catapult-creative.com>
Date:   Mon Nov 21 16:11:35 2011 -0600

    Remove AR patch stuff; attempting to debug non-connection between MSF and Pro

commit 4586112241
Author: Trevor Rosen <trevor@catapult-creative.com>
Date:   Fri Nov 18 16:17:27 2011 -0600

    Drop ActiveRecord/ActiveSupport in preparation for upgrade
2012-04-15 23:35:38 -05:00

626 lines
25 KiB
Ruby

require 'net/ssh/loggable'
require 'net/ssh/connection/constants'
require 'net/ssh/connection/term'
module Net; module SSH; module Connection
# The channel abstraction. Multiple "channels" can be multiplexed onto a
# single SSH channel, each operating independently and seemingly in parallel.
# This class represents a single such channel. Most operations performed
# with the Net::SSH library will involve using one or more channels.
#
# Channels are intended to be used asynchronously. You request that one be
# opened (via Connection::Session#open_channel), and when it is opened, your
# callback is invoked. Then, you set various other callbacks on the newly
# opened channel, which are called in response to the corresponding events.
# Programming with Net::SSH works best if you think of your programs as
# state machines. Complex programs are best implemented as objects that
# wrap a channel. See Net::SCP and Net::SFTP for examples of how complex
# state machines can be built on top of the SSH protocol.
#
# ssh.open_channel do |channel|
# channel.exec("/invoke/some/command") do |ch, success|
# abort "could not execute command" unless success
#
# channel.on_data do |ch, data|
# puts "got stdout: #{data}"
# channel.send_data "something for stdin\n"
# end
#
# channel.on_extended_data do |ch, type, data|
# puts "got stderr: #{data}"
# end
#
# channel.on_close do |ch|
# puts "channel is closing!"
# end
# end
# end
#
# ssh.loop
#
# Channels also have a basic hash-like interface, that allows programs to
# store arbitrary state information on a channel object. This helps simplify
# the writing of state machines, especially when you may be juggling
# multiple open channels at the same time.
#
# Note that data sent across SSH channels are governed by maximum packet
# sizes and maximum window sizes. These details are managed internally
# by Net::SSH::Connection::Channel, so you may remain blissfully ignorant
# if you so desire, but you can always inspect the current maximums, as
# well as the remaining window size, using the reader attributes for those
# values.
class Channel
include Constants, Loggable
# The local id for this channel, assigned by the Net::SSH::Connection::Session instance.
attr_reader :local_id
# The remote id for this channel, assigned by the remote host.
attr_reader :remote_id
# The type of this channel, usually "session".
attr_reader :type
# The underlying Net::SSH::Connection::Session instance that supports this channel.
attr_reader :connection
# The maximum packet size that the local host can receive.
attr_reader :local_maximum_packet_size
# The maximum amount of data that the local end of this channel can
# receive. This is a total, not per-packet.
attr_reader :local_maximum_window_size
# The maximum packet size that the remote host can receive.
attr_reader :remote_maximum_packet_size
# The maximum amount of data that the remote end of this channel can
# receive. This is a total, not per-packet.
attr_reader :remote_maximum_window_size
# This is the remaining window size on the local end of this channel. When
# this reaches zero, no more data can be received.
attr_reader :local_window_size
# This is the remaining window size on the remote end of this channel. When
# this reaches zero, no more data can be sent.
attr_reader :remote_window_size
# A hash of properties for this channel. These can be used to store state
# information about this channel. See also #[] and #[]=.
attr_reader :properties
# The output buffer for this channel. Data written to the channel is
# enqueued here, to be written as CHANNEL_DATA packets during each pass of
# the event loop. See Connection::Session#process and #enqueue_pending_output.
attr_reader :output #:nodoc:
# The list of pending requests. Each time a request is sent which requires
# a reply, the corresponding callback is pushed onto this queue. As responses
# arrive, they are shifted off the front and handled.
attr_reader :pending_requests #:nodoc:
# Instantiates a new channel on the given connection, of the given type,
# and with the given id. If a block is given, it will be remembered until
# the channel is confirmed open by the server, and will be invoked at
# that time (see #do_open_confirmation).
#
# This also sets the default maximum packet size and maximum window size.
def initialize(connection, type, local_id, &on_confirm_open)
self.logger = connection.logger
@connection = connection
@type = type
@local_id = local_id
@local_maximum_packet_size = 0x10000
@local_window_size = @local_maximum_window_size = 0x20000
@on_confirm_open = on_confirm_open
@output = Buffer.new
@properties = {}
@pending_requests = []
@on_open_failed = @on_data = @on_extended_data = @on_process = @on_close = @on_eof = nil
@on_request = {}
@closing = @eof = false
end
# A shortcut for accessing properties of the channel (see #properties).
def [](name)
@properties[name]
end
# A shortcut for setting properties of the channel (see #properties).
def []=(name, value)
@properties[name] = value
end
# Syntactic sugar for executing a command. Sends a channel request asking
# that the given command be invoked. If the block is given, it will be
# called when the server responds. The first parameter will be the
# channel, and the second will be true or false, indicating whether the
# request succeeded or not. In this case, success means that the command
# is being executed, not that it has completed, and failure means that the
# command altogether failed to be executed.
#
# channel.exec "ls -l /home" do |ch, success|
# if success
# puts "command has begun executing..."
# # this is a good place to hang callbacks like #on_data...
# else
# puts "alas! the command could not be invoked!"
# end
# end
def exec(command, &block)
send_channel_request("exec", :string, command, &block)
end
# Syntactic sugar for requesting that a subsystem be started. Subsystems
# are a way for other protocols (like SFTP) to be run, using SSH as
# the transport. Generally, you'll never need to call this directly unless
# you are the implementor of something that consumes an SSH subsystem, like
# SFTP.
#
# channel.subsystem("sftp") do |ch, success|
# if success
# puts "subsystem successfully started"
# else
# puts "subsystem could not be started"
# end
# end
def subsystem(subsystem, &block)
send_channel_request("subsystem", :string, subsystem, &block)
end
# Syntactic sugar for setting an environment variable in the remote
# process' environment. Note that for security reasons, the server may
# refuse to set certain environment variables, or all, at the server's
# discretion. If you are connecting to an OpenSSH server, you will
# need to update the AcceptEnv setting in the sshd_config to include the
# environment variables you want to send.
#
# channel.env "PATH", "/usr/local/bin"
def env(variable_name, variable_value, &block)
send_channel_request("env", :string, variable_name, :string, variable_value, &block)
end
# A hash of the valid PTY options (see #request_pty).
VALID_PTY_OPTIONS = { :term => "xterm",
:chars_wide => 80,
:chars_high => 24,
:pixels_wide => 640,
:pixels_high => 480,
:modes => {} }
# Requests that a pseudo-tty (or "pty") be made available for this channel.
# This is useful when you want to invoke and interact with some kind of
# screen-based program (e.g., vim, or some menuing system).
#
# Note, that without a pty some programs (e.g. sudo, or subversion) on
# some systems, will not be able to run interactively, and will error
# instead of prompt if they ever need some user interaction.
#
# Note, too, that when a pty is requested, user's shell configuration
# scripts (.bashrc and such) are not run by default, whereas they are
# run when a pty is not present.
#
# channel.request_pty do |ch, success|
# if success
# puts "pty successfully obtained"
# else
# puts "could not obtain pty"
# end
# end
def request_pty(opts={}, &block)
extra = opts.keys - VALID_PTY_OPTIONS.keys
raise ArgumentError, "invalid option(s) to request_pty: #{extra.inspect}" if extra.any?
opts = VALID_PTY_OPTIONS.merge(opts)
modes = opts[:modes].inject(Buffer.new) do |memo, (mode, data)|
memo.write_byte(mode).write_long(data)
end
# mark the end of the mode opcode list with a 0 byte
modes.write_byte(0)
send_channel_request("pty-req", :string, opts[:term],
:long, opts[:chars_wide], :long, opts[:chars_high],
:long, opts[:pixels_wide], :long, opts[:pixels_high],
:string, modes.to_s, &block)
end
# Sends data to the channel's remote endpoint. This usually has the
# effect of sending the given string to the remote process' stdin stream.
# Note that it does not immediately send the data across the channel,
# but instead merely appends the given data to the channel's output buffer,
# preparatory to being packaged up and sent out the next time the connection
# is accepting data. (A connection might not be accepting data if, for
# instance, it has filled its data window and has not yet been resized by
# the remote end-point.)
#
# This will raise an exception if the channel has previously declared
# that no more data will be sent (see #eof!).
#
# channel.send_data("the password\n")
def send_data(data)
raise EOFError, "cannot send data if channel has declared eof" if eof?
output.append(data.to_s)
end
# Returns true if the channel exists in the channel list of the session,
# and false otherwise. This can be used to determine whether a channel has
# been closed or not.
#
# ssh.loop { channel.active? }
def active?
connection.channels.key?(local_id)
end
# Runs the SSH event loop until the channel is no longer active. This is
# handy for blocking while you wait for some channel to finish.
#
# channel.exec("grep ...") { ... }
# channel.wait
def wait
connection.loop { active? }
end
# Returns true if the channel is currently closing, but not actually
# closed. A channel is closing when, for instance, #close has been
# invoked, but the server has not yet responded with a CHANNEL_CLOSE
# packet of its own.
def closing?
@closing
end
# Requests that the channel be closed. If the channel is already closing,
# this does nothing, nor does it do anything if the channel has not yet
# been confirmed open (see #do_open_confirmation). Otherwise, it sends a
# CHANNEL_CLOSE message and marks the channel as closing.
def close
return if @closing
if remote_id
@closing = true
connection.send_message(Buffer.from(:byte, CHANNEL_CLOSE, :long, remote_id))
end
end
# Returns true if the local end of the channel has declared that no more
# data is forthcoming (see #eof!). Trying to send data via #send_data when
# this is true will result in an exception being raised.
def eof?
@eof
end
# Tells the remote end of the channel that no more data is forthcoming
# from this end of the channel. The remote end may still send data.
def eof!
return if eof?
@eof = true
connection.send_message(Buffer.from(:byte, CHANNEL_EOF, :long, remote_id))
end
# If an #on_process handler has been set up, this will cause it to be
# invoked (passing the channel itself as an argument). It also causes all
# pending output to be enqueued as CHANNEL_DATA packets (see #enqueue_pending_output).
def process
@on_process.call(self) if @on_process
enqueue_pending_output
end
# Registers a callback to be invoked when data packets are received by the
# channel. The callback is called with the channel as the first argument,
# and the data as the second.
#
# channel.on_data do |ch, data|
# puts "got data: #{data.inspect}"
# end
#
# Data received this way is typically the data written by the remote
# process to its +stdout+ stream.
def on_data(&block)
old, @on_data = @on_data, block
old
end
# Registers a callback to be invoked when extended data packets are received
# by the channel. The callback is called with the channel as the first
# argument, the data type (as an integer) as the second, and the data as
# the third. Extended data is almost exclusively used to send +stderr+ data
# (+type+ == 1). Other extended data types are not defined by the SSH
# protocol.
#
# channel.on_extended_data do |ch, type, data|
# puts "got stderr: #{data.inspect}"
# end
def on_extended_data(&block)
old, @on_extended_data = @on_extended_data, block
old
end
# Registers a callback to be invoked for each pass of the event loop for
# this channel. There are no guarantees on timeliness in the event loop,
# but it will be called roughly once for each packet received by the
# connection (not the channel). This callback is invoked with the channel
# as the sole argument.
#
# Here's an example that accumulates the channel data into a variable on
# the channel itself, and displays individual lines in the input one
# at a time when the channel is processed:
#
# channel[:data] = ""
#
# channel.on_data do |ch, data|
# channel[:data] << data
# end
#
# channel.on_process do |ch|
# if channel[:data] =~ /^.*?\n/
# puts $&
# channel[:data] = $'
# end
# end
def on_process(&block)
old, @on_process = @on_process, block
old
end
# Registers a callback to be invoked when the server acknowledges that a
# channel is closed. This is invoked with the channel as the sole argument.
#
# channel.on_close do |ch|
# puts "remote end is closing!"
# end
def on_close(&block)
old, @on_close = @on_close, block
old
end
# Registers a callback to be invoked when the server indicates that no more
# data will be sent to the channel (although the channel can still send
# data to the server). The channel is the sole argument to the callback.
#
# channel.on_eof do |ch|
# puts "remote end is done sending data"
# end
def on_eof(&block)
old, @on_eof = @on_eof, block
old
end
# Registers a callback to be invoked when the server was unable to open
# the requested channel. The channel itself will be passed to the block,
# along with the integer "reason code" for the failure, and a textual
# description of the failure from the server.
#
# channel = session.open_channel do |ch|
# # ..
# end
#
# channel.on_open_failed { |ch, code, desc| ... }
def on_open_failed(&block)
old, @on_open_failed = @on_open_failed, block
old
end
# Registers a callback to be invoked when a channel request of the given
# type is received. The callback will receive the channel as the first
# argument, and the associated (unparsed) data as the second. The data
# will be a Net::SSH::Buffer that you will need to parse, yourself,
# according to the kind of request you are watching.
#
# By default, if the request wants a reply, Net::SSH will send a
# CHANNEL_SUCCESS response for any request that was handled by a registered
# callback, and CHANNEL_FAILURE for any that wasn't, but if you want your
# registered callback to result in a CHANNEL_FAILURE response, just raise
# Net::SSH::ChannelRequestFailed.
#
# Some common channel requests that your programs might want to listen
# for are:
#
# * "exit-status" : the exit status of the remote process will be reported
# as a long integer in the data buffer, which you can grab via
# data.read_long.
# * "exit-signal" : if the remote process died as a result of a signal
# being sent to it, the signal will be reported as a string in the
# data, via data.read_string. (Not all SSH servers support this channel
# request type.)
#
# channel.on_request "exit-status" do |ch, data|
# puts "process terminated with exit status: #{data.read_long}"
# end
def on_request(type, &block)
old, @on_request[type] = @on_request[type], block
old
end
# Sends a new channel request with the given name. The extra +data+
# parameter must either be empty, or consist of an even number of
# arguments. See Net::SSH::Buffer.from for a description of their format.
# If a block is given, it is registered as a callback for a pending
# request, and the packet will be flagged so that the server knows a
# reply is required. If no block is given, the server will send no
# response to this request. Responses, where required, will cause the
# callback to be invoked with the channel as the first argument, and
# either true or false as the second, depending on whether the request
# succeeded or not. The meaning of "success" and "failure" in this context
# is dependent on the specific request that was sent.
#
# channel.send_channel_request "shell" do |ch, success|
# if success
# puts "user shell started successfully"
# else
# puts "could not start user shell"
# end
# end
#
# Most channel requests you'll want to send are already wrapped in more
# convenient helper methods (see #exec and #subsystem).
def send_channel_request(request_name, *data, &callback)
info { "sending channel request #{request_name.inspect}" }
msg = Buffer.from(:byte, CHANNEL_REQUEST,
:long, remote_id, :string, request_name,
:bool, !callback.nil?, *data)
connection.send_message(msg)
pending_requests << callback if callback
end
public # these methods are public, but for Net::SSH internal use only
# Enqueues pending output at the connection as CHANNEL_DATA packets. This
# does nothing if the channel has not yet been confirmed open (see
# #do_open_confirmation). This is called automatically by #process, which
# is called from the event loop (Connection::Session#process). You will
# generally not need to invoke it directly.
def enqueue_pending_output #:nodoc:
return unless remote_id
while output.length > 0
length = output.length
length = remote_window_size if length > remote_window_size
length = remote_maximum_packet_size if length > remote_maximum_packet_size
if length > 0
connection.send_message(Buffer.from(:byte, CHANNEL_DATA, :long, remote_id, :string, output.read(length)))
output.consume!
@remote_window_size -= length
else
break
end
end
end
# Invoked when the server confirms that a channel has been opened.
# The remote_id is the id of the channel as assigned by the remote host,
# and max_window and max_packet are the maximum window and maximum
# packet sizes, respectively. If an open-confirmation callback was
# given when the channel was created, it is invoked at this time with
# the channel itself as the sole argument.
def do_open_confirmation(remote_id, max_window, max_packet) #:nodoc:
@remote_id = remote_id
@remote_window_size = @remote_maximum_window_size = max_window
@remote_maximum_packet_size = max_packet
connection.forward.agent(self) if connection.options[:forward_agent] && type == "session"
@on_confirm_open.call(self) if @on_confirm_open
end
# Invoked when the server failed to open the channel. If an #on_open_failed
# callback was specified, it will be invoked with the channel, reason code,
# and description as arguments. Otherwise, a ChannelOpenFailed exception
# will be raised.
def do_open_failed(reason_code, description)
if @on_open_failed
@on_open_failed.call(self, reason_code, description)
else
raise ChannelOpenFailed.new(reason_code, description)
end
end
# Invoked when the server sends a CHANNEL_WINDOW_ADJUST packet, and
# causes the remote window size to be adjusted upwards by the given
# number of bytes. This has the effect of allowing more data to be sent
# from the local end to the remote end of the channel.
def do_window_adjust(bytes) #:nodoc:
@remote_maximum_window_size += bytes
@remote_window_size += bytes
end
# Invoked when the server sends a channel request. If any #on_request
# callback has been registered for the specific type of this request,
# it is invoked. If +want_reply+ is true, a packet will be sent of
# either CHANNEL_SUCCESS or CHANNEL_FAILURE type. If there was no callback
# to handle the request, CHANNEL_FAILURE will be sent. Otherwise,
# CHANNEL_SUCCESS, unless the callback raised ChannelRequestFailed. The
# callback should accept the channel as the first argument, and the
# request-specific data as the second.
def do_request(request, want_reply, data) #:nodoc:
result = true
begin
callback = @on_request[request] or raise ChannelRequestFailed
callback.call(self, data)
rescue ChannelRequestFailed
result = false
end
if want_reply
msg = Buffer.from(:byte, result ? CHANNEL_SUCCESS : CHANNEL_FAILURE, :long, remote_id)
connection.send_message(msg)
end
end
# Invokes the #on_data callback when the server sends data to the
# channel. This will reduce the available window size on the local end,
# but does not actually throttle requests that come in illegally when
# the window size is too small. The callback is invoked with the channel
# as the first argument, and the data as the second.
def do_data(data) #:nodoc:
update_local_window_size(data.length)
@on_data.call(self, data) if @on_data
end
# Invokes the #on_extended_data callback when the server sends
# extended data to the channel. This will reduce the available window
# size on the local end. The callback is invoked with the channel,
# type, and data.
def do_extended_data(type, data)
update_local_window_size(data.length)
@on_extended_data.call(self, type, data) if @on_extended_data
end
# Invokes the #on_eof callback when the server indicates that no
# further data is forthcoming. The callback is invoked with the channel
# as the argument.
def do_eof
@on_eof.call(self) if @on_eof
end
# Invokes the #on_close callback when the server closes a channel.
# The channel is the only argument.
def do_close
@on_close.call(self) if @on_close
end
# Invokes the next pending request callback with +false+ as the second
# argument.
def do_failure
if callback = pending_requests.shift
callback.call(self, false)
else
error { "channel failure recieved with no pending request to handle it (bug?)" }
end
end
# Invokes the next pending request callback with +true+ as the second
# argument.
def do_success
if callback = pending_requests.shift
callback.call(self, true)
else
error { "channel success recieved with no pending request to handle it (bug?)" }
end
end
private
# Updates the local window size by the given amount. If the window
# size drops to less than half of the local maximum (an arbitrary
# threshold), a CHANNEL_WINDOW_ADJUST message will be sent to the
# server telling it that the window size has grown.
def update_local_window_size(size)
@local_window_size -= size
if local_window_size < local_maximum_window_size/2
connection.send_message(Buffer.from(:byte, CHANNEL_WINDOW_ADJUST,
:long, remote_id, :long, 0x20000))
@local_window_size += 0x20000
@local_maximum_window_size += 0x20000
end
end
end
end; end; end