#!/usr/bin/env python3
# P@draigBrady.com
#
# This is a ckpasswd equivalent that verifies user passwords against the
# passwords stored in a Mailman list configuration file.  It allows users
# to access newsgroups with the same password as they use to access their
# Mailman configuration.
#
# To use this program, it needs to run as the Mailman user, and therefore
# may have to be run from a wrapper.  Other than that, use it like ckpasswd
# in a readers.conf file as an auth parameter, passing it the configuration
# file for the list as its only parameter.
#
# 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.


"""Reads username and password from stdin,
and database to use as first parameter.
and is meant to be used like ckpasswd is.
returns:
  0 success
  1 bad username &/or password
  2 other errors"""

import sys
import marshal
import string
import os

try:
    filename = sys.argv[1]
except IndexError:
    sys.stderr.write("Usage: " + sys.argv[0] + " /path/to/config.db\n")
    sys.exit(2)

fp = open(filename, "rb")
d = marshal.load(fp)
passwords = d["passwords"]
fp.close()

username = ""
password = ""

while 1:
    line = sys.stdin.readline()
    if line == "":
        break
    try:
        name, value = map(string.strip, line.split(":"))
        if name == "ClientAuthname":
            username = value
        if name == "ClientPassword":
            password = value
    except:
        pass

if not username or not password:
    sys.exit(2)

auth = 0
try:
    if passwords[username] == password:
        auth = 1
except:
    pass

if auth == 1:
    print("User:%s" % username)
    sys.exit(0)
else:
    sys.exit(1)
