summaryrefslogtreecommitdiffstats
path: root/rspamc.pl.in
blob: c353439bb99d55a17253cc9042de60baaf25fb99 (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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#!/usr/bin/perl -w

# Simple script that read message from STDIN and test it on rspamd server
# using specified command.
#
# Usage: rspamc.pl [-c conf_file] [command] [-s statfile]
#
# By default rspamc.pl would read ./rspamd.conf and default command is SYMBOLS

use Socket qw(:DEFAULT :crlf);
use Getopt::Std;

my %cfg = (
    'conf_file' => '@CMAKE_INSTALL_PREFIX@/etc/rspamd.conf',
    'command'   => 'SYMBOLS',
    'host'      => 'localhost',
    'port'      => '11333',
    'is_unix'   =>  0,
	'require_input'	=> 0,
    'password'  =>  '',
    'control'   =>  0,
    'statfile'  =>  '',
	'deliver_to'=>  '',
);

$main::VERSION = '@RSPAMD_VERSION@';

sub HELP_MESSAGE {
    print <<EOD;
Usage: rspamc.pl [-h host] [-p port] [-P password] [-c conf_file] [-s statfile] [-d user\@domain] [command] [path]
-h         host to connect or unix socket path
-p         port to connect (not used with unix sockets)
-P         define control password
-c         config file to parse
-s         statfile to use for learn commands
-d         define deliver-to header
imap format: imap:user:<username>:password:<password>:host:<hostname>:mbox:<mboxname>
Version:   @RSPAMD_VERSION@
EOD
};

# Load rspamd config params
sub parse_config {
    my ($is_ctrl) = @_;

    open CONF, "< $cfg{'conf_file'}" or die "config file $cfg{'conf_file'} cannot be opened";

    my $ctrl = 0, $skip = 0;
    while (<CONF>) {
        if ($_ =~ /^.*type.*=.*controller.*$/i) {
            $ctrl = 1;
        }
        if ($ctrl && $_ =~ /}/) {
            $ctrl = 0;
        }
        if ($_ =~ /^.*type.*=.*(?:lmtp|delivery|fuzzy).*$/i) {
            $skip = 1;
        }
        if ($skip && $_ =~ /}/) {
            $skip = 0;
        }
        if (!$skip && ((!$is_ctrl && !$ctrl) || ($ctrl && $is_ctrl))
                && $_ =~ /^\s*bind_socket\s*=\s*((([^:]+):(\d+))|(\/\S*))/i) {
            if ($3 && $4) {
                $cfg{'host'} = $3;
                $cfg{'port'} = $4;
                $cfg{'is_unix'} = 0;
            }
            else {
                $cfg{'host'} = $5;
                $cfg{'is_unix'} = 1;
            }
        }
        if ($ctrl && $is_ctrl && $_ =~ /^\s*password\s*=\s*"(\S+)"/) {
            $cfg{'password'} = $1;
        }
    }

    close CONF;

}

sub make_tcp_socket {
	my ($host, $port) = @_; 
	my $proto = getprotobyname('tcp');
	my $sin;

	socket ($sock, PF_INET, SOCK_STREAM, $proto) or die "cannot create tcp socket";
	if ($host eq '*') {
		$host = '127.0.0.1';
	}
	if (inet_aton ($host)) {
		$sin = sockaddr_in ($port, inet_aton($host));
	}
	else {
		my $addr = gethostbyname($host);
		if (!$addr) {
			die "cannot resolve $host";
		}
		$sin = sockaddr_in ($port, $addr);
	}
	
	connect ($sock, $sin) or die "cannot connect to socket $host:$port";

	return $sock;
}

sub make_ssl_socket {
	my ($host, $port) = @_; 
	
	eval {
		use IO::Socket::SSL;
	} or die 'cannot connect to imap without IO::Socket::SSL';

	return IO::Socket::SSL->new("$host:$port");
}

sub connect_socket {
    my $sock;

    if ($cfg{'is_unix'}) {
        socket ($sock, PF_UNIX, SOCK_STREAM, 0) or die "cannot create unix socket";
        my $sun = sockaddr_un($cfg{'host'});
        connect ($sock, $sun) or die "cannot connect to socket $cfg{'host'}";
    }
    else {
		$sock = make_tcp_socket ($cfg{'host'}, $cfg{'port'});
    }
    return $sock;
}

