summaryrefslogtreecommitdiff
path: root/sys/src/cmd/upas/send/filter.c
blob: 8c70c1cfa1ce95d6034693b7cc665c8e53d04b64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include "common.h"
#include "send.h"
#include <regexp.h>

Biobuf	bin;
int	flagn;
int	flagx;
int	rmail;
int	tflg;
char	*subjectarg;

char*
findbody(char *p)
{
	if(*p == '\n')
		return p;

	while(*p){
		if(*p == '\n' && *(p+1) == '\n')
			return p+1;
		p++;
	}
	return p;
}

int
refuse(dest*, message *, char *cp, int, int)
{
	fprint(2, "%s\n", cp);
	exits("error");
	return 0;
}

void
usage(void)
{
	fprint(2, "usage: upas/filter [-nbh] rcvr mailbox [regexp file] ...\n");
	exits("usage");
}

void
main(int argc, char *argv[])
{
	char *cp, file[Pathlen];
	int i, header, body;
	message *mp;
	dest *dp;
	Reprog *p;
	Resub match[10];

	header = body = 0;
	ARGBEGIN {
	case 'n':
		flagn = 1;
		break;
	case 'h':
		header = 1;
		break;
	case 'b':
		header = 1;
		body = 1;
		break;
	default:
		usage();
	} ARGEND

	Binit(&bin, 0, OREAD);
	if(argc < 2)
		usage();
	mp = m_read(&bin, 1, 0);

	/* get rid of local system name */
	cp = strchr(s_to_c(mp->sender), '!');
	if(cp){
		cp++;
		mp->sender = s_copy(cp);
	}

	strecpy(file, file+sizeof file, argv[1]);
	cp = findbody(s_to_c(mp->body));
	for(i = 2; i < argc; i += 2){
		p = regcomp(argv[i]);
		if(p == 0)
			continue;
		if(regexec(p, s_to_c(mp->sender), match, 10)){
			regsub(argv[i+1], file, sizeof(file), match, 10);
			break;
		}
		if(header == 0 && body == 0)
			continue;
		if(regexec(p, s_to_c(mp->body), match, 10)){
			if(body == 0 && match[0].sp >= cp)
				continue;
			regsub(argv[i+1], file, sizeof(file), match, 10);
			break;
		}
	}
	dp = d_new(s_copy(argv[0]));
	dp->repl1 = s_copy(file);
	if(cat_mail(dp, mp) != 0)
		exits("fail");
	exits("");
}