/*
 * Copyright (c) 2005 Guillaume Destuynder <kang@rsbac.org>
 * rfc1738 functions by Harvest Derived for Squid and
 * Copyrighted (C) 2001 by the Regents of the University of California
 * 
 * Last modified: 25/Aug/2005
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <rsbac/types.h>
#include <rsbac/syscalls.h>
#include <rsbac/error.h>

/*
 *    rfc1738_unescape() - Converts escaped characters (%xy numbers) in 
 *     given the string.  %% is a %. %ab is the 8-bit hexadecimal number "ab"
 */
	void
rfc1738_unescape(char *s)
{
	char hexnum[3];
	int i, j;                   /* i is write, j is read */
	unsigned int x;
	for (i = j = 0; s[j]; i++, j++) {
		s[i] = s[j];
		if (s[i] != '%')
			continue;
		if (s[j + 1] == '%') {  /* %% case */
			j++;
			continue;
		}
		if (s[j + 1] && s[j + 2]) {
			if (s[j + 1] == '0' && s[j + 2] == '0') {   /* %00 case */
				j += 2;
				continue;
			}
			hexnum[0] = s[j + 1];
			hexnum[1] = s[j + 2];
			hexnum[2] = '\0';
			if (1 == sscanf(hexnum, "%x", &x)) {
				s[i] = (char) (0x0ff & x);
				j += 2;
			}
		}
	}
	s[i] = '\0';
}

int main(void)
{
	char buf[256];
	char *user, *passwd, *p;

	setbuf(stdout, NULL);
	while (fgets(buf, 256, stdin) != NULL) {
		if ((p = strchr(buf, '\n')) != NULL)
			*p = '\0';
	
		if ((user = strtok(buf, " ")) == NULL) {
			printf("ERR\n");
			continue;
		}
		if ((passwd = strtok(NULL, "")) == NULL) {
			printf("ERR\n");
			continue;
		}
		
		rfc1738_unescape(user);
		rfc1738_unescape(passwd);
		if (rsbac_um_auth_name(user, passwd))
			printf("ERR\n");
		else
			printf("OK\n");
	}

	exit(0);
}
