############################################################################
##
## Copyright (c) 2000-2001 BalaBit IT Ltd, Budapest, Hungary
## All rights reserved.
##
## $Id: Connector.py,v 1.20.2.3.2.1 2001/05/11 14:19:10 bazsi Exp $
##
## Author  : Bazsi
## Auditor : kisza
## Last version: 1.7
## Notes:
##
############################################################################

"""Implements classes to establish a connection.

This module implements a Python wrapper around the ZorpConnect class
implemented in C.
"""

import Zorp

connect_hook = None
unconnect_hook = None

class Connect:
	"""A wrapper class around the ZorpConnect class implemented in C.

	This class is a wrapper around the ZorpConnect class
	implemented by the Zorp core, and as such it'll be a placeholder
	for future extensions.
	   
	Attributes
	
	  local	  -- Address of local end of the connection (set after 
	             __init__ in nonblocking mode, or after blockingConnect() 
	             in blocking mode)
	  
	  remote  -- Address where we connect
	  
	  connect -- a Zorp.Connect object
	"""

	def __init__(self, local, remote, callback = None):
		"""Constructor initializing a Connect instance.
		
		Sets the instance attributes based on constructor
		parameters, and starts connecting in a separate thread if
		callback is not None. If callback is None, a separate call
		to blockingConnect() will start the connection.

		Arguments

		  self     -- this instance
		  
		  local    -- Address of local end of the connection
		  
		  remote   -- Address where we connect
		  
		  callback -- Callback to be called when the connection is
		              established. 
		"""
		global connect_hook
		
		self.local = local
		self.remote = remote
		self.connect = Zorp.Connect(local, remote, callback)
		if callback != None:
			self.connect.start()
			if connect_hook:
				connect_hook(self)
			self.local = self.connect.local
			
	def __del__(self):
		global unconnect_hook
		
		if unconnect_hook:
			unconnect_hook(self)
			
	def blockingConnect(self):
		"""Function establishing a connection in blocking mode.
		
		This function must be called when the Connect instance was
		initialized with callback=None. It establishes the connection
		in this thread (ie. waits for the connection to complete)
		and returns the file corresponding file descriptor.
		
		Arguments
		
		  self  -- this instance
		  
		Returns
		
		  the fd corresponding to the connection
		"""
		global connect_hook
		
		self.connect.start()
		self.local = self.connect.local
		if connect_hook:
			connect_hook(self)
		return self.connect.block()
		
	def destroy(self):
		"""Function to destroy this connector instance.
		
		This function forces the underlying ZorpConnect instance
		to stop connecting and free any allocated memory block.
		   
		Arguments
		
		  self -- instance
		"""
		self.connect.destroy()
