net-ssh 4.2.0 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. checksums.yaml +5 -5
  2. checksums.yaml.gz.sig +0 -0
  3. data/.dockerignore +6 -0
  4. data/.github/config/rubocop_linter_action.yml +4 -0
  5. data/.github/workflows/ci-with-docker.yml +44 -0
  6. data/.github/workflows/ci.yml +87 -0
  7. data/.github/workflows/rubocop.yml +13 -0
  8. data/.gitignore +7 -0
  9. data/.rubocop.yml +19 -2
  10. data/.rubocop_todo.yml +619 -667
  11. data/CHANGES.txt +110 -1
  12. data/Dockerfile +27 -0
  13. data/Dockerfile.openssl3 +17 -0
  14. data/Gemfile +3 -7
  15. data/{Gemfile.norbnacl → Gemfile.noed25519} +3 -1
  16. data/Manifest +4 -5
  17. data/README.md +293 -0
  18. data/Rakefile +45 -29
  19. data/appveyor.yml +8 -6
  20. data/docker-compose.yml +23 -0
  21. data/lib/net/ssh/authentication/agent.rb +248 -223
  22. data/lib/net/ssh/authentication/certificate.rb +178 -164
  23. data/lib/net/ssh/authentication/constants.rb +17 -15
  24. data/lib/net/ssh/authentication/ed25519.rb +141 -116
  25. data/lib/net/ssh/authentication/ed25519_loader.rb +28 -28
  26. data/lib/net/ssh/authentication/key_manager.rb +79 -36
  27. data/lib/net/ssh/authentication/methods/abstract.rb +62 -47
  28. data/lib/net/ssh/authentication/methods/hostbased.rb +34 -37
  29. data/lib/net/ssh/authentication/methods/keyboard_interactive.rb +3 -3
  30. data/lib/net/ssh/authentication/methods/none.rb +16 -19
  31. data/lib/net/ssh/authentication/methods/password.rb +15 -16
  32. data/lib/net/ssh/authentication/methods/publickey.rb +96 -55
  33. data/lib/net/ssh/authentication/pageant.rb +468 -465
  34. data/lib/net/ssh/authentication/pub_key_fingerprint.rb +43 -0
  35. data/lib/net/ssh/authentication/session.rb +131 -122
  36. data/lib/net/ssh/buffer.rb +385 -332
  37. data/lib/net/ssh/buffered_io.rb +150 -151
  38. data/lib/net/ssh/config.rb +316 -239
  39. data/lib/net/ssh/connection/channel.rb +635 -613
  40. data/lib/net/ssh/connection/constants.rb +29 -29
  41. data/lib/net/ssh/connection/event_loop.rb +104 -95
  42. data/lib/net/ssh/connection/keepalive.rb +55 -51
  43. data/lib/net/ssh/connection/session.rb +614 -611
  44. data/lib/net/ssh/connection/term.rb +125 -123
  45. data/lib/net/ssh/errors.rb +101 -99
  46. data/lib/net/ssh/key_factory.rb +194 -108
  47. data/lib/net/ssh/known_hosts.rb +212 -134
  48. data/lib/net/ssh/loggable.rb +50 -49
  49. data/lib/net/ssh/packet.rb +83 -79
  50. data/lib/net/ssh/prompt.rb +51 -51
  51. data/lib/net/ssh/proxy/command.rb +105 -91
  52. data/lib/net/ssh/proxy/errors.rb +12 -10
  53. data/lib/net/ssh/proxy/http.rb +81 -81
  54. data/lib/net/ssh/proxy/https.rb +37 -36
  55. data/lib/net/ssh/proxy/jump.rb +49 -48
  56. data/lib/net/ssh/proxy/socks4.rb +2 -6
  57. data/lib/net/ssh/proxy/socks5.rb +14 -17
  58. data/lib/net/ssh/service/forward.rb +365 -362
  59. data/lib/net/ssh/test/channel.rb +145 -143
  60. data/lib/net/ssh/test/extensions.rb +131 -127
  61. data/lib/net/ssh/test/kex.rb +34 -32
  62. data/lib/net/ssh/test/local_packet.rb +46 -44
  63. data/lib/net/ssh/test/packet.rb +87 -84
  64. data/lib/net/ssh/test/remote_packet.rb +32 -30
  65. data/lib/net/ssh/test/script.rb +155 -155
  66. data/lib/net/ssh/test/socket.rb +49 -48
  67. data/lib/net/ssh/test.rb +82 -80
  68. data/lib/net/ssh/transport/algorithms.rb +433 -364
  69. data/lib/net/ssh/transport/cipher_factory.rb +95 -91
  70. data/lib/net/ssh/transport/constants.rb +32 -24
  71. data/lib/net/ssh/transport/ctr.rb +37 -15
  72. data/lib/net/ssh/transport/hmac/abstract.rb +81 -63
  73. data/lib/net/ssh/transport/hmac/md5.rb +0 -2
  74. data/lib/net/ssh/transport/hmac/md5_96.rb +0 -2
  75. data/lib/net/ssh/transport/hmac/none.rb +0 -2
  76. data/lib/net/ssh/transport/hmac/ripemd160.rb +0 -2
  77. data/lib/net/ssh/transport/hmac/sha1.rb +0 -2
  78. data/lib/net/ssh/transport/hmac/sha1_96.rb +0 -2
  79. data/lib/net/ssh/transport/hmac/sha2_256.rb +7 -11
  80. data/lib/net/ssh/transport/hmac/sha2_256_96.rb +4 -8
  81. data/lib/net/ssh/transport/hmac/sha2_256_etm.rb +12 -0
  82. data/lib/net/ssh/transport/hmac/sha2_512.rb +6 -9
  83. data/lib/net/ssh/transport/hmac/sha2_512_96.rb +4 -8
  84. data/lib/net/ssh/transport/hmac/sha2_512_etm.rb +12 -0
  85. data/lib/net/ssh/transport/hmac.rb +14 -12
  86. data/lib/net/ssh/transport/identity_cipher.rb +54 -52
  87. data/lib/net/ssh/transport/kex/abstract.rb +130 -0
  88. data/lib/net/ssh/transport/kex/abstract5656.rb +72 -0
  89. data/lib/net/ssh/transport/kex/curve25519_sha256.rb +39 -0
  90. data/lib/net/ssh/transport/kex/curve25519_sha256_loader.rb +30 -0
  91. data/lib/net/ssh/transport/kex/diffie_hellman_group14_sha1.rb +33 -40
  92. data/lib/net/ssh/transport/kex/diffie_hellman_group14_sha256.rb +11 -0
  93. data/lib/net/ssh/transport/kex/diffie_hellman_group1_sha1.rb +112 -217
  94. data/lib/net/ssh/transport/kex/diffie_hellman_group_exchange_sha1.rb +53 -63
  95. data/lib/net/ssh/transport/kex/diffie_hellman_group_exchange_sha256.rb +5 -9
  96. data/lib/net/ssh/transport/kex/ecdh_sha2_nistp256.rb +36 -90
  97. data/lib/net/ssh/transport/kex/ecdh_sha2_nistp384.rb +18 -10
  98. data/lib/net/ssh/transport/kex/ecdh_sha2_nistp521.rb +18 -10
  99. data/lib/net/ssh/transport/kex.rb +15 -12
  100. data/lib/net/ssh/transport/key_expander.rb +24 -21
  101. data/lib/net/ssh/transport/openssl.rb +158 -133
  102. data/lib/net/ssh/transport/packet_stream.rb +223 -191
  103. data/lib/net/ssh/transport/server_version.rb +55 -56
  104. data/lib/net/ssh/transport/session.rb +306 -259
  105. data/lib/net/ssh/transport/state.rb +178 -176
  106. data/lib/net/ssh/verifiers/accept_new.rb +33 -0
  107. data/lib/net/ssh/verifiers/accept_new_or_local_tunnel.rb +33 -0
  108. data/lib/net/ssh/verifiers/always.rb +58 -0
  109. data/lib/net/ssh/verifiers/never.rb +19 -0
  110. data/lib/net/ssh/version.rb +55 -53
  111. data/lib/net/ssh.rb +47 -34
  112. data/net-ssh-public_cert.pem +18 -19
  113. data/net-ssh.gemspec +12 -11
  114. data/support/ssh_tunnel_bug.rb +5 -5
  115. data.tar.gz.sig +0 -0
  116. metadata +78 -73
  117. metadata.gz.sig +0 -0
  118. data/.travis.yml +0 -51
  119. data/Gemfile.norbnacl.lock +0 -41
  120. data/README.rdoc +0 -169
  121. data/lib/net/ssh/ruby_compat.rb +0 -24
  122. data/lib/net/ssh/verifiers/lenient.rb +0 -30
  123. data/lib/net/ssh/verifiers/null.rb +0 -12
  124. data/lib/net/ssh/verifiers/secure.rb +0 -52
  125. data/lib/net/ssh/verifiers/strict.rb +0 -24
  126. data/support/arcfour_check.rb +0 -20
