#!/usr/bin/env python

# For some information about the interface used, see :
# http://cr.yp.to/checkpwd/interface.html

import os
import sys

INPUT_FD = 3

try:
	ip	= os.environ['TCPREMOTEIP']
	port	= os.environ['TCPLOCALPORT']
except:
	print "Missing environment values"
	# If checkpassword is misused, it may instead exit 2
	sys.exit(2)
	

data = ""

try:
	file = os.fdopen(INPUT_FD)
	data = os.read(file.fileno(),512)
	file.close()
except:
	print "Could not get data from file descriptor 3"
	# If there is a temporary problem checking the password, checkpassword exits 111
	sys.exit(111)



res = 0

for check in ['/bin/checkpassword','/var/qmail/bin/auth_pop']:

	prog = check.split('/')[-1]
	sys.argv[0] = prog

	(r,w) = os.pipe()

	os.write(w,data)
	os.close(w)
	
	pid = os.fork()
		
	if pid:
		(pid, res) = os.waitpid(pid,0)
		res = res >> 8
		if res == 0:
			break
			
		os.close(r)
	else:
		os.execve(check,sys.argv,os.environ)


sys.exit(res)
