1 # This program is free software; you can redistribute it and/or modify
2 # it under the terms of the GNU General Public License as published by
3 # the Free Software Foundation; either version 2 of the License, or
4 # (at your option) any later version.
6 # This program is distributed in the hope that it will be useful,
7 # but WITHOUT ANY WARRANTY; without even the implied warranty of
8 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9 # GNU Library General Public License for more details.
11 # You should have received a copy of the GNU General Public License
12 # along with this program; if not, write to the Free Software
13 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15 # See the COPYING file for license information.
17 # Copyright (c) 2006, 2007, 2008 Guillaume Chazarain <guichaz@gmail.com>
26 from gsh
.buffered_dispatcher
import buffered_dispatcher
27 from gsh
import callbacks
28 from gsh
.console
import console_output
29 from gsh
import file_transfer
31 # Either the remote shell is expecting a command or one is already running
32 STATE_NAMES
= ['not_started', 'idle', 'running', 'terminated']
37 STATE_TERMINATED
= range(len(STATE_NAMES
))
39 # Count the total number of remote_dispatcher.handle_read() invocations
42 def main_loop_iteration(timeout
=None):
43 """Return the number of remote_dispatcher.handle_read() calls made by this
45 prev_nr_read
= nr_handle_read
46 asyncore
.loop(count
=1, timeout
=timeout
, use_poll
=True)
47 return nr_handle_read
- prev_nr_read
51 options
.log_file
.write(msg
)
53 class remote_dispatcher(buffered_dispatcher
):
54 """A remote_dispatcher is a ssh process we communicate with"""
56 def __init__(self
, hostname
):
57 self
.pid
, fd
= pty
.fork()
60 self
.launch_ssh(hostname
)
64 buffered_dispatcher
.__init
__(self
, fd
)
65 self
.hostname
= hostname
66 self
.debug
= options
.debug
67 self
.active
= True # deactived shells are dead forever
68 self
.enabled
= True # shells can be enabled and disabled
69 self
.state
= STATE_NOT_STARTED
70 self
.term_size
= (-1, -1)
71 self
.display_name
= ''
72 self
.change_name(hostname
)
73 self
.init_string
= self
.configure_tty() + self
.set_prompt()
74 self
.init_string_sent
= False
75 self
.command
= options
.command
77 def launch_ssh(self
, name
):
78 """Launch the ssh command in the child process"""
79 evaluated
= options
.ssh
% {'host': name
}
80 if evaluated
== options
.ssh
:
81 evaluated
= '%s %s' % (evaluated
, name
)
82 os
.execlp('/bin/sh', 'sh', '-c', evaluated
)
84 def set_enabled(self
, enabled
):
85 from gsh
.dispatchers
import update_max_display_name_length
86 self
.enabled
= enabled
87 if options
.interactive
:
88 # In non-interactive mode, remote processes leave as soon
89 # as they are terminated, but we don't want to break the
90 # indentation if all the remaining processes have short names.
91 l
= len(self
.display_name
)
94 update_max_display_name_length(l
)
96 def change_state(self
, state
):
97 """Change the state of the remote process, logging the change"""
98 if state
is not self
.state
:
100 self
.print_debug('state => %s' % (STATE_NAMES
[state
]))
103 def disconnect(self
):
104 """We are no more interested in this remote process"""
106 os
.kill(self
.pid
, signal
.SIGKILL
)
108 # The process was already dead, no problem
110 self
.read_buffer
= ''
111 self
.write_buffer
= ''
113 self
.set_enabled(False)
114 if options
.abort_error
and self
.state
is STATE_NOT_STARTED
:
115 raise asyncore
.ExitNow(1)
118 """Relaunch and reconnect to this same remote process"""
121 remote_dispatcher(self
.hostname
)
123 def configure_tty(self
):
124 """We don't want \n to be replaced with \r\n, and we disable the echo"""
125 attr
= termios
.tcgetattr(self
.fd
)
126 attr
[1] &= ~termios
.ONLCR
# oflag
127 attr
[3] &= ~termios
.ECHO
# lflag
128 termios
.tcsetattr(self
.fd
, termios
.TCSANOW
, attr
)
129 # unsetopt zle prevents Zsh from resetting the tty
130 return 'unsetopt zle 2> /dev/null;stty -echo -onlcr;'
132 def seen_prompt_cb(self
, unused
):
133 if options
.interactive
:
134 self
.change_state(STATE_IDLE
)
136 self
.dispatch_command(self
.command
+ '\n')
139 self
.change_state(STATE_TERMINATED
)
142 def set_prompt(self
):
143 """The prompt is important because we detect the readyness of a process
144 by waiting for its prompt. The prompt is built in two parts for it not
145 to appear in its building"""
147 command_line
= 'RPS1=;RPROMPT=;'
148 command_line
+= 'TERM=ansi;'
149 prompt1
, prompt2
= callbacks
.add('prompt', self
.seen_prompt_cb
, True)
150 command_line
+= 'PS1="%s""%s\n"\n' % (prompt1
, prompt2
)
154 """We are always interested in reading from active remote processes if
156 return self
.active
and buffered_dispatcher
.readable(self
)
158 def handle_error(self
):
159 """An exception may or may not lead to a disconnection"""
160 if buffered_dispatcher
.handle_error(self
):
161 console_output('Error talking to %s\n' % self
.display_name
)
164 def print_lines(self
, lines
):
165 from gsh
.dispatchers
import max_display_name_length
166 lines
= lines
.strip('\n')
168 no_empty_lines
= lines
.replace('\n\n', '\n')
169 if len(no_empty_lines
) == len(lines
):
171 lines
= no_empty_lines
174 indent
= max_display_name_length
- len(self
.display_name
)
175 prefix
= self
.display_name
+ indent
* ' ' + ': '
176 console_output(prefix
+ lines
.replace('\n', '\n' + prefix
) + '\n')
178 def handle_read_fast_case(self
, data
):
179 """If we are in a fast case we'll avoid the long processing of each
181 if callbacks
.contains(data
) or self
.state
is not STATE_RUNNING
:
185 last_nl
= data
.rfind('\n')
187 # No '\n' in data => slow case
189 self
.read_buffer
= data
[last_nl
+ 1:]
190 self
.print_lines(data
[:last_nl
])
193 def handle_read(self
):
194 """We got some output from a remote shell, this is one of the state
198 global nr_handle_read
200 new_data
= buffered_dispatcher
.handle_read(self
)
202 self
.print_debug('==> ' + new_data
)
203 if self
.handle_read_fast_case(self
.read_buffer
):
205 lf_pos
= new_data
.find('\n')
207 # Optimization: we knew there were no '\n' in the previous read
208 # buffer, so we searched only in the new_data and we offset the
209 # found index by the length of the previous buffer
210 lf_pos
+= len(self
.read_buffer
) - len(new_data
)
212 # For each line in the buffer
213 line
= self
.read_buffer
[:lf_pos
+ 1]
214 if callbacks
.process(line
):
216 elif self
.state
in (STATE_IDLE
, STATE_RUNNING
):
217 self
.print_lines(line
)
218 elif self
.state
is STATE_NOT_STARTED
:
219 if 'The authenticity of host' in line
:
220 msg
= line
.strip('\n') + ' Closing connection.'
222 elif 'REMOTE HOST IDENTIFICATION HAS CHANGED' in line
:
223 msg
= 'Remote host identification has changed.'
228 self
.print_lines(msg
+ ' Consider manually connecting or ' +
229 'using ssh-keyscan.')
231 # Go to the next line in the buffer
232 self
.read_buffer
= self
.read_buffer
[lf_pos
+ 1:]
233 if self
.handle_read_fast_case(self
.read_buffer
):
235 lf_pos
= self
.read_buffer
.find('\n')
236 if self
.state
is STATE_NOT_STARTED
and not self
.init_string_sent
:
237 self
.dispatch_write(self
.init_string
)
238 self
.init_string_sent
= True
240 def print_unfinished_line(self
):
241 """The unfinished line stayed long enough in the buffer to be printed"""
242 if self
.state
is STATE_RUNNING
:
243 self
.print_lines(self
.read_buffer
)
244 self
.read_buffer
= ''
247 """Do we want to write something?"""
248 return self
.active
and buffered_dispatcher
.writable(self
)
250 def handle_write(self
):
251 """Let's write as much as we can"""
252 num_sent
= self
.send(self
.write_buffer
)
254 self
.print_debug('<== ' + self
.write_buffer
[:num_sent
])
255 self
.write_buffer
= self
.write_buffer
[num_sent
:]
257 def print_debug(self
, msg
):
258 """Log some debugging information to the console"""
259 state
= STATE_NAMES
[self
.state
]
260 msg
= msg
.encode('string_escape')
261 console_output('[dbg] %s[%s]: %s\n' % (self
.display_name
, state
, msg
))
264 """Return a list with all information available about this process"""
266 state
= STATE_NAMES
[self
.state
]
275 return [self
.display_name
, 'fd:%d' % (self
.fd
),
276 'r:%d' % (len(self
.read_buffer
)),
277 'w:%d' % (len(self
.write_buffer
)),
278 self
.active
and 'active' or 'dead',
279 self
.enabled
and 'enabled' or 'disabled',
283 def dispatch_write(self
, buf
):
284 """There is new stuff to write when possible"""
285 if self
.active
and self
.enabled
:
286 buffered_dispatcher
.dispatch_write(self
, buf
)
289 def dispatch_command(self
, command
):
290 if self
.dispatch_write(command
):
291 self
.change_state(STATE_RUNNING
)
293 def change_name(self
, name
):
294 """Change the name of the shell, possibly updating the maximum name
296 from gsh
import dispatchers
299 previous_name_len
= len(self
.display_name
)
300 self
.display_name
= None
301 self
.display_name
= dispatchers
.make_unique_name(name
)
302 dispatchers
.update_max_display_name_length(len(self
.display_name
))
303 dispatchers
.update_max_display_name_length(-previous_name_len
)
305 def rename(self
, string
):
306 """Send to the remote shell, its new name to be shell expanded"""
308 rename1
, rename2
= callbacks
.add('rename', self
.change_name
, False)
309 self
.dispatch_command('/bin/echo "%s""%s"%s\n' %
310 (rename1
, rename2
, string
))
312 self
.change_name(self
.hostname
)
315 return self
.display_name