@@ -1,709 +1,712 @@
1
1
  require 'net/ssh/loggable'
2
- require 'net/ssh/ruby_compat'
3
2
  require 'net/ssh/connection/channel'
4
3
  require 'net/ssh/connection/constants'
5
4
  require 'net/ssh/service/forward'
6
5
  require 'net/ssh/connection/keepalive'
7
6
  require 'net/ssh/connection/event_loop'
8
7
 
9
- module Net; module SSH; module Connection
10
-
11
- # A session class representing the connection service running on top of
12
- # the SSH transport layer. It manages the creation of channels (see
13
- # #open_channel), and the dispatching of messages to the various channels.
14
- # It also encapsulates the SSH event loop (via #loop and #process),
15
- # and serves as a central point-of-reference for all SSH-related services (e.g.
16
- # port forwarding, SFTP, SCP, etc.).
17
- #
18
- # You will rarely (if ever) need to instantiate this class directly; rather,
19
- # you'll almost always use Net::SSH.start to initialize a new network
20
- # connection, authenticate a user, and return a new connection session,
21
- # all in one call.
22
- #
23
- # Net::SSH.start("localhost", "user") do |ssh|
24
- # # 'ssh' is an instance of Net::SSH::Connection::Session
25
- # ssh.exec! "/etc/init.d/some_process start"
26
- # end
27
- class Session
28
- include Constants, Loggable
29
-
30
- # Default IO.select timeout threshold
31
- DEFAULT_IO_SELECT_TIMEOUT = 300
32
-
33
- # The underlying transport layer abstraction (see Net::SSH::Transport::Session).
34
- attr_reader :transport
35
-
36
- # The map of options that were used to initialize this instance.
37
- attr_reader :options
38
-
39
- # The collection of custom properties for this instance. (See #[] and #[]=).
40
- attr_reader :properties
41
-
42
- # The map of channels, each key being the local-id for the channel.
43
- attr_reader :channels #:nodoc:
44
-
45
- # The map of listeners that the event loop knows about. See #listen_to.
46
- attr_reader :listeners #:nodoc:
47
-
48
- # The map of specialized handlers for opening specific channel types. See
49
- # #on_open_channel.
50
- attr_reader :channel_open_handlers #:nodoc:
51
-
52
- # The list of callbacks for pending requests. See #send_global_request.
53
- attr_reader :pending_requests #:nodoc:
54
-
55
- class NilChannel
56
- def initialize(session)
57
- @session = session
58
- end
8
+ module Net
9
+ module SSH
10
+ module Connection
11
+ # A session class representing the connection service running on top of
12
+ # the SSH transport layer. It manages the creation of channels (see
13
+ # #open_channel), and the dispatching of messages to the various channels.
14
+ # It also encapsulates the SSH event loop (via #loop and #process),
15
+ # and serves as a central point-of-reference for all SSH-related services (e.g.
16
+ # port forwarding, SFTP, SCP, etc.).
17
+ #
18
+ # You will rarely (if ever) need to instantiate this class directly; rather,
19
+ # you'll almost always use Net::SSH.start to initialize a new network
20
+ # connection, authenticate a user, and return a new connection session,
21
+ # all in one call.
22
+ #
23
+ # Net::SSH.start("localhost", "user") do |ssh|
24
+ # # 'ssh' is an instance of Net::SSH::Connection::Session
25
+ # ssh.exec! "/etc/init.d/some_process start"
26
+ # end
27
+ class Session
28
+ include Loggable
29
+ include Constants
30
+
31
+ # Default IO.select timeout threshold
32
+ DEFAULT_IO_SELECT_TIMEOUT = 300
33
+
34
+ # The underlying transport layer abstraction (see Net::SSH::Transport::Session).
35
+ attr_reader :transport
36
+
37
+ # The map of options that were used to initialize this instance.
38
+ attr_reader :options
39
+
40
+ # The collection of custom properties for this instance. (See #[] and #[]=).
41
+ attr_reader :properties
42
+
43
+ # The map of channels, each key being the local-id for the channel.
44
+ attr_reader :channels # :nodoc:
45
+
46
+ # The map of listeners that the event loop knows about. See #listen_to.
47
+ attr_reader :listeners # :nodoc:
48
+
49
+ # The map of specialized handlers for opening specific channel types. See
50
+ # #on_open_channel.
51
+ attr_reader :channel_open_handlers # :nodoc:
52
+
53
+ # The list of callbacks for pending requests. See #send_global_request.
54
+ attr_reader :pending_requests # :nodoc:
55
+
56
+ class NilChannel
57
+ def initialize(session)
58
+ @session = session
59
+ end
59
60
 
60
- def method_missing(sym, *args)
61
- @session.lwarn { "ignoring request #{sym.inspect} for non-existent (closed?) channel; probably ssh server bug" }
62
- end
63
- end
61
+ def method_missing(sym, *args)
62
+ @session.lwarn { "ignoring request #{sym.inspect} for non-existent (closed?) channel; probably ssh server bug" }
63
+ end
64
+ end
64
65
 
65
- # Create a new connection service instance atop the given transport
66
- # layer. Initializes the listeners to be only the underlying socket object.
67
- def initialize(transport, options={})
68
- self.logger = transport.logger
66
+ # Create a new connection service instance atop the given transport
67
+ # layer. Initializes the listeners to be only the underlying socket object.
68
+ def initialize(transport, options = {})
69
+ self.logger = transport.logger
69
70
 
70
- @transport = transport
71
- @options = options
71
+ @transport = transport
72
+ @options = options
72
73
 
73
- @channel_id_counter = -1
74
- @channels = Hash.new(NilChannel.new(self))
75
- @listeners = { transport.socket => nil }
76
- @pending_requests = []
77
- @channel_open_handlers = {}
78
- @on_global_request = {}
79
- @properties = (options[:properties] || {}).dup
74
+ @channel_id_counter = -1
75
+ @channels = Hash.new(NilChannel.new(self))
76
+ @listeners = { transport.socket => nil }
77
+ @pending_requests = []
78
+ @channel_open_handlers = {}
79
+ @on_global_request = {}
80
+ @properties = (options[:properties] || {}).dup
80
81
 
81
- @max_pkt_size = (options.key?(:max_pkt_size) ? options[:max_pkt_size] : 0x8000)
82
- @max_win_size = (options.key?(:max_win_size) ? options[:max_win_size] : 0x20000)
82
+ @max_pkt_size = (options.key?(:max_pkt_size) ? options[:max_pkt_size] : 0x8000)
83
+ @max_win_size = (options.key?(:max_win_size) ? options[:max_win_size] : 0x20000)
83
84
 
84
- @keepalive = Keepalive.new(self)
85
+ @keepalive = Keepalive.new(self)
85
86
 
86
- @event_loop = options[:event_loop] || SingleSessionEventLoop.new
87
- @event_loop.register(self)
88
- end
87
+ @event_loop = options[:event_loop] || SingleSessionEventLoop.new
88
+ @event_loop.register(self)
89
+ end
89
90
 