# Currently just read stdin for user's message and pass it to rspamd
sub do_rspamc_command {
    my ($sock, $input) = @_;

    print "Sending ". length ($input) ." bytes...\n";

    syswrite $sock, "$cfg{'command'} RSPAMC/1.1 $CRLF";
	if ($cfg{'deliver_to'}) {
		syswrite $sock, "Deliver-To: " . $cfg{'deliver_to'} . $CRLF;
	}
    syswrite $sock, "Content-Length: " . length ($input) . $CRLF . $CRLF;
    syswrite $sock, $input;
    syswrite $sock, $CRLF;
    while (defined (my $line = <$sock>)) {
        print $line;
    }
}

sub do_ctrl_auth {
    my ($sock) = @_;

    syswrite $sock, "password $cfg{'password'}" . $CRLF;
    if (defined (my $reply = <$sock>)) {
        my $end = <$sock>;
        if ($reply =~ /^password accepted/) {
            return 1;
        }
    }

    return 0;
}

sub do_control_command {
    my ($sock, $input) = @_;

    # Read greeting first
    if (defined (my $greeting = <$sock>)) {
        if ($greeting !~ /^Rspamd version/) {
            die "not rspamd greeting line $greeting";
        }
    }
    if ($cfg{'command'} =~ /^learn$/i) {
        die "statfile is not specified to learn command" if !$cfg{'statfile'};
        
        
        if (do_ctrl_auth ($sock)) {
            my $len = length ($input);
            print "Sending $len bytes...\n";
            syswrite $sock, "learn $cfg{'statfile'} $len" . $CRLF;
            syswrite $sock, $input . $CRLF;
            if (defined (my $reply = <$sock>)) {
                if ($reply =~ /^learn ok, sum weight: ([0-9.]+)/) {
                    print "Learn succeed. Sum weight: $1\n";
                }
                else {
                    print "Learn failed\n";
                }
            }
        }
        else {
            print "Authentication failed\n";
        }
    }
    elsif ($cfg{'command'} =~ /(reload|shutdown)/i) {
        if (do_ctrl_auth ($sock)) {
            syswrite $sock, $cfg{'command'} . $CRLF;
            while (defined (my $line = <$sock>)) {
                last if $line =~ /^END/;
                print $line;
            }
        }
        else {
            print "Authentication failed\n";
        }
    }
    elsif ($cfg{'command'} =~ /(fuzzy_add|fuzzy_del)/i) {
        if (do_ctrl_auth ($sock)) {
            my $len = length ($input);
            print "Sending $len bytes...\n";
            syswrite $sock, $cfg{'command'} . " $len" . $CRLF;
            syswrite $sock, $input . $CRLF;
            if (defined (my $reply = <$sock>)) {
                if ($reply =~ /^OK/) {
                    print $cfg{'command'} . " succeed\n";
                }
                else {
                    print $cfg{'command'} . " failed\n";
                }
            }
        }
        else {
            print "Authentication failed\n";
        }
    
    }
    else {
        syswrite $sock, $cfg{'command'} . $CRLF;
        while (defined (my $line = <$sock>)) {
            last if $line =~ /^END/;
            print $line;
        }
    }
}

sub process_file {
	my $file = shift;

	print "Process file: $file\n";
	open(FILE, "< $file") or return;
	
	my $input;
	while (defined (my $line = <FILE>)) {
		$input .= $line;
	}
	
	close FILE;
	do_cmd ($input);
}

sub process_directory {
	my $dir = shift;

	opendir (DIR, $dir) or return;

	while (defined (my $file = readdir (DIR))) {
		$file = "$dir/$file";
		if (-f $file) {
			process_file ($file);
		}	
	}
	closedir (DIR);
}

sub check_imap_reply {
	my $sock = shift;
	my $seq = shift;

	while (defined (<$sock>)) {
		chomp;
		next if ($_ =~ /^\*/);
		if ($_ =~ /^$seq OK/) {
			return 1;
		}
		return 0;
	}

	return 0;
}

sub parse_imap_sequences {
	my $sock = shift;
	my $seq = shift;
	my $input;
	my $got_body = 0;

	while (defined (<$sock>)) {
		if (!$got_body && $_ =~ /^\*/) {
			$got_body = 1;
			next;
		}
		if ($_ =~ /^$seq OK/) {
			return $input;
		}
		elsif ($got_body) {
			$input .= $_ . $CRLF;
		}

		return undef;
	}

	return undef;

}

sub process_imap_body {
	my $sock = shift;
	my $seq = shift;
	my $input;

	while (defined (<$sock>)) {
		chomp;
		if ($_ =~ /^\* SEARCH (.+)$/) {
			@res = split (/\s/, $1);
			next;
		}
		elsif ($_ =~ /^$seq OK/) {
			return \@res;
		}
		return undef;
	}

}

