Package x2go :: Module forward
[frames] | no frames]

Source Code for Module x2go.forward

  1  #!/usr/bin/env python 
  2   
  3  # Copyright (C) 2010-2011 by Mike Gabriel <mike.gabriel@das-netzwerkteam.de> 
  4  # 
  5  # Python X2go is free software; you can redistribute it and/or modify 
  6  # it under the terms of the GNU General Public License as published by 
  7  # the Free Software Foundation; either version 3 of the License, or 
  8  # (at your option) any later version. 
  9  # 
 10  # Python X2go is distributed in the hope that it will be useful, 
 11  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
 12  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 13  # GNU General Public License for more details. 
 14  # 
 15  # You should have received a copy of the GNU General Public License 
 16  # along with this program; if not, write to the 
 17  # Free Software Foundation, Inc., 
 18  # 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. 
 19   
 20  """\ 
 21  Python Gevent based port forwarding server (openssh -L option) for the 
 22  proxying of graphical X2go elements. 
 23   
 24  """ 
 25  __NAME__ = "x2gofwtunnel-pylib" 
 26   
 27  # modules 
 28  import os, sys, copy 
 29   
 30  # gevent/greenlet 
 31  import gevent 
 32  from gevent import select, socket 
 33  from gevent.server import StreamServer 
 34   
 35  # Python X2go modules 
 36  import log 
 37  from defaults import X2GOCLIENT_OS as _X2GOCLIENT_OS 
 38  import x2go_exceptions 
 39   
