/*
*
*              Reverse MX Filter for Postfix 2
*                    reject_bad_rmx
*           (c) 2004 Elita rozanski@sergiusz.com
*
*/

/*
MXfilter 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, or (at your option) any later
version.
*/

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <ctype.h>
#include <arpa/nameser.h>
#include <resolv.h>
#include <arpa/inet.h>

#include "gettxt.h"

struct rrecord {
    int16_t r_type;
    int16_t r_class;
    u_int32_t r_ttl;
    int16_t r_length;
};

/*
-2 no data or no txt
-1 dns error
0 ok
*/

int gettxt(char *domain, char *res, int sizeof_res, int *querycount, int querymax) {
    static char out[1000];
    unsigned char query[1000];
    HEADER *h;
    unsigned char *p;
    int qcount, acount;
    char buf[1000];
    struct rrecord *r;

    querycount[0]++;
    if(querycount[0]>querymax) return -1;

    if (res_search(domain, C_IN, T_TXT, query, 1000) <= 0) {
        if(h_errno == HOST_NOT_FOUND ||
                h_errno == TRY_AGAIN ||
                h_errno == NO_DATA)
            return (-2);
        return -1;
	}

    h = (HEADER *) query;

    p = query + sizeof(HEADER);
    qcount = ntohs(h->qdcount);	/* # of queries present */
    acount = ntohs(h->ancount);	/* # of answers present */
    
    /* get past queries */
    while (qcount--) {
	p += dn_expand(query, query + 1000, p, buf, 1000);
	p += 4;			/* qclass, qtype */
    }

    out[0] = 0;
    while (acount--) {
	p += dn_expand(query, query + 1000, p, buf, 1000);

	r = (struct rrecord *) p;
	if (htons(r->r_type) == T_TXT) {		/* TXT record */
	    char result[1024];
	    unsigned char *p1 = p + 11;
	    snprintf(result,sizeof(result),"%.*s",ntohs(r->r_length)-1,p1);
	    snprintf(res,sizeof_res,"%s",result);
	    return 0;
//TODO multiple!
	    }
	p = p + 10 + ntohs(r->r_length);	/* skip RR header and data */
    }

return -2;
}
