/*
  decode_ldap.c

  Lightweight Directory Access Protocol.
  
  Copyright (c) 2000 Dug Song <dugsong@monkey.org>
 
  $Id: decode_ldap.c,v 1.2 2000/06/14 16:16:00 dugsong Exp $
*/

#include "config.h"

#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include "asn1.h"
#include "decode.h"

int
decode_ldap(u_char *buf, int len)
{
	u_char *p, *q;
	int i, type, alen = len;
	char *dn, *auth;
	
	Buf[0] = '\0';
	
	for (q = buf; q + 10 < buf + len; q += alen) {
		p = q;
		type = asn1_type(&p);
		if ((alen = asn1_len(&p)) <= 0) break;
		alen += (p - q);
		
		if (type != ASN1_SEQUENCE)		/* LDAPMessage */
			continue;
		
		if (asn1_type(&p) != ASN1_INTEGER)	/* messageID */
			continue;
		p += asn1_len(&p);
		
		if (*p != 0x60) continue;		/* op */
		p += 2;
		
		if (asn1_type(&p) != ASN1_INTEGER)	/* version */
			continue;
		p += asn1_len(&p);
		
		if (asn1_type(&p) != ASN1_STRING)	/* name */
			continue;
		if ((i = asn1_len(&p)) <= 0)
			continue;
		
		p--; memmove(p, p + 1, i); p[i] = '\0';	/* XXX - i suk */
		dn = p;
		p += (i + 1);
		
		if (*p++ != 0x80) continue;		/* simple auth [0] */
		if ((i = asn1_len(&p)) <= 0)
			continue;
		p--; memmove(p, p + 1, i); p[i] = '\0';	/* XXX - i suk */
		auth = p;
		
		snprintf(Buf, sizeof(Buf) - strlen(Buf), "%s\n%s\n", dn, auth);
	}
	return (strlen(Buf));
}

