aboutsummaryrefslogtreecommitdiffstats
path: root/toys/de/derb/drbssh.rb
blob: 240ace06fc9d71bc6aea2df108e339bcbcfd2c97 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# -*- mode: ruby; tab-width: 4; indent-tabs-mode: t -*-

require 'drb'
require 'socket'
require 'timeout'

# DRb protocol handler for using a persistent SSH connection to a remote server. Creates a duplex
# connection so DRbUndumped objects can contact the initiating machine back through the same link.
#
# Contains all needed classes and no external dependencies, since this file will be read and sent
# to the remote end, to bootstrap its protocol support without requiring anything but Ruby
# installed.

# Original version by Kenneth Vestergaard
# Modified: 2013 Laurent Ghigonis <laurent@p1sec.com>

# Copyright (c) 2012 Kenneth Vestergaard
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

module DRb

	class DRbSSHProtocol
		def self.server; @server; end

		# Open a client connection to the server at +uri+, using configuration +config+, and return it.
		def self.open(uri, config)
			raise DRbServerNotFound, "need to run a DRbSSH server first" if @server.nil? or @server.closed?

			DRb.thread['DRbSSHLocalClient'] || DRbSSHRemoteClient.new(uri, @server)
		end

		# Open a server listening at +uri+, using configuration +config+, and return it.
		def self.open_server(uri, config)
			@server = nil if !@server.nil? and @server.closed?

			raise DRbConnError, "server already running with different uri" if !@server.nil? and @server.uri != uri

			@server ||= DRbSSHServer.new(uri, config)
		end

		# Parse +uri+ into a [uri, option] pair.
		def self.uri_option(uri, config)
			host, path = split_uri(uri)
			host ||= Socket.gethostname
			[ "drbssh://#{host}/#{path}", nil ]
		end

		# Split URI into component pairs
		def self.split_uri(uri)
			if uri.match('^drbssh://([^/?]+)?/?(?:(.+))?$')
				[ $1, $2 ]
			else
				raise DRbBadScheme,uri unless uri =~ /^drbssh:/
				raise DRbBadURI, "can't parse uri: " + uri
			end
		end
	end
	DRbProtocol.add_protocol(DRbSSHProtocol)


	# Base class for the DRbSSH clients.
	class DRbSSHClient
		attr_reader :receiveq
		attr_reader :sendq
		attr_reader :read_fd
		attr_reader :write_fd

		def initialize(server)
			@receiveq, @sendq = Queue.new, Queue.new
			@write_fd.sync = true

			server.client_queue.push(self)
		end

		def send_request(ref, msg_id, arg, b)
			@sendq.push(['req', [ref, msg_id, arg, b]])
		end

		def recv_reply
			reply = @receiveq.pop
			if reply.is_a? Exception
				self.close
				raise reply
			else
				reply
			end
		end

		def alive?
			!self.read_fd.closed? && !self.write_fd.closed?
		end
	end


	# DRbSSH remote client - does the heavy lifting of SSH'ing to a remote server and bootstrapping
	# its Ruby interpreter for DRb communication.
	class DRbSSHRemoteClient < DRbSSHClient
		# Create an SSH-connection to +uri+, and spawn a server, so client has something to talk to
		def initialize(uri, server)
			# child-to-parent, parent-to-child
			ctp_rd, ctp_wr = IO.pipe
			ptc_rd, ptc_wr = IO.pipe

			host, cmd = DRbSSHProtocol.split_uri(uri)

			# Read the source-code for this file, and add bits for initialising the remote side.
			# Since DRbSSHServer is doing all the filedescriptor read/writing, we need to start
			# a DRbSSHLocalClient immediately.
			self_code = <<-EOT
				#{File.read(__FILE__)};
				DRb.start_service("#{uri}", binding)
				DRb.thread['DRbSSHLocalClient'] = DRb::DRbSSHLocalClient.new(DRb::DRbSSHProtocol.server)
				DRb.thread.join
			EOT

			# Fork to create an SSH child-process
			if fork.nil?
				# In child - cleanup filehandles, reopen stdin/stdout, and exec ssh to connect to remote

				ctp_rd.close
				ptc_wr.close

				$stdin.reopen(ptc_rd)
				$stdout.reopen(ctp_wr)

				cmd = ['ruby'] if cmd.nil? or cmd.empty?

				# exec Ruby on remote end, and read bootstrap code.
				exec("ssh", "-oBatchMode=yes", "-T", host, "exec", cmd, '-e', "\"eval STDIN.read(#{self_code.bytesize})\"")
				exit
			else
				# In parent - cleanup filehandles, write bootstrap-code, and hand over to superclass.

				ctp_wr.close
				ptc_rd.close

				# Bootstrap remote Ruby.
				ptc_wr.write(self_code)

				@read_fd, @write_fd = ctp_rd, ptc_wr

				super(server)
			end
		end

		# Close client.
		def close
			# Closing the filedescriptors should trigger an IOError in the server-thread
			# waiting, which makes it close the client attached.
			self.read_fd.close unless self.read_fd.closed?
			self.write_fd.close unless self.write_fd.closed?
		end
	end


	# DRbSSH client used to contact local objects - used on remote side.
	class DRbSSHLocalClient < DRbSSHClient
		# Use stdin/stdout to talk with the local side of an SSH-connection.
		def initialize(server)
			@read_fd, @write_fd = $stdin, $stdout

			super(server)
		end

		# Kill Ruby if client is asked to close.
		def close
			Kernel.exit 0
		end
	end


	# Common DRb protocol server for DRbSSH. Waits on incoming clients on a thread-safe `Queue`,
	# and spawns a new connection handler for each.
	class DRbSSHServer
		attr_reader :uri
		attr_reader :client_queue

		# Create new server.
		def initialize(uri, config)
			@uri = uri
			@config = config
			@client_queue = Queue.new
			@clients = []
		end

		# Wait for clients to register themselves on the client_queue.
		def accept
			client = @client_queue.pop
			@clients << DRbSSHServerConn.new(uri, @config, client)
			@clients.last
		end

		# Close server by closing all clients.
		def close
			@clients.map(&:close)
			@clients = nil
		end

		# Server is closed if +close+ has been called earlier.
		def closed?
			@clients.nil?
		end
	end


	# DRbSSH protocol server per-connection class. Handles client-to-client communications
	# by utilizing thread-safe Queue's for the input and output, and by adding a small
	# 'rep' or 'req' packet before sending, so we can have two-way DRb duplexed over a
	# single pair of filedescriptors.
	class DRbSSHServerConn
		attr_reader :uri

		# Create a new server-connection for the specified +client+.
		def initialize(uri, config, client)
			@uri = uri
			@client = client
			@srv_requestq = Queue.new

			msg = DRbMessage.new(config)

			# Read-thread
			Thread.new do
				# Read from client, and delegate request/reply to the correct place.
				begin
					loop do
						type = msg.load(client.read_fd)
						if type == 'req'
							@srv_requestq.push(msg.recv_request(client.read_fd))
						else
							client.receiveq.push(msg.recv_reply(client.read_fd))
						end
					end
				rescue
					client.receiveq.push($!)
					@srv_requestq.push($!)
				end
			end

			# Write-thread
			Thread.new do
				# Wait for outgoing data on send queue, and add header-packet before
				# writing.
				begin
					loop do
						type, data = client.sendq.pop

						client.write_fd.write(msg.dump(type))

						if type == 'req'
							msg.send_request(client.write_fd, *data)
						else
							msg.send_reply(client.write_fd, *data)
						end
					end
				rescue
					client.receiveq.push($!)
					@srv_requestq.push($!)
				end
			end
		end

		# Delegate shutdown to client.
		def close
			return unless @client.alive?

			Timeout::timeout(15) do
				sleep 0.1 until @client.sendq.empty?
			end rescue nil

			@client.close
		end

		# Wait for a request to appear on the request-queue
		def recv_request
			reply = @srv_requestq.pop
			if reply.is_a? Exception
				self.close
				raise reply
			else
				reply
			end
		end

		# Queue client-reply
		def send_reply(succ, result)
			@client.sendq.push(['rep', [succ, result]])
		end
	end
end