90
- # Retrieves a custom property from this instance. This can be used to
91
- # store additional state in applications that must manage multiple
92
- # SSH connections.
93
- def [](key)
94
- @properties[key]
95
- end
91
+ # Retrieves a custom property from this instance. This can be used to
92
+ # store additional state in applications that must manage multiple
93
+ # SSH connections.
94
+ def [](key)
95
+ @properties[key]
96
+ end
96
97
 
97
- # Sets a custom property for this instance.
98
- def []=(key, value)
99
- @properties[key] = value
100
- end
98
+ # Sets a custom property for this instance.
99
+ def []=(key, value)
100
+ @properties[key] = value
101
+ end
101
102
 
102
- # Returns the name of the host that was given to the transport layer to
103
- # connect to.
104
- def host
105
- transport.host
106
- end
103
+ # Returns the name of the host that was given to the transport layer to
104
+ # connect to.
105
+ def host
106
+ transport.host
107
+ end
107
108
 
108
- # Returns true if the underlying transport has been closed. Note that
109
- # this can be a little misleading, since if the remote server has
110
- # closed the connection, the local end will still think it is open
111
- # until the next operation on the socket. Nevertheless, this method can
112
- # be useful if you just want to know if _you_ have closed the connection.
113
- def closed?
114
- transport.closed?
115
- end
109
+ # Returns true if the underlying transport has been closed. Note that
110
+ # this can be a little misleading, since if the remote server has
111
+ # closed the connection, the local end will still think it is open
112
+ # until the next operation on the socket. Nevertheless, this method can
113
+ # be useful if you just want to know if _you_ have closed the connection.
114
+ def closed?
115
+ transport.closed?
116
+ end
116
117
 
117
- # Closes the session gracefully, blocking until all channels have
118
- # successfully closed, and then closes the underlying transport layer
119
- # connection.
120
- def close
121
- info { "closing remaining channels (#{channels.length} open)" }
122
- channels.each { |id, channel| channel.close }
123
- begin
124
- loop(0.1) { channels.any? }
125
- rescue Net::SSH::Disconnect
126
- raise unless channels.empty?
127
- end
128
- transport.close
129
- end
118
+ # Closes the session gracefully, blocking until all channels have
119
+ # successfully closed, and then closes the underlying transport layer
120
+ # connection.
121
+ def close
122
+ info { "closing remaining channels (#{channels.length} open)" }
123
+ channels.each { |id, channel| channel.close }
124
+ begin
125
+ loop(0.1) { channels.any? }
126
+ rescue Net::SSH::Disconnect
127
+ raise unless channels.empty?
128
+ end
129
+ transport.close
130
+ end
130
131
 
131
- # Performs a "hard" shutdown of the connection. In general, this should
132
- # never be done, but it might be necessary (in a rescue clause, for instance,
133
- # when the connection needs to close but you don't know the status of the
134
- # underlying protocol's state).
135
- def shutdown!
136
- transport.shutdown!
137
- end
132
+ # Performs a "hard" shutdown of the connection. In general, this should
133
+ # never be done, but it might be necessary (in a rescue clause, for instance,
134
+ # when the connection needs to close but you don't know the status of the
135
+ # underlying protocol's state).
136
+ def shutdown!
137
+ transport.shutdown!
138
+ end
138
139
 
139
- # preserve a reference to Kernel#loop
140
- alias :loop_forever :loop
141
-
142
- # Returns +true+ if there are any channels currently active on this
143
- # session. By default, this will not include "invisible" channels
144
- # (such as those created by forwarding ports and such), but if you pass
145
- # a +true+ value for +include_invisible+, then those will be counted.
146
- #
147
- # This can be useful for determining whether the event loop should continue
148
- # to be run.
149
- #
150
- # ssh.loop { ssh.busy? }
151
- def busy?(include_invisible=false)
152
- if include_invisible
153
- channels.any?
154
- else
155
- channels.any? { |id, ch| !ch[:invisible] }
156
- end
157
- end
140
+ # preserve a reference to Kernel#loop
141
+ alias :loop_forever :loop
142
+
143
+ # Returns +true+ if there are any channels currently active on this
144
+ # session. By default, this will not include "invisible" channels
145
+ # (such as those created by forwarding ports and such), but if you pass
146
+ # a +true+ value for +include_invisible+, then those will be counted.
147
+ #
148
+ # This can be useful for determining whether the event loop should continue
149
+ # to be run.
150
+ #
151
+ # ssh.loop { ssh.busy? }
152
+ def busy?(include_invisible = false)
153
+ if include_invisible
154
+ channels.any?
155
+ else
156
+ channels.any? { |id, ch| !ch[:invisible] }
157
+ end
158
+ end
158
159
 
159
- # The main event loop. Calls #process until #process returns false. If a
160
- # block is given, it is passed to #process, otherwise a default proc is
161
- # used that just returns true if there are any channels active (see #busy?).
162
- # The # +wait+ parameter is also passed through to #process (where it is
163
- # interpreted as the maximum number of seconds to wait for IO.select to return).
164
- #
165
- # # loop for as long as there are any channels active
166
- # ssh.loop
167
- #
168
- # # loop for as long as there are any channels active, but make sure
169
- # # the event loop runs at least once per 0.1 second
170
- # ssh.loop(0.1)
171
- #
172
- # # loop until ctrl-C is pressed
173
- # int_pressed = false
174
- # trap("INT") { int_pressed = true }
175
- # ssh.loop(0.1) { not int_pressed }
176
- def loop(wait=nil, &block)
177
- running = block || Proc.new { busy? }
178
- loop_forever { break unless process(wait, &running) }
179
- begin
180
- process(0)
181
- rescue IOError => e
182
- if e.message =~ /closed/
183
- debug { "stream was closed after loop => shallowing exception so it will be re-raised in next loop" }
184
- else
160
+ # The main event loop. Calls #process until #process returns false. If a
161
+ # block is given, it is passed to #process, otherwise a default proc is
162
+ # used that just returns true if there are any channels active (see #busy?).
163
+ # The # +wait+ parameter is also passed through to #process (where it is
164
+ # interpreted as the maximum number of seconds to wait for IO.select to return).
165
+ #
166
+ # # loop for as long as there are any channels active
167
+ # ssh.loop
168
+ #
169
+ # # loop for as long as there are any channels active, but make sure
170
+ # # the event loop runs at least once per 0.1 second
171
+ # ssh.loop(0.1)
172
+ #
173
+ # # loop until ctrl-C is pressed
174
+ # int_pressed = false
175
+ # trap("INT") { int_pressed = true }
176
+ # ssh.loop(0.1) { not int_pressed }
177
+ def loop(wait = nil, &block)
178
+ running = block || Proc.new { busy? }
179
+ loop_forever { break unless process(wait, &running) }
180
+ begin
181
+ process(0)
182
+ rescue IOError => e
183
+ if e.message =~ /closed/
184
+ debug { "stream was closed after loop => shallowing exception so it will be re-raised in next loop" }
185
+ else
186
+ raise
187
+ end
188
+ end
189
+ end
190
+
191
+ # The core of the event loop. It processes a single iteration of the event
192
+ # loop. If a block is given, it should return false when the processing
193
+ # should abort, which causes #process to return false. Otherwise,
194
+ # #process returns true. The session itself is yielded to the block as its
195
+ # only argument.
196
+ #
197
+ # If +wait+ is nil (the default), this method will block until any of the
198
+ # monitored IO objects are ready to be read from or written to. If you want
199
+ # it to not block, you can pass 0, or you can pass any other numeric value
200
+ # to indicate that it should block for no more than that many seconds.
201
+ # Passing 0 is a good way to poll the connection, but if you do it too
202
+ # frequently it can make your CPU quite busy!
203
+ #
204
+ # This will also cause all active channels to be processed once each (see
205
+ # Net::SSH::Connection::Channel#on_process).
206
+ #
207
+ # TODO revise example
208
+ #
209
+ # # process multiple Net::SSH connections in parallel
210
+ # connections = [
211
+ # Net::SSH.start("host1", ...),
212
+ # Net::SSH.start("host2", ...)
213
+ # ]
214
+ #
215
+ # connections.each do |ssh|
216
+ # ssh.exec "grep something /in/some/files"
217
+ # end
218
+ #
219
+ # condition = Proc.new { |s| s.busy? }
220
+ #
221
+ # loop do
222
+ # connections.delete_if { |ssh| !ssh.process(0.1, &condition) }
223
+ # break if connections.empty?
224
+ # end
225
+ def process(wait = nil, &block)
226
+ @event_loop.process(wait, &block)
227
+ rescue StandardError
228
+ force_channel_cleanup_on_close if closed?
185
229
  raise
