#include <string.h>
#include <ctype.h>
#include <stdio.h>

#include "acl.h"

/*
test access list for mxfilter
return 0 for skip
return 1 for check
return < 0 for error
*/

int mxfilter_acl(char *recipient, char *result, int sresult, char *reason, int sreason) {
FILE *p;
char buf[1024],*k;
char r[1024];
int i;

result[0]=0;
reason[0]=0;

if(strlen(recipient)==0)return -1; //recipient empty

snprintf(r,sizeof(r),"%s",recipient);

for(i=0;i<strlen(r);i++)
    r[i]=tolower(r[i]);

if(!(p=fopen("/etc/postfix/mxfilter.acl","r"))) return -2; //acl error

while(fgets(buf,sizeof(buf)-1,p)) {
    k=(char *)index(buf,10);
    if(k)k[0]=0;
    k=(char *)index(buf,13);
    if(k)k[0]=0;
    
    if(strlen(buf)>0) { // empty line ignore
	if(buf[0]!='#') { // remark line ignore
	    k=(char *)index(buf,9);
	    if(k) { //bad line ignore
		k++[0]=0;
// printf("* %s %s %s\n",recipient,buf,k);
		if(strstr(r,buf) || strcmp(buf,"*")==0) { // ok
		    if(strncmp(k,"check",5)==0) {
			k=(char *)index(k,9);
			if(k) {
			    k++;
			    snprintf(result,sresult,"%s",k);
			    k=(char *)index(result,9);
			    if(k) {
				k++[0]=0;
				snprintf(reason,sreason,"%s",k);
				}
			    }
// printf("** %s %s\n",result,reason);
			return 1;
			}
		    if(strcmp(k,"skip")==0)
			return 0;
		    // other action ignore
		    }
		}
	    }    
	}
    }
fclose(p);
return 0; //default skip
}
