Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _check_is_started(self):
if not self.is_active: # underlying transport not alive
msg = 'Server is not started. Please .start() first!'
raise BaseSSHTunnelForwarderError(msg)
if not self.is_alive:
msg = 'Tunnels are not started. Please .start() first!'
raise HandlerSSHTunnelForwarderError(msg)
self._create_tunnels()
if not self.is_active:
self._raise(BaseSSHTunnelForwarderError,
reason='Could not establish session to SSH gateway')
for _srv in self._server_list:
thread = threading.Thread(
target=self._serve_forever_wrapper,
args=(_srv, ),
name='Srv-{0}'.format(address_to_str(_srv.local_port))
)
thread.daemon = self.daemon_forward_servers
thread.start()
self._check_tunnel(_srv)
self.is_alive = any(self.tunnel_is_up.values())
if not self.is_alive:
self._raise(HandlerSSHTunnelForwarderError,
'An error occurred while opening tunnels.')
try:
chan = self.ssh_transport.open_channel(
kind='direct-tcpip',
dest_addr=self.remote_address,
src_addr=src_address,
timeout=TUNNEL_TIMEOUT
)
except paramiko.SSHException:
chan = None
if chan is None:
msg = '{0} to {1} was rejected by the SSH server'.format(
self.info,
self.remote_address
)
self.logger.log(TRACE_LEVEL, msg)
raise HandlerSSHTunnelForwarderError(msg)
self.logger.log(TRACE_LEVEL, '{0} connected'.format(self.info))
try:
self._redirect(chan)
except socket.error:
# Sometimes a RST is sent and a socket error is raised, treat this
# exception. It was seen that a 3way FIN is processed later on, so
# no need to make an ordered close of the connection here or raise
# the exception beyond this point...
self.logger.log(TRACE_LEVEL, '{0} sending RST'.format(self.info))
except Exception as e:
self.logger.log(TRACE_LEVEL,
'{0} error: {1}'.format(self.info, repr(e)))
finally:
chan.close()
self.request.close()
def _stop_transport(self):
""" Close the underlying transport when nothing more is needed """
try:
self._check_is_started()
except (BaseSSHTunnelForwarderError,
HandlerSSHTunnelForwarderError) as e:
self.logger.warning(e)
for _srv in self._server_list:
tunnel = _srv.local_address
if self.tunnel_is_up[tunnel]:
self.logger.info('Shutting down tunnel {0}'.format(tunnel))
_srv.shutdown()
_srv.server_close()
# clean up the UNIX domain socket if we're using one
if isinstance(_srv, _UnixStreamForwardServer):
try:
os.unlink(_srv.local_address)
except Exception as e:
self.logger.error('Unable to unlink socket {0}: {1}'
.format(self.local_address, repr(e)))
self.is_alive = False
if self.is_active: