net-ssh 3.2.0.rc2 → 7.1.0

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