40 -class X2goFwServer(StreamServer):
41 """\ 42 L{X2goFwServer} implements a gevent's StreamServer based Paramiko/SSH port 43 forwarding server. 44 45 An L{X2goFwServer} class object is used to tunnel graphical trafic 46 through an external proxy command launched by a C{X2goProxy*} backend. 47 48 """
49 - def __init__ (self, listener, remote_host, remote_port, ssh_transport, session_instance=None, logger=None, loglevel=log.loglevel_DEFAULT,):
50 """\ 51 @param listener: listen on TCP/IP socket C{(<IP>, <Port>)} 52 @type listener: C{tuple} 53 @param remote_host: hostname or IP of remote host (in case of X2go mostly 127.0.0.1) 54 @type remote_host: C{str} 55 @param remote_port: port of remote host 56 @type remote_port: C{int} 57 @param ssh_transport: a valid Paramiko/SSH transport object 58 @type ssh_transport: C{instance} 59 @param logger: you can pass an L{X2goLogger} object to the 60 L{X2goFwServer} constructor 61 @type logger: C{instance} 62 @param loglevel: if no L{X2goLogger} object has been supplied a new one will be 63 constructed with the given loglevel 64 @type loglevel: C{int} 65 66 """ 67 if logger is None: 68 self.logger = log.X2goLogger(loglevel=loglevel) 69 else: 70 self.logger = copy.deepcopy(logger) 71 self.logger.tag = __NAME__ 72 73 self.chan = None 74 self.is_active = False 75 self.keepalive = False 76 self.chain_host = remote_host 77 self.chain_port = remote_port 78 self.ssh_transport = ssh_transport 79 self.session_instance = session_instance 80 81 self.fw_socket = None 82 83 StreamServer.__init__(self, listener, self.x2go_forward_tunnel_handle)
84
85 - def x2go_forward_tunnel_handle(self, fw_socket, address):
86 """\ 87 Handle for SSH/Paramiko forwarding tunnel. 88 89 @param fw_socket: local end of the forwarding tunnel 90 @type fw_socket: C{instance} 91 @param address: unused/ignored 92 @type address: C{tuple} 93 94 """ 95 self.fw_socket = fw_socket 96 97 # disable Nagle algorithm in TCP/IP protocol 98 self.fw_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) 99 100 _success = False 101 _count = 0 102 _maxwait = 20 103 104 while not _success and _count < _maxwait: 105 106 # it is recommended here to have passed on the session instance to this object... 107 if self.session_instance: 108 if not self.session_instance.is_connected(): 109 break 110 111 _count += 1 112 try: 113 self.chan = self.ssh_transport.open_channel('direct-tcpip', 114 (self.chain_host, self.chain_port), 115 self.fw_socket.getpeername()) 116 chan_peername = self.chan.getpeername() 117 _success = True 118 except Exception, e: 119 self.logger('incoming request to %s:%d failed on attempt %d of %d: %s' % (self.chain_host, 120 self.chain_port, 121 _count, 122 _maxwait, 123 repr(e)), 124 loglevel=log.loglevel_WARN) 125 gevent.sleep(.4) 126 127 128 if not _success: 129 self.logger('incoming request to %s:%d failed after %d attempts' % (self.chain_host, 130 self.chain_port, 131 _count), 132 loglevel=log.loglevel_ERROR) 133 else: 134 # once we are here, we can presume the tunnel to be active... 135 self.is_active = True 136 137 if self.chan is None: 138 self.logger('incoming request to [%s]:%d was rejected by the SSH server.' % 139 (self.chain_host, self.chain_port), loglevel=log.loglevel_ERROR) 140 if self.session_instance: 141 self.session_instance.HOOK_forwarding_tunnel_setup_failed(chain_host=self.chain_host, chain_port=self.chain_port) 142 return 143 else: 144 self.logger('connected! Tunnel open %r -> %r -> %r' % (self.fw_socket.getpeername(), 145 chan_peername, (self.chain_host, self.chain_port)), 146 loglevel=log.loglevel_INFO) 147 self.keepalive = True 148 try: 149 while self.keepalive: 150 r, w, x = select.select([self.fw_socket, self.chan], [], []) 151 if fw_socket in r: 152 data = fw_socket.recv(1024) 153 if len(data) == 0: 154 break 155 self.chan.send(data) 156 if self.chan in r: 157 data = self.chan.recv(1024) 158 if len(data) == 0: 159 break 160 fw_socket.send(data) 161 self.close_channel() 162 self.close_socket() 163 except socket.error: 164 pass 165 166 self.is_active = False 167 self.logger('Tunnel closed from %r' % (chan_peername,), 168 loglevel=log.loglevel_INFO)
169
170 - def close_channel(self):
171 """\ 172 Close an open channel again. 173 174 """ 175 #if self.chan is not None and _X2GOCLIENT_OS != "Windows": 176 if self.chan is not None: 177 try: 178 if _X2GOCLIENT_OS != 'Windows': 179 self.chan.close() 180 self.chan = None 181 except EOFError: 182 pass
183
184 - def close_socket(self):
185 """\ 186 Close the forwarding tunnel's socket again. 187 188 """ 189 _success = False 190 _count = 0 191 _maxwait = 20 192 193 # try at least <_maxwait> times 194 while not _success and _count < _maxwait: 195 _count += 1 196 try: 197 self.close_channel() 198 if self.fw_socket is not None: 199 self.fw_socket.close() 200 _success = True 201 except socket.error: 202 gevent.sleep(.2) 203 self.logger('could not close fw_tunnel socket, try again (%s of %s)' % (_count, _maxwait), loglevel=log.loglevel_WARN) 204 205 if _count >= _maxwait: 206 self.logger('forwarding tunnel to [%s]:%d could not be closed properly' % (self.chain_host, self.chain_port), loglevel=log.loglevel_WARN)
207
208 - def stop(self):
209 """\ 210 Stop the forwarding tunnel. 211 212 """ 213 self.close_socket() 214 StreamServer.stop(self)
215 216
217 -def start_forward_tunnel(local_host='127.0.0.1', local_port=22022, 218 remote_host='127.0.0.1', remote_port=22, 219 ssh_transport=None, 220 session_instance=None, 221 logger=None, ):
222 """\ 223 Setup up a Paramiko/SSH port forwarding tunnel (like openssh -L option). 224 225 The tunnel is used to transport X2go graphics data through a proxy application like nxproxy. 226 227 @param local_host: local starting point of the forwarding tunnel 228 @type local_host: C{int} 229 @param local_port: listen port of the local starting point 230 @type local_port: C{int} 231 @param remote_host: from the endpoint of the tunnel, connect to host C{<remote_host>}... 232 @type remote_host: C{str} 233 @param remote_port: ... on port C{<remote_port>} 234 @type remote_port: C{int} 235 @param ssh_transport: the Paramiko/SSH transport (i.e. the X2go sessions Paramiko/SSH transport object) 236 @type ssh_transport: C{instance} 237 @param session_instance: the L{X2goSession} instance that initiates this tunnel 238 @type session_instance: C{instance} 239 @param logger: an X2goLogger object 240 @type logger: C{instance} 241 242 @return: returns an L{X2goFwServer} instance 243 @rtype: C{instance} 244 245 """ 246 try: 247 fw_server = X2goFwServer(listener=(local_host, local_port), 248 remote_host=remote_host, remote_port=remote_port, 249 ssh_transport=ssh_transport, session_instance=session_instance, 250 logger=logger, 251 ) 252 try: 253 fw_server.start() 254 return fw_server 255 except socket.error: 256 pass 257 except x2go_exceptions.X2goFwTunnelException: 258 pass 259 260 return None
261 262
263 -def stop_forward_tunnel(fw_server):
264 """\ 265 Tear down a given Paramiko/SSH port forwarding tunnel. 266 267 @param fw_server: an L{X2goFwServer} instance as returned by the L{start_forward_tunnel()} function 268 @type fw_server: C{instance} 269 270 """ 271 if fw_server is not None: 272 fw_server.keepalive = False 273 gevent.sleep(.5) 274 fw_server.stop()
275 276 277 if __name__ == '__main__': 278 pass 279