186
230
  end
187
- end
188
- end
189
231
 
190
- # The core of the event loop. It processes a single iteration of the event
191
- # loop. If a block is given, it should return false when the processing
192
- # should abort, which causes #process to return false. Otherwise,
193
- # #process returns true. The session itself is yielded to the block as its
194
- # only argument.
195
- #
196
- # If +wait+ is nil (the default), this method will block until any of the
197
- # monitored IO objects are ready to be read from or written to. If you want
198
- # it to not block, you can pass 0, or you can pass any other numeric value
199
- # to indicate that it should block for no more than that many seconds.
200
- # Passing 0 is a good way to poll the connection, but if you do it too
201
- # frequently it can make your CPU quite busy!
202
- #
203
- # This will also cause all active channels to be processed once each (see
204
- # Net::SSH::Connection::Channel#on_process).
205
- #
206
- # TODO revise example
207
- #
208
- # # process multiple Net::SSH connections in parallel
209
- # connections = [
210
- # Net::SSH.start("host1", ...),
211
- # Net::SSH.start("host2", ...)
212
- # ]
213
- #
214
- # connections.each do |ssh|
215
- # ssh.exec "grep something /in/some/files"
216
- # end
217
- #
218
- # condition = Proc.new { |s| s.busy? }
219
- #
220
- # loop do
221
- # connections.delete_if { |ssh| !ssh.process(0.1, &condition) }
222
- # break if connections.empty?
223
- # end
224
- def process(wait=nil, &block)
225
- @event_loop.process(wait, &block)
226
- rescue
227
- force_channel_cleanup_on_close if closed?
228
- raise
229
- end
232
+ # This is called internally as part of #process. It dispatches any
233
+ # available incoming packets, and then runs Net::SSH::Connection::Channel#process
234
+ # for any active channels. If a block is given, it is invoked at the
235
+ # start of the method and again at the end, and if the block ever returns
236
+ # false, this method returns false. Otherwise, it returns true.
237
+ def preprocess(&block)
238
+ return false if block_given? && !yield(self)
230
239
 
231
- # This is called internally as part of #process. It dispatches any
232
- # available incoming packets, and then runs Net::SSH::Connection::Channel#process
233
- # for any active channels. If a block is given, it is invoked at the
234
- # start of the method and again at the end, and if the block ever returns
235
- # false, this method returns false. Otherwise, it returns true.
236
- def preprocess(&block)
237
- return false if block_given? && !yield(self)
238
- ev_preprocess(&block)
239
- return false if block_given? && !yield(self)
240
- return true
241
- end
240
+ ev_preprocess(&block)
241
+ return false if block_given? && !yield(self)
242
242
 
243
- # Called by event loop to process available data before going to
244
- # event multiplexing
245
- def ev_preprocess(&block)
246
- dispatch_incoming_packets(raise_disconnect_errors: false)
247
- each_channel { |id, channel| channel.process unless channel.local_closed? }
248
- end
249
-
250
- # Returns the file descriptors the event loop should wait for read/write events,
251
- # we also return the max wait
252
- def ev_do_calculate_rw_wait(wait)
253
- r = listeners.keys
254
- w = r.select { |w2| w2.respond_to?(:pending_write?) && w2.pending_write? }
255
- [r,w,io_select_wait(wait)]
256
- end
243
+ return true
244
+ end
257
245
 
258
- # This is called internally as part of #process.
259
- def postprocess(readers, writers)
260
- ev_do_handle_events(readers, writers)
261
- end
246
+ # Called by event loop to process available data before going to
247
+ # event multiplexing
248
+ def ev_preprocess(&block)
249
+ dispatch_incoming_packets(raise_disconnect_errors: false)
250
+ each_channel { |id, channel| channel.process unless channel.local_closed? }
251
+ end
262
252
 
263
- # It loops over the given arrays of reader IO's and writer IO's,
264
- # processing them as needed, and
265
- # then calls Net::SSH::Transport::Session#rekey_as_needed to allow the
266
- # transport layer to rekey. Then returns true.
267
- def ev_do_handle_events(readers, writers)
268
- Array(readers).each do |reader|
269
- if listeners[reader]
270
- listeners[reader].call(reader)
271
- else
272
- if reader.fill.zero?
273
- reader.close
274
- stop_listening_to(reader)
275
- end
253
+ # Returns the file descriptors the event loop should wait for read/write events,
254
+ # we also return the max wait
255
+ def ev_do_calculate_rw_wait(wait)
256
+ r = listeners.keys
257
+ w = r.select { |w2| w2.respond_to?(:pending_write?) && w2.pending_write? }
258
+ [r, w, io_select_wait(wait)]
276
259
  end
277
- end
278
260
 
279
- Array(writers).each do |writer|
280
- writer.send_pending
281
- end
282
- end
261
+ # This is called internally as part of #process.
262
+ def postprocess(readers, writers)
263
+ ev_do_handle_events(readers, writers)
264
+ end
283
265
 
284
- # calls Net::SSH::Transport::Session#rekey_as_needed to allow the
285
- # transport layer to rekey
286
- def ev_do_postprocess(was_events)
287
- @keepalive.send_as_needed(was_events)
288
- transport.rekey_as_needed
289
- true
290
- end
266
+ # It loops over the given arrays of reader IO's and writer IO's,
267
+ # processing them as needed, and
268
+ # then calls Net::SSH::Transport::Session#rekey_as_needed to allow the
269
+ # transport layer to rekey. Then returns true.
270
+ def ev_do_handle_events(readers, writers)
271
+ Array(readers).each do |reader|
272
+ if listeners[reader]
273
+ listeners[reader].call(reader)
274
+ else
275
+ if reader.fill.zero?
276
+ reader.close
277
+ stop_listening_to(reader)
278
+ end
279
+ end
280
+ end
291
281
 
292
- # Send a global request of the given type. The +extra+ parameters must
293
- # be even in number, and conform to the same format as described for
294
- # Net::SSH::Buffer.from. If a callback is not specified, the request will
295
- # not require a response from the server, otherwise the server is required
296
- # to respond and indicate whether the request was successful or not. This
297
- # success or failure is indicated by the callback being invoked, with the
298
- # first parameter being true or false (success, or failure), and the second
299
- # being the packet itself.
300
- #
301
- # Generally, Net::SSH will manage global requests that need to be sent
302
- # (e.g. port forward requests and such are handled in the Net::SSH::Service::Forward
303
- # class, for instance). However, there may be times when you need to
304
- # send a global request that isn't explicitly handled by Net::SSH, and so
305
- # this method is available to you.
306
- #
307
- # ssh.send_global_request("keep-alive@openssh.com")
308
- def send_global_request(type, *extra, &callback)
309
- info { "sending global request #{type}" }
310
- msg = Buffer.from(:byte, GLOBAL_REQUEST, :string, type.to_s, :bool, !callback.nil?, *extra)
311
- send_message(msg)
312
- pending_requests << callback if callback
313
- self
314
- end
282
+ Array(writers).each do |writer|
283
+ writer.send_pending
284
+ end
285
+ end
315
286
 
