sonixlabs-net-ssh 2.3.0

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