sub process_imap {
	my ($ssl, $user, $password, $host, $mbox) = @_;
	my $seq = 1;
	my $sock;
	print "Process imap: host: $host, mbox: $mbox\n";

	# Stupid code that does not take care of timeouts etc, just trying to extract messages
	if ($ssl) {
		$sock = make_ssl_socket ($host, 'imaps');
	}
	else {
		$sock = make_tcp_socket ($host, 143);
	}
	syswrite $sock, "$seq LOGIN $user $password$CRLF";
	if (!check_imap_reply ($sock, $seq)) {
		return;
	}
	$seq ++;
	syswrite $sock, "$seq SELECT $mbox$CRLF";
	if (!check_imap_reply ($sock, $seq)) {
		return;
	}
	$seq ++;
	syswrite $sock, "$seq FIND ALL$CRLF";
	my $messages;
	if (!defined ($messages = parse_imap_sequences ($sock, $seq))) {
		return;
	}
	$seq ++;
	foreach my $message (@{ $messages }){
		syswrite $sock, "$seq FETCH $message body[]$CRLF";
		if (defined (my $input = parse_imap_body ($sock, $seq))) {
			do_cmd ($input);
		}
		$seq ++;
	} 
	syswrite $sock, "$seq LOGOUT$CRLF";
	close $sock;
}

# Single item
sub process_item {
	my $item = shift;
	
	print "Processing $item\n";
	if (defined ($item)) {
		if ($item =~ qr|^imap(s?):user:([^:]+):password:([^:]):host:([^:]):mbox:(.+)$|) {
			process_imap_folder ($1, $2, $3, $4, $5);
		}
		elsif (-f $item) {
			process_file ($item);
		}
		elsif (-d $item) {
			process_directory ($item);
		}
		else {
			warn "urecognized argument: $item";
		}
	}
}

# Do specified command for each file in path or 
sub process_path {
	foreach (@_) {
		process_item($_);
	}
}

# Do specified command for specified input
sub do_cmd {
	my $input = shift;

    my $sock = connect_socket ();

    if ($cfg{'control'}) {
        do_control_command ($sock, $input);
    }
    else {
        do_rspamc_command ($sock, $input);
    }

    close ($sock);
}

############################# Main part ###########################################
my %args;
getopt('c:h:p:P:s:d:', \%args);
my $cmd = shift;
my @path = shift;
my $do_parse_config = 1;

if (!defined ($cmd) || $cmd eq '') {
    $cmd = 'SYMBOLS';
}

if (defined ($args{c})) {
     if (-r $args{c}) {
            $cfg{'conf_file'} = $args{c};
            $do_parse_config = 1;
     }
     else {
        die "config file $args{c} is not readable";
     }

}
if (defined ($args{s})) {
    if ($args{s}) {
        $cfg{'statfile'} = $args{s};
    }
    else {
        main::HELP_MESSAGE();
        exit;
    }
}
if (defined ($args{h})) {
    $cfg{'host'} = $args{h};
    if ($args{h} =~ /^\/.*$/) {
        $cfg{'is_unix'} = 1;
    }
    $do_parse_config = 0;
}
if (defined ($args{p})) {
    $cfg{'port'} = $args{p};
}
if (defined ($args{P})) {
    $cfg{'password'} = $args{P};
}
if (defined ($args{d})) {
	$cfg{'deliver_to'} = $args{d};
}

if ($cmd =~ /(SYMBOLS|SCAN|PROCESS|CHECK|REPORT_IFSPAM|REPORT|URLS|EMAILS)/i) {
    $cfg{'command'} = $1;
    $cfg{'control'} = 0;
}
elsif ($cmd =~ /(STAT|LEARN|SHUTDOWN|RELOAD|UPTIME|COUNTERS|FUZZY_ADD|FUZZY_DEL)/i) {
    $cfg{'command'} = $1;
    $cfg{'control'} = 1;
}
else {
    die "unknown command $cmd";
}

if ($cmd =~ /SYMBOLS|SCAN|PROCESS|CHECK|REPORT_IFSPAM|REPORT|URLS|EMAILS|LEARN|FUZZY_ADD|FUZZY_DEL/i) {
	$cfg{'require_input'} = 1;
}

if ($do_parse_config != 0) {
    parse_config ($cfg{'control'});
}

if (!defined ($path[0]) || ! $cfg{'require_input'}) {
	my $input;
	if ($cfg{'require_input'}) {
		while (defined (my $line = <>)) {
			$input .= $line;
		}
	}
	do_cmd ($input);
}
else {
	process_path (@path);
}