316
- # Requests that a new channel be opened. By default, the channel will be
317
- # of type "session", but if you know what you're doing you can select any
318
- # of the channel types supported by the SSH protocol. The +extra+ parameters
319
- # must be even in number and conform to the same format as described for
320
- # Net::SSH::Buffer.from. If a callback is given, it will be invoked when
321
- # the server confirms that the channel opened successfully. The sole parameter
322
- # for the callback is the channel object itself.
323
- #
324
- # In general, you'll use #open_channel without any arguments; the only
325
- # time you'd want to set the channel type or pass additional initialization
326
- # data is if you were implementing an SSH extension.
327
- #
328
- # channel = ssh.open_channel do |ch|
329
- # ch.exec "grep something /some/files" do |ch, success|
330
- # ...
331
- # end
332
- # end
333
- #
334
- # channel.wait
335
- def open_channel(type="session", *extra, &on_confirm)
336
- local_id = get_next_channel_id
337
-
338
- channel = Channel.new(self, type, local_id, @max_pkt_size, @max_win_size, &on_confirm)
339
- msg = Buffer.from(:byte, CHANNEL_OPEN, :string, type, :long, local_id,
340
- :long, channel.local_maximum_window_size,
341
- :long, channel.local_maximum_packet_size, *extra)
342
- send_message(msg)
343
-
344
- channels[local_id] = channel
345
- end
287
+ # calls Net::SSH::Transport::Session#rekey_as_needed to allow the
288
+ # transport layer to rekey
289
+ def ev_do_postprocess(was_events)
290
+ @keepalive.send_as_needed(was_events)
291
+ transport.rekey_as_needed
292
+ true
293
+ end
346
294
 
347
- class StringWithExitstatus < String
348
- def initialize(str, exitstatus)
349
- super(str)
350
- @exitstatus = exitstatus
351
- end
295
+ # Send a global request of the given type. The +extra+ parameters must
296
+ # be even in number, and conform to the same format as described for
297
+ # Net::SSH::Buffer.from. If a callback is not specified, the request will
298
+ # not require a response from the server, otherwise the server is required
299
+ # to respond and indicate whether the request was successful or not. This
300
+ # success or failure is indicated by the callback being invoked, with the
301
+ # first parameter being true or false (success, or failure), and the second
302
+ # being the packet itself.
303
+ #
304
+ # Generally, Net::SSH will manage global requests that need to be sent
305
+ # (e.g. port forward requests and such are handled in the Net::SSH::Service::Forward
306
+ # class, for instance). However, there may be times when you need to
307
+ # send a global request that isn't explicitly handled by Net::SSH, and so
308
+ # this method is available to you.
309
+ #
310
+ # ssh.send_global_request("keep-alive@openssh.com")
311
+ def send_global_request(type, *extra, &callback)
312
+ info { "sending global request #{type}" }
313
+ msg = Buffer.from(:byte, GLOBAL_REQUEST, :string, type.to_s, :bool, !callback.nil?, *extra)
314
+ send_message(msg)
315
+ pending_requests << callback if callback
316
+ self
317
+ end
352
318
 
353
- attr_reader :exitstatus
354
- end
319
+ # Requests that a new channel be opened. By default, the channel will be
320
+ # of type "session", but if you know what you're doing you can select any
321
+ # of the channel types supported by the SSH protocol. The +extra+ parameters
322
+ # must be even in number and conform to the same format as described for
323
+ # Net::SSH::Buffer.from. If a callback is given, it will be invoked when
324
+ # the server confirms that the channel opened successfully. The sole parameter
325
+ # for the callback is the channel object itself.
326
+ #
327
+ # In general, you'll use #open_channel without any arguments; the only
328
+ # time you'd want to set the channel type or pass additional initialization
329
+ # data is if you were implementing an SSH extension.
330
+ #
331
+ # channel = ssh.open_channel do |ch|
332
+ # ch.exec "grep something /some/files" do |ch, success|
333
+ # ...
334
+ # end
335
+ # end
336
+ #
337
+ # channel.wait
338
+ def open_channel(type = "session", *extra, &on_confirm)
339
+ local_id = get_next_channel_id
340
+
341
+ channel = Channel.new(self, type, local_id, @max_pkt_size, @max_win_size, &on_confirm)
342
+ msg = Buffer.from(:byte, CHANNEL_OPEN, :string, type, :long, local_id,
343
+ :long, channel.local_maximum_window_size,
344
+ :long, channel.local_maximum_packet_size, *extra)
345
+ send_message(msg)
355
346
 
356
- # A convenience method for executing a command and interacting with it. If
357
- # no block is given, all output is printed via $stdout and $stderr. Otherwise,
358
- # the block is called for each data and extended data packet, with three
359
- # arguments: the channel object, a symbol indicating the data type
360
- # (:stdout or :stderr), and the data (as a string).
361
- #
362
- # Note that this method returns immediately, and requires an event loop
363
- # (see Session#loop) in order for the command to actually execute.
364
- #
365
- # This is effectively identical to calling #open_channel, and then
366
- # Net::SSH::Connection::Channel#exec, and then setting up the channel
367
- # callbacks. However, for most uses, this will be sufficient.
368
- #
369
- # ssh.exec "grep something /some/files" do |ch, stream, data|
370
- # if stream == :stderr
371
- # puts "ERROR: #{data}"
372
- # else
373
- # puts data
374
- # end
375
- # end
376
- def exec(command, status: nil, &block)
377
- open_channel do |channel|
378
- channel.exec(command) do |ch, success|
379
- raise "could not execute command: #{command.inspect}" unless success
380
-
381
- if status
382
- channel.on_request("exit-status") do |ch2,data|
383
- status[:exit_code] = data.read_long
384
- end
347
+ channels[local_id] = channel
348
+ end
385
349
 
386
- channel.on_request("exit-signal") do |ch2, data|
387
- status[:exit_signal] = data.read_long
388
- end
350
+ class StringWithExitstatus < String
351
+ def initialize(str, exitstatus)
352
+ super(str)
353
+ @exitstatus = exitstatus
389
354
  end
390
355
 
391
- channel.on_data do |ch2, data|
392
- if block
393
- block.call(ch2, :stdout, data)
394
- else
395
- $stdout.print(data)
396
- end
397
- end
356
+ attr_reader :exitstatus
357
+ end
398
358
 
399
- channel.on_extended_data do |ch2, type, data|
400
- if block
401
- block.call(ch2, :stderr, data)
402
- else
403
- $stderr.print(data)
359
+ # A convenience method for executing a command and interacting with it. If
360
+ # no block is given, all output is printed via $stdout and $stderr. Otherwise,
361
+ # the block is called for each data and extended data packet, with three
362
+ # arguments: the channel object, a symbol indicating the data type
363
+ # (:stdout or :stderr), and the data (as a string).
364
+ #
365
+ # Note that this method returns immediately, and requires an event loop
366
+ # (see Session#loop) in order for the command to actually execute.
367
+ #
368
+ # This is effectively identical to calling #open_channel, and then
369
+ # Net::SSH::Connection::Channel#exec, and then setting up the channel
370
+ # callbacks. However, for most uses, this will be sufficient.
371
+ #
372
+ # ssh.exec "grep something /some/files" do |ch, stream, data|
373
+ # if stream == :stderr
374
+ # puts "ERROR: #{data}"
375
+ # else
376
+ # puts data
377
+ # end
378
+ # end
379
+ def exec(command, status: nil, &block)
380
+ open_channel do |channel|
381
+ channel.exec(command) do |ch, success|
382
+ raise "could not execute command: #{command.inspect}" unless success
383
+
384
+ if status
385
+ channel.on_request("exit-status") do |ch2, data|
386
+ status[:exit_code] = data.read_long
387
+ end
388
+
389
+ channel.on_request("exit-signal") do |ch2, data|
390
+ status[:exit_signal] = data.read_long
391
+ end
392
+ end
393
+
394
+ channel.on_data do |ch2, data|
395
+ if block
396
+ block.call(ch2, :stdout, data)
397
+ else
398
+ $stdout.print(data)
399
+ end
400
+ end
401
+
402
+ channel.on_extended_data do |ch2, type, data|
403
+ if block
404
+ block.call(ch2, :stderr, data)
405
+ else
406
+ $stderr.print(data)
407
+ end
408
+ end
404
409
  end
