# -*- Mode: Python; tab-width: 4 -*-

import asynchat
import socket
import string

class ident_client (asynchat.async_chat):

	def __init__ (self, (remote_port,  local_port), remote_ip, callback):
		self.port_pair = (remote_port, local_port)
		self.remote_ip = remote_ip
		self.callback = callback
		self.set_terminator ('\r\n')
		self.data = ''
		asynchat.async_chat.__init__ (self)
		self.create_socket (socket.AF_INET, socket.SOCK_STREAM)
		self.connect ((remote_ip, 113))

	def handle_connect (self):
		self.send ('%d, %d\r\n' % self.port_pair)
		
	def handle_error (self, *info):
		# ignore all problems with ident
		self.close()

	def collect_incoming_data (self, data):
		if len(self.data) > 1000:
			# watch for naughty implementations...
			self.close()
		else:
			self.data = self.data + data

	def found_terminator (self):
		# sample replies:
		# 6193, 23 : USERID : UNIX : stjohns
		# 6195, 23 : ERROR : NO-USER
		line, self.data = self.data, ''
		parts = string.split (line, ':')
		if len(parts) >= 2:
			response = string.lower (string.strip (parts[1]))
			if response == 'userid':
				self.callback (string.strip (parts[3]))
		self.close()

