#!/usr/bin/env python

# Copyright 2008-2009 Thomas Arnett
# Licensed under the Open Software License, version 3.0

'''pipe authenticator for Dovecot and jabberd2
http://jabberd2.xiaoka.com/export/250/trunk/docs/dev/c2s-pipe-authenticator'''

# COMPAT: Python 2.6
from __future__ import print_function
try:
	input = raw_input
except NameError:
	pass

import sys

import dovecot

SERVICE = 'jabberd'

def check(username, pass_b64):
	return client.auth(username, pass_b64.decode('base64'), SERVICE)

commands = {
	   'USER-EXISTS': lambda username: master.user(username, SERVICE),
	'CHECK-PASSWORD': check,
	          'FREE': exit
}

# handshake with Dovecot
client = dovecot.Client()
master = dovecot.Master(client)

# handshake with jabberd2
print('OK', *commands.keys())
sys.stdout.flush()

while True:
	try:
		args = input().split(' ')
		ok = commands[args.pop(0)](*args)
	except EOFError:
		exit()
	except Exception:
		ok = False
	
	print('OK' if ok else 'NO')
	sys.stdout.flush()