405
410
  end
406
411
  end
407
- end
408
- end
409
412
 
410
- # Same as #exec, except this will block until the command finishes. Also,
411
- # if no block is given, this will return all output (stdout and stderr)
412
- # as a single string.
413
- #
414
- # matches = ssh.exec!("grep something /some/files")
415
- #
416
- # the returned string has an exitstatus method to query it's exit satus
417
- def exec!(command, status: nil, &block)
418
- block_or_concat = block || Proc.new do |ch, type, data|
419
- ch[:result] ||= ""
420
- ch[:result] << data
421
- end
413
+ # Same as #exec, except this will block until the command finishes. Also,
414
+ # if no block is given, this will return all output (stdout and stderr)
415
+ # as a single string.
416
+ #
417
+ # matches = ssh.exec!("grep something /some/files")
418
+ #
419
+ # the returned string has an exitstatus method to query it's exit satus
420
+ def exec!(command, status: nil, &block)
421
+ block_or_concat = block || Proc.new do |ch, type, data|
422
+ ch[:result] ||= String.new
423
+ ch[:result] << data
424
+ end
422
425
 
423
- status ||= {}
424
- channel = exec(command, status: status, &block_or_concat)
425
- channel.wait
426
+ status ||= {}
427
+ channel = exec(command, status: status, &block_or_concat)
428
+ channel.wait
426
429
 
427
- channel[:result] ||= "" unless block
428
- channel[:result] &&= channel[:result].force_encoding("UTF-8") unless block
430
+ channel[:result] ||= String.new unless block
431
+ channel[:result] &&= channel[:result].force_encoding("UTF-8") unless block
429
432
 
430
- StringWithExitstatus.new(channel[:result], status[:exit_code]) if channel[:result]
431
- end
433
+ StringWithExitstatus.new(channel[:result], status[:exit_code]) if channel[:result]
434
+ end
432
435
 
433
- # Enqueues a message to be sent to the server as soon as the socket is
434
- # available for writing. Most programs will never need to call this, but
435
- # if you are implementing an extension to the SSH protocol, or if you
436
- # need to send a packet that Net::SSH does not directly support, you can
437
- # use this to send it.
438
- #
439
- # ssh.send_message(Buffer.from(:byte, REQUEST_SUCCESS).to_s)
440
- def send_message(message)
441
- transport.enqueue_message(message)
442
- end
436
+ # Enqueues a message to be sent to the server as soon as the socket is
437
+ # available for writing. Most programs will never need to call this, but
438
+ # if you are implementing an extension to the SSH protocol, or if you
439
+ # need to send a packet that Net::SSH does not directly support, you can
440
+ # use this to send it.
441
+ #
442
+ # ssh.send_message(Buffer.from(:byte, REQUEST_SUCCESS).to_s)
443
+ def send_message(message)
444
+ transport.enqueue_message(message)
445
+ end
443
446
 
444
- # Adds an IO object for the event loop to listen to. If a callback
445
- # is given, it will be invoked when the io is ready to be read, otherwise,
446
- # the io will merely have its #fill method invoked.
447
- #
448
- # Any +io+ value passed to this method _must_ have mixed into it the
449
- # Net::SSH::BufferedIo functionality, typically by calling #extend on the
450
- # object.
451
- #
452
- # The following example executes a process on the remote server, opens
453
- # a socket to somewhere, and then pipes data from that socket to the
454
- # remote process' stdin stream:
455
- #
456
- # channel = ssh.open_channel do |ch|
457
- # ch.exec "/some/process/that/wants/input" do |ch, success|
458
- # abort "can't execute!" unless success
459
- #
460
- # io = TCPSocket.new(somewhere, port)
461
- # io.extend(Net::SSH::BufferedIo)
462
- # ssh.listen_to(io)
463
- #
464
- # ch.on_process do
465
- # if io.available > 0
466
- # ch.send_data(io.read_available)
467
- # end
468
- # end
469
- #
470
- # ch.on_close do
471
- # ssh.stop_listening_to(io)
472
- # io.close
473
- # end
474
- # end
475
- # end
476
- #
477
- # channel.wait
478
- def listen_to(io, &callback)
479
- listeners[io] = callback
480
- end
447
+ # Adds an IO object for the event loop to listen to. If a callback
448
+ # is given, it will be invoked when the io is ready to be read, otherwise,
449
+ # the io will merely have its #fill method invoked.
450
+ #
451
+ # Any +io+ value passed to this method _must_ have mixed into it the
452
+ # Net::SSH::BufferedIo functionality, typically by calling #extend on the
453
+ # object.
454
+ #
455
+ # The following example executes a process on the remote server, opens
456
+ # a socket to somewhere, and then pipes data from that socket to the
457
+ # remote process' stdin stream:
458
+ #
459
+ # channel = ssh.open_channel do |ch|
460
+ # ch.exec "/some/process/that/wants/input" do |ch, success|
461
+ # abort "can't execute!" unless success
462
+ #
463
+ # io = TCPSocket.new(somewhere, port)
464
+ # io.extend(Net::SSH::BufferedIo)
465
+ # ssh.listen_to(io)
466
+ #
467
+ # ch.on_process do
468
+ # if io.available > 0
469
+ # ch.send_data(io.read_available)
470
+ # end
471
+ # end
472
+ #
473
+ # ch.on_close do
474
+ # ssh.stop_listening_to(io)
475
+ # io.close
476
+ # end
477
+ # end
478
+ # end
479
+ #
480
+ # channel.wait
481
+ def listen_to(io, &callback)
482
+ listeners[io] = callback
483
+ end
481
484
 
482
- # Removes the given io object from the listeners collection, so that the
483
- # event loop will no longer monitor it.
484
- def stop_listening_to(io)
485
- listeners.delete(io)
486
- end
485
+ # Removes the given io object from the listeners collection, so that the
486
+ # event loop will no longer monitor it.
487
+ def stop_listening_to(io)
488
+ listeners.delete(io)
489
+ end
487
490
 
488
- # Returns a reference to the Net::SSH::Service::Forward service, which can
489
- # be used for forwarding ports over SSH.
490
- def forward
491
- @forward ||= Service::Forward.new(self)
492
- end
491
+ # Returns a reference to the Net::SSH::Service::Forward service, which can
492
+ # be used for forwarding ports over SSH.
493
+ def forward
494
+ @forward ||= Service::Forward.new(self)
495
+ end
493
496
 
494
- # Registers a handler to be invoked when the server wants to open a
495
- # channel on the client. The callback receives the connection object,
496
- # the new channel object, and the packet itself as arguments, and should
497
- # raise ChannelOpenFailed if it is unable to open the channel for some
498
- # reason. Otherwise, the channel will be opened and a confirmation message
499
- # sent to the server.
500
- #
501
- # This is used by the Net::SSH::Service::Forward service to open a channel
502
- # when a remote forwarded port receives a connection. However, you are
503
- # welcome to register handlers for other channel types, as needed.
504
- def on_open_channel(type, &block)
505
- channel_open_handlers[type] = block
506
- end
497
+ # Registers a handler to be invoked when the server wants to open a
498
+ # channel on the client. The callback receives the connection object,
499
+ # the new channel object, and the packet itself as arguments, and should
500
+ # raise ChannelOpenFailed if it is unable to open the channel for some
501
+ # reason. Otherwise, the channel will be opened and a confirmation message
502
+ # sent to the server.
503
+ #
504
+ # This is used by the Net::SSH::Service::Forward service to open a channel
505
+ # when a remote forwarded port receives a connection. However, you are
506
+ # welcome to register handlers for other channel types, as needed.
507
+ def on_open_channel(type, &block)
508
+ channel_open_handlers[type] = block
509
+ end
507
510
 
