######################################################################
#     XTalk - A BSD talk client written in Python.
#     (C) Adam P. Jenkins <adampjenkins@yahoo.com>
#     
#     This program is free software; you can redistribute it and/or
#     modify it under the terms of the GNU General Public License
#     as published by the Free Software Foundation; either version 2
#     of the License, or (at your option) any later version.
#     
#     This program is distributed in the hope that it will be useful,
#     but WITHOUT ANY WARRANTY; without even the implied warranty of
#     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#     GNU General Public License for more details.
#     
#     You should have received a copy of the GNU General Public License
#     along with this program; if not, write to the Free Software
#     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#
######################################################################

# talkd interface.  A TalkdInter object represents a pair of talk daemons.
# TalkdInter has the following member functions.  All of them may
# raise a TalkdInter.error exception.
# 
# __init__ (remote-host, remote-user, remote-tty='')
#
# leaveInvite (my-address)
#   where my-address is a (address, port) tupple of a socket waiting
#   for a connection
#
# lookUp ()
#   Does a lookup on the remote host to see if an invititation is
#   waiting.  If so, it returns an (address, port) tuple, otherwise an
#   exception is thrown
#
# deleteInvite (which)
#   which is either 'mine' or 'his'.  Deletes the invitation on the
#   local or remote host.  raises an "error" exception if there is no
#   invite waiting.
#
# announce ()
#   Announces on the remote users's screen that you want to talk.
#   raises an exception if the remote user isn't logged in or isn't
#   accepting connections
#
#
# A talk client wanting to establish a connection would use the
# following protocol.
# 1) Create a TalkdInter object for the desired (remote-host,
# remote-user, tty) that you want to connect with.
# 2) use lookUp() to see if there's already an invite waiting.  If so,
# lookUp() will return a (address, port) that the remote user is
# already waiting on.  Just connect to this (address, port) and you're
# all set.
# 3) If lookUp() failed, but not because the user wasn't logged in,
# then open a SOCK_STREAM socket, and listen on it for a connection.
# Call leaveInvite() with the (address, port) that you're listening
# on.
# 4) call announce() to announce to the remote user that you're
# waiting.  Now when they do a lookUp(), they'll find your (address,
# port) and connect to you.  You can keep sending an announce every so
# often.
# 5) When they connect to you, call deleteInvite('mine') to delete the
# invitation that you left.  You may also want to call
# deleteInvite('his') just to make sure the other one isn't left there.

import socket
from socket import *
from talkd import *
import pwd, os, errno, select

error = 'error'

_errorMsgs = ("Successful.",
	     "Your party is not logged on",
	     "Target machine is too confused to talk to us",
	     "Target machine does not recognize us",
	     "Your party is refusing messages",
	     "Target machine cannot handle remote talk",
	     "Target machine indicates protocol mismatch",
	     "Target machine indicates protocol botch (addr)",
	     "Target machine indicates protocol botch (ctl_addr)")

class TalkdInter:
    def __init__(self, rhost, ruser, rtty=''):
	self.lastAnnounce = -2
	self.localId = -1
	self.remoteId = -1
	self.rhost = rhost
	self.ruser = ruser
	self.rtty = rtty

	try:
	    self.luser = pwd.getpwuid(os.getuid())[0]
	    self.raddress = gethostbyname(rhost)
	    self.laddress = gethostbyname(gethostname())
	    self.talkdPort = getservbyname('ntalk', 'udp')

	    # set up a socket that will be used to communicate with a talk
	    # daemon, self.ctlSock. self.ctlAddr is the corresponding
	    # address. 
	    self.ctlSock = socket.socket(AF_INET, SOCK_DGRAM)
	    self.ctlAddr = (self.laddress, 0)
	    self.ctlSock.bind(self.ctlAddr)
	    # find out what port we were assigned
	    self.ctlAddr = self.ctlSock.getsockname()
	except socket.error, err:
	    raise error, err

	# and set up the CTL_MSG structure.  This initializes the
	# whole thing except for "addr", which isn't known until a
	# client wants to open a connection.
	self.ctlMsg = CTL_MSG()
	self.ctlMsg.ctlAddr = sockaddr_in(AF_INET, self.ctlAddr[1],
					    self.ctlAddr[0])
	self.ctlMsg.addr = sockaddr_in(AF_INET)
	self.ctlMsg.pid = os.getpid()
	self.ctlMsg.localName = self.luser
	self.ctlMsg.remoteName = self.ruser
	self.ctlMsg.remoteTTY = self.rtty

    # addr is a (host, port) tuple that the remote talk should respond
    # to.  Leaves an invitation with the local talk daemon.
    def leaveInvite(self, addr):
	self.ctlMsg.addr.address = addr[0]
	self.ctlMsg.addr.port = addr[1]
	
	response = self.transact(LEAVE_INVITE, self.laddress)
	# keep track of local id, so I can delete the invitation later
	self.localId = response.idNum

    # does a lookup on the remote talk daemon to see if there's an
    # invitation waiting.
    def lookUp(self):
	response = self.transact(LOOK_UP, self.raddress)
	if response.answer == SUCCESS:
	    self.remoteId = response.idNum
	    addr = (response.addr.address, response.addr.port)
	    return addr
	else:
	    raise error, _errorMsgs[response.answer]

    # deletes an invite.  which is either 'mine', or 'his', indicating
    # whether to delete the local or remote invitation
    def deleteInvite(self, which):
	if which == 'mine':
	    addr = self.laddress
	    self.ctlMsg.idNum = self.localId
	else:
	    addr = self.raddress
	    self.ctlMsg.idNum = self.remoteId
	response = self.transact(DELETE, addr)
	if response.answer != SUCCESS:
	    raise error, _errorMsgs[response.answer]
	
    def announce(self):
	self.ctlMsg.idNum = (self.lastAnnounce + 1)
	response = self.transact(ANNOUNCE, self.raddress)
	if response.answer != SUCCESS:
	    raise error, _errorMsgs[response.answer]
	else:
	    self.lastAnnounce = response.idNum

    def transact(self, type, addr):
	self.ctlMsg.type = type

	daemonAddr = (addr, self.talkdPort)
	sendData = self.ctlMsg.toCStruct()
	response = CTL_RESPONSE()
	response.version = -1

	while 1:
	    # resend message until a response is obtained
	    while 1:
		num = self.ctlSock.sendto(sendData, daemonAddr)
		if num != self.ctlMsg.size:
		    raise error, 'Error on write to talk daemon'
		try:
		    ready = select.select([self.ctlSock], [], [], 2.0)
		except select.error, er:
		    if er[0] != errno.EINTR:
			raise error, er[1]
		if ready[0]: break
		    
	    # keep reading while there are queued messages
	    while 1:
		try:
		    readData = self.ctlSock.recv(response.size)
		except socket.error, err:
		    if err[0] != errno.EINTR:
			raise error, err[1]
		response.fromCStruct(readData)
		ready = select.select([self.ctlSock], [], [], 0)
		if not ready[0] or (response.version == TALK_VERSION and
				    response.type == type):
		    break
	    if (response.version == TALK_VERSION and
		response.type == type):
		break
	return response
    