508
- # Registers a handler to be invoked when the server sends a global request
509
- # of the given type. The callback receives the request data as the first
510
- # parameter, and true/false as the second (indicating whether a response
511
- # is required). If the callback sends the response, it should return
512
- # :sent. Otherwise, if it returns true, REQUEST_SUCCESS will be sent, and
513
- # if it returns false, REQUEST_FAILURE will be sent.
514
- def on_global_request(type, &block)
515
- old, @on_global_request[type] = @on_global_request[type], block
516
- old
517
- end
511
+ # Registers a handler to be invoked when the server sends a global request
512
+ # of the given type. The callback receives the request data as the first
513
+ # parameter, and true/false as the second (indicating whether a response
514
+ # is required). If the callback sends the response, it should return
515
+ # :sent. Otherwise, if it returns true, REQUEST_SUCCESS will be sent, and
516
+ # if it returns false, REQUEST_FAILURE will be sent.
517
+ def on_global_request(type, &block)
518
+ old, @on_global_request[type] = @on_global_request[type], block
519
+ old
520
+ end
518
521
 
519
- def cleanup_channel(channel)
520
- if channel.local_closed? and channel.remote_closed?
521
- info { "#{host} delete channel #{channel.local_id} which closed locally and remotely" }
522
- channels.delete(channel.local_id)
523
- end
524
- end
522
+ def cleanup_channel(channel)
523
+ if channel.local_closed? and channel.remote_closed?
524
+ info { "#{host} delete channel #{channel.local_id} which closed locally and remotely" }
525
+ channels.delete(channel.local_id)
526
+ end
527
+ end
525
528
 
526
- # If the #preprocess and #postprocess callbacks for this session need to run
527
- # periodically, this method returns the maximum number of seconds which may
528
- # pass between callbacks.
529
- def max_select_wait_time
530
- @keepalive.interval if @keepalive.enabled?
531
- end
529
+ # If the #preprocess and #postprocess callbacks for this session need to run
530
+ # periodically, this method returns the maximum number of seconds which may
531
+ # pass between callbacks.
532
+ def max_select_wait_time
533
+ @keepalive.interval if @keepalive.enabled?
534
+ end
532
535
 
536
+ private
533
537
 
534
- private
538
+ # iterate channels with the posibility of callbacks opening new channels during the iteration
539
+ def each_channel(&block)
540
+ channels.dup.each(&block)
541
+ end
535
542
 
536
- # iterate channels with the posibility of callbacks opening new channels during the iteration
537
- def each_channel(&block)
538
- channels.dup.each(&block)
539
- end
543
+ # Read all pending packets from the connection and dispatch them as
544
+ # appropriate. Returns as soon as there are no more pending packets.
545
+ def dispatch_incoming_packets(raise_disconnect_errors: true)
546
+ while packet = transport.poll_message
547
+ raise Net::SSH::Exception, "unexpected response #{packet.type} (#{packet.inspect})" unless MAP.key?(packet.type)
540
548
 
541
- # Read all pending packets from the connection and dispatch them as
542
- # appropriate. Returns as soon as there are no more pending packets.
543
- def dispatch_incoming_packets(raise_disconnect_errors: true)
544
- while packet = transport.poll_message
545
- unless MAP.key?(packet.type)
546
- raise Net::SSH::Exception, "unexpected response #{packet.type} (#{packet.inspect})"
549
+ send(MAP[packet.type], packet)
547
550
  end
548
-
549
- send(MAP[packet.type], packet)
551
+ rescue StandardError
552
+ force_channel_cleanup_on_close if closed?
553
+ raise if raise_disconnect_errors || !$!.is_a?(Net::SSH::Disconnect)
550
554
  end
551
- rescue
552
- force_channel_cleanup_on_close if closed?
553
- raise if raise_disconnect_errors || !$!.is_a?(Net::SSH::Disconnect)
554
- end
555
555
 
556
- # Returns the next available channel id to be assigned, and increments
557
- # the counter.
558
- def get_next_channel_id
559
- @channel_id_counter += 1
560
- end
556
+ # Returns the next available channel id to be assigned, and increments
557
+ # the counter.
558
+ def get_next_channel_id
559
+ @channel_id_counter += 1
560
+ end
561
561
 
562
- def force_channel_cleanup_on_close
563
- channels.each do |id, channel|
564
- channel_closed(channel)
562
+ def force_channel_cleanup_on_close
563
+ channels.each do |id, channel|
564
+ channel_closed(channel)
565
+ end
565
566
  end
566
- end
567
567
 
568
- def channel_closed(channel)
569
- channel.remote_closed!
570
- channel.close
568
+ def channel_closed(channel)
569
+ channel.remote_closed!
570
+ channel.close
571
571
 
572
- cleanup_channel(channel)
573
- channel.do_close
574
- end
572
+ cleanup_channel(channel)
573
+ channel.do_close
574
+ end
575
575
 
576
- # Invoked when a global request is received. The registered global
577
- # request callback will be invoked, if one exists, and the necessary
578
- # reply returned.
579
- def global_request(packet)
580
- info { "global request received: #{packet[:request_type]} #{packet[:want_reply]}" }
581
- callback = @on_global_request[packet[:request_type]]
582
- result = callback ? callback.call(packet[:request_data], packet[:want_reply]) : false
576
+ # Invoked when a global request is received. The registered global
577
+ # request callback will be invoked, if one exists, and the necessary
578
+ # reply returned.
579
+ def global_request(packet)
580
+ info { "global request received: #{packet[:request_type]} #{packet[:want_reply]}" }
581
+ callback = @on_global_request[packet[:request_type]]
582
+ result = callback ? callback.call(packet[:request_data], packet[:want_reply]) : false
583
583
 
584
- if result != :sent && result != true && result != false
585
- raise "expected global request handler for `#{packet[:request_type]}' to return true, false, or :sent, but got #{result.inspect}"
586
- end
584
+ if result != :sent && result != true && result != false
585
+ raise "expected global request handler for `#{packet[:request_type]}' to return true, false, or :sent, but got #{result.inspect}"
586
+ end
587
587
 
588
- if packet[:want_reply] && result != :sent
589
- msg = Buffer.from(:byte, result ? REQUEST_SUCCESS : REQUEST_FAILURE)
590
- send_message(msg)
588
+ if packet[:want_reply] && result != :sent
589
+ msg = Buffer.from(:byte, result ? REQUEST_SUCCESS : REQUEST_FAILURE)
590
+ send_message(msg)
591
+ end
591
592
  end
592
- end
593
593
 
594
- # Invokes the next pending request callback with +true+.
595
- def request_success(packet)
596
- info { "global request success" }
597
- callback = pending_requests.shift
598
- callback.call(true, packet) if callback
599
- end
594
+ # Invokes the next pending request callback with +true+.
595
+ def request_success(packet)
596
+ info { "global request success" }
597
+ callback = pending_requests.shift
598
+ callback.call(true, packet) if callback
599
+ end
600
600
 
601
- # Invokes the next pending request callback with +false+.
602
- def request_failure(packet)
603
- info { "global request failure" }
604
- callback = pending_requests.shift
605
- callback.call(false, packet) if callback
606
- end
601
+ # Invokes the next pending request callback with +false+.
602
+ def request_failure(packet)
603
+ info { "global request failure" }
604
+ callback = pending_requests.shift
605
+ callback.call(false, packet) if callback
606
+ end
607
607
 
608
- # Called when the server wants to open a channel. If no registered
609
- # channel handler exists for the given channel type, CHANNEL_OPEN_FAILURE
610
- # is returned, otherwise the callback is invoked and everything proceeds
611
- # accordingly.
612
- def channel_open(packet)
613
- info { "channel open #{packet[:channel_type]}" }
608
+ # Called when the server wants to open a channel. If no registered
609
+ # channel handler exists for the given channel type, CHANNEL_OPEN_FAILURE
610
+ # is returned, otherwise the callback is invoked and everything proceeds
611
+ # accordingly.
612
+ def channel_open(packet)
613
+ info { "channel open #{packet[:channel_type]}" }
614
614
 
615
- local_id = get_next_channel_id
615
+ local_id = get_next_channel_id
616
616
 
617
- channel = Channel.new(self, packet[:channel_type], local_id, @max_pkt_size, @max_win_size)
618
- channel.do_open_confirmation(packet[:remote_id], packet[:window_size], packet[:packet_size])
617
+ channel = Channel.new(self, packet[:channel_type], local_id, @max_pkt_size, @max_win_size)
618
+ channel.do_open_confirmation(packet[:remote_id], packet[:window_size], packet[:packet_size])
619
619
 
620
- callback = channel_open_handlers[packet[:channel_type]]
620
+ callback = channel_open_handlers[packet[:channel_type]]
621
621
 
622
- if callback
623
- begin
624
- callback[self, channel, packet]
625
- rescue ChannelOpenFailed => err
626
- failure = [err.code, err.reason]
622
+ if callback
623
+ begin
624
+ callback[self, channel, packet]
625
+ rescue ChannelOpenFailed => err
626
+ failure = [err.code, err.reason]
627
+ else
628
+ channels[local_id] = channel
629
+ msg = Buffer.from(:byte, CHANNEL_OPEN_CONFIRMATION, :long, channel.remote_id, :long,
630
+ channel.local_id, :long, channel.local_maximum_window_size, :long,
631
+ channel.local_maximum_packet_size)
632
+ end
627
633
  else
628
- channels[local_id] = channel
629
- msg = Buffer.from(:byte, CHANNEL_OPEN_CONFIRMATION, :long, channel.remote_id, :long, channel.local_id, :long, channel.local_maximum_window_size, :long, channel.local_maximum_packet_size)
634
+ failure = [3, "unknown channel type #{channel.type}"]
630
635
  end
631
- else
632
- failure = [3, "unknown channel type #{channel.type}"]
633
- end
634
636
 
635
- if failure
636
- error { failure.inspect }
637
- msg = Buffer.from(:byte, CHANNEL_OPEN_FAILURE, :long, channel.remote_id, :long, failure[0], :string, failure[1], :string, "")
637
+ if failure
638
+ error { failure.inspect }
639
+ msg = Buffer.from(:byte, CHANNEL_OPEN_FAILURE, :long, channel.remote_id, :long, failure[0], :string, failure[1], :string, "")
640
+ end
641
+
642
+ send_message(msg)
638
643
  end
639
644
 
640
- send_message(msg)
641
- end
645
+ def channel_open_confirmation(packet)
646
+ info { "channel_open_confirmation: #{packet[:local_id]} #{packet[:remote_id]} #{packet[:window_size]} #{packet[:packet_size]}" }
647
+ channel = channels[packet[:local_id]]
648
+ channel.do_open_confirmation(packet[:remote_id], packet[:window_size], packet[:packet_size])
649
+ end
642
650
 
643
- def channel_open_confirmation(packet)
644
- info { "channel_open_confirmation: #{packet[:local_id]} #{packet[:remote_id]} #{packet[:window_size]} #{packet[:packet_size]}" }
645
- channel = channels[packet[:local_id]]
646
- channel.do_open_confirmation(packet[:remote_id], packet[:window_size], packet[:packet_size])
647
- end
651
+ def channel_open_failure(packet)
652
+ error { "channel_open_failed: #{packet[:local_id]} #{packet[:reason_code]} #{packet[:description]}" }
653
+ channel = channels.delete(packet[:local_id])
654
+ channel.do_open_failed(packet[:reason_code], packet[:description])
655
+ end
648
656
 
649
- def channel_open_failure(packet)
650
- error { "channel_open_failed: #{packet[:local_id]} #{packet[:reason_code]} #{packet[:description]}" }
651
- channel = channels.delete(packet[:local_id])
652
- channel.do_open_failed(packet[:reason_code], packet[:description])
653
- end
657
+ def channel_window_adjust(packet)
658
+ info { "channel_window_adjust: #{packet[:local_id]} +#{packet[:extra_bytes]}" }
659
+ channels[packet[:local_id]].do_window_adjust(packet[:extra_bytes])
660
+ end
654
661
 
655
- def channel_window_adjust(packet)
656
- info { "channel_window_adjust: #{packet[:local_id]} +#{packet[:extra_bytes]}" }
657
- channels[packet[:local_id]].do_window_adjust(packet[:extra_bytes])
658
- end
662
+ def channel_request(packet)
663
+ info { "channel_request: #{packet[:local_id]} #{packet[:request]} #{packet[:want_reply]}" }
664
+ channels[packet[:local_id]].do_request(packet[:request], packet[:want_reply], packet[:request_data])
665
+ end
659
666
 
660
- def channel_request(packet)
661
- info { "channel_request: #{packet[:local_id]} #{packet[:request]} #{packet[:want_reply]}" }
662
- channels[packet[:local_id]].do_request(packet[:request], packet[:want_reply], packet[:request_data])
663
- end
667
+ def channel_data(packet)
668
+ info { "channel_data: #{packet[:local_id]} #{packet[:data].length}b" }
669
+ channels[packet[:local_id]].do_data(packet[:data])
670
+ end
664
671
 
665
- def channel_data(packet)
666
- info { "channel_data: #{packet[:local_id]} #{packet[:data].length}b" }
667
- channels[packet[:local_id]].do_data(packet[:data])
668
- end
672
+ def channel_extended_data(packet)
673
+ info { "channel_extended_data: #{packet[:local_id]} #{packet[:data_type]} #{packet[:data].length}b" }
674
+ channels[packet[:local_id]].do_extended_data(packet[:data_type], packet[:data])
675
+ end
669
676
 
670
- def channel_extended_data(packet)
671
- info { "channel_extended_data: #{packet[:local_id]} #{packet[:data_type]} #{packet[:data].length}b" }
672
- channels[packet[:local_id]].do_extended_data(packet[:data_type], packet[:data])
673
- end
677
+ def channel_eof(packet)
678
+ info { "channel_eof: #{packet[:local_id]}" }
679
+ channels[packet[:local_id]].do_eof
680
+ end
674
681
 
675
- def channel_eof(packet)
676
- info { "channel_eof: #{packet[:local_id]}" }
677
- channels[packet[:local_id]].do_eof
678
- end
682
+ def channel_close(packet)
683
+ info { "channel_close: #{packet[:local_id]}" }
679
684
 
680
- def channel_close(packet)
681
- info { "channel_close: #{packet[:local_id]}" }
685
+ channel = channels[packet[:local_id]]
686
+ channel_closed(channel)
687
+ end
682
688
 
683
- channel = channels[packet[:local_id]]
684
- channel_closed(channel)
685
- end
689
+ def channel_success(packet)
690
+ info { "channel_success: #{packet[:local_id]}" }
691
+ channels[packet[:local_id]].do_success
692
+ end
686
693
 
687
- def channel_success(packet)
688
- info { "channel_success: #{packet[:local_id]}" }
689
- channels[packet[:local_id]].do_success
690
- end
694
+ def channel_failure(packet)
695
+ info { "channel_failure: #{packet[:local_id]}" }
696
+ channels[packet[:local_id]].do_failure
697
+ end
691
698
 
692
- def channel_failure(packet)
693
- info { "channel_failure: #{packet[:local_id]}" }
694
- channels[packet[:local_id]].do_failure
695
- end
699
+ def io_select_wait(wait)
700
+ [wait, max_select_wait_time].compact.min
701
+ end
696
702
 
697
- def io_select_wait(wait)
698
- [wait, max_select_wait_time].compact.min
699
- end
703
+ MAP = Constants.constants.each_with_object({}) do |name, memo|
704
+ value = const_get(name)
705
+ next unless Integer === value
700
706
 
701
- MAP = Constants.constants.inject({}) do |memo, name|
702
- value = const_get(name)
703
- next unless Integer === value
704
- memo[value] = name.downcase.to_sym
705
- memo
707
+ memo[value] = name.downcase.to_sym
708
+ end
706
709
  end
710
+ end
707
711
  end
708
-
709
- end; end; end
712
+ end