Debian Codegraph @

contrib/ftpmail

raw
1 #!/usr/bin/env perl
2 # ---------------------------------------------------------------------------
3 # Copyright (C) 2008-2017 TJ Saunders <[email protected]>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
18 # ---------------------------------------------------------------------------
19
20 use strict;
21
22 use File::Basename qw(basename);
23 use Getopt::Long;
24 use Mail::Sendmail;
25 use MIME::Base64 qw(encode_base64);
26 use Time::HiRes qw(usleep);
27
28 my $program = basename($0);
29
30 my $opts = {};
31 GetOptions($opts, 'attach-file', 'fifo=s', 'from=s', 'help', 'ignore-users=s',
32 'log=s', 'recipient=s@', 'upload-recipient=s@', 'download-recipient=s@',
33 'sleep=s', 'smtp-server=s', 'subject=s', 'watch-users=s', 'auth=s');
34
35 if ($opts->{help}) {
36 usage();
37 exit 0;
38 }
39
40 unless ($opts->{fifo}) {
41 print STDERR "$program: missing required --fifo parameter\n";
42 exit 1;
43 }
44 my $fifo = $opts->{fifo};
45
46 unless ($opts->{from}) {
47 print STDERR "$program: missing required --from parameter\n";
48 exit 1;
49 }
50 my $from = $opts->{from};
51
52 unless ($opts->{recipient} ||
53 $opts->{'upload-recipient'}) {
54 print STDERR "$program: missing required --recipient (or --upload-recipient) parameter\n";
55 exit 1;
56 }
57 my $upload_recipients = $opts->{recipient};
58
59 # The --upload-recipient list takes precedence over the (deprecated)
60 # --recipient list.
61 if (defined($opts->{'upload-recipient'})) {
62 $upload_recipients = $opts->{'upload-recipient'};
63 }
64
65 my $download_recipients = undef;
66 if (defined($opts->{'download-recipient'})) {
67 $download_recipients = $opts->{'download-recipient'};
68 }
69
70 unless ($opts->{'smtp-server'}) {
71 print STDERR "$program: missing required --smtp-server parameter\n";
72 exit 1;
73 }
74 my $smtp_server = $opts->{'smtp-server'};
75
76 my $smtp_auth;
77 if ($opts->{'auth'}) {
78 eval { $smtp_auth = get_auth_info($opts->{'auth'}) };
79 if ($@) {
80 my $ex = $@;
81 print STDERR "$program: unable to obtain SMTP auth info: $ex\n";
82 exit 1;
83 }
84 }
85
86 my $delay = 0.5;
87 if ($opts->{sleep}) {
88 $delay = $opts->{sleep};
89 }
90
91 my $fifoh;
92 if (open($fifoh, "< $fifo")) {
93
94 while (1) {
95 my $line = <$fifoh>;
96 if ($line) {
97 chomp($line);
98
99 if ($line =~ /^(\S+\s+\S+\s+\d+\s+\d+:\d+:\d+\s+\d+)\s+(\d+)\s+(.*?)\s+(\d+)\s+(.*?)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*?)\s+.*?(\S+)$/o) {
100 my $curr_time = $1;
101 my $xfer_nsecs = $2;
102 my $client = $3;
103 my $nbytes = $4;
104
105 # Note that any spaces or control characters will be replaced in this
106 # path with underscores. This can make finding the actual file, as for
107 # attachments, rather difficult; we have to test to find the difference
108 # between a real underscore in the name, and a substituted underscore.
109 my $path = $5;
110
111 unless (-e $path) {
112 # Perform a quick-and-dirty check, on the assumption that all of the
113 # underscores in the given path are actually spaces. If a
114 # combination of underscores and spaces appears in the real file,
115 # we won't detect that here.
116
117 my $alt_path = $path;
118 $alt_path =~ s/_/ /g;
119
120 if (-e $alt_path) {
121 $path = $alt_path;
122 }
123 }
124
125 my $xfer_type = $6;
126 my $action_flag = $7;
127 my $xfer_direction = $8;
128 my $access_mode = $9;
129 my $user_name = $10;
130 my $completion_status = $11;
131
132 my $send_email = 0;
133
134 if ($xfer_direction eq 'i') {
135 $send_email = 1;
136 }
137
138 if (defined($download_recipients)) {
139 # If we have a list of download email recipients, it means we should
140 # send emails for downloads, too.
141 if ($xfer_direction eq 'o') {
142 $send_email = 1;
143 }
144 }
145
146 if ($send_email) {
147
148 # First, check for any specific --watch-users filter. If configured,
149 # and if the user name does NOT match the --watch-users filter, then
150 # don't send email. Otherwise, check for an --ignore-users filter,
151 # and see if the user matches that ignore filter.
152
153 if ($opts->{'watch-users'}) {
154 if ($user_name !~ /$opts->{'watch-users'}/) {
155 $send_email = 0;
156 }
157
158 } elsif ($opts->{'ignore-users'}) {
159 if ($user_name =~ /$opts->{'ignore-users'}/) {
160 $send_email = 0;
161 }
162 }
163 }
164
165 if ($send_email) {
166 send_email({
167 timestamp => $curr_time,
168 duration => $xfer_nsecs,
169 client => $client,
170 size => $nbytes,
171 file => $path,
172 transfer_type => $xfer_type,
173 auth_mode => $access_mode,
174 user => $user_name,
175 status => $completion_status,
176 direction => $xfer_direction,
177 });
178 }
179 }
180
181 if ($opts->{log}) {
182 # Note: since this opens, writes, then closes the log file for every
183 # write, it will interact with log rotation scripts MUCH better than
184 # proftpd by itself. Just one of the small benefits.
185
186 my $log_file = $opts->{log};
187 my $logfh;
188
189 if (open($logfh, ">> $log_file")) {
190 print $logfh "$line\n";
191
192 unless (close($logfh)) {
193 print STDERR "$program: error writing to log file '$log_file': $!\n";
194 }
195
196 } else {
197 print STDERR "$program: error opening log file '$log_file': $!\n";
198 }
199 }
200
201 } else {
202 # No input at this time. Sleep for half a second (or less) and check
203 # again.
204 usleep($delay * 1000000);
205 }
206 }
207
208 close($fifoh);
209
210 } else {
211 die "$program: unable to read FIFO '$fifo': $!\n";
212 }
213
214 sub get_auth_info {
215 my $path = shift;
216
217 my $info = {};
218
219 if (open(my $fh, "< $path")) {
220 while (my $line = <$fh>) {
221 chomp($line);
222
223 # Skip comments and blank lines
224 if ($line =~ /^(\s+)?#/) {
225 next;
226 }
227
228 if ($line =~ /^\s+$/) {
229 next;
230 }
231
232 if ($line =~ /^(\s+)?(\S+)(\s+)?=(\s+)?(.*)$/) {
233 my $key = $2;
234 my $val = $5;
235
236 # Trim off comments after the value, if any
237 $val =~ s/(\s*#.*)?$//;
238
239 # Ignore any keys other than 'user' and 'password'.
240
241 if (lc($key) eq 'user') {
242 $info->{'user'} = $val;
243
244 } elsif (lc($key) eq 'password' ||
245 lc($key) eq 'pass') {
246 $info->{'password'} = $val;
247 }
248 }
249 }
250
251 close($fh);
252
253 } else {
254 die("Can't read '$path': $!\n");
255 }
256
257 # Make sure that we have the required values
258
259 my $reqs = [qw(user password)];
260
261 foreach my $req (@$reqs) {
262 unless (exists($info->{$req})) {
263 die("Missing required '$req' value\n");
264 }
265 }
266
267 return $info;
268 }
269
270 sub send_email {
271 my $transfer_info = shift;
272
273 my $file = $transfer_info->{file};
274 my $file_str = basename($file);
275
276 my $transferred = 'uploaded';
277 if ($transfer_info->{direction} eq 'o') {
278 $transferred = 'downloaded';
279 }
280
281 my $subject = "User '$transfer_info->{user}' $transferred file '$file_str' via FTP";
282 if ($opts->{subject}) {
283 $subject = $opts->{subject};
284 }
285
286 my $bytes_str = "bytes";
287 if ($transfer_info->{size} == 1) {
288 $bytes_str = "byte";
289 }
290
291 my $status = "Completed";
292 if ($transfer_info->{status} eq 'i') {
293 $status = "Incomplete";
294 }
295
296 my $secs_str = "secs";
297 if ($transfer_info->{duration} == 1) {
298 $secs_str = "sec";
299 }
300
301 my $type_str = "Binary";
302 if ($transfer_info->{transfer_type} eq 'a') {
303 $type_str = "ASCII";
304 }
305
306 my $attached = "";
307 if ($opts->{'attach-file'} &&
308 -e $file) {
309 $attached = "(attached)";
310 }
311
312 my $text = <<EOT;
313 File just $transferred via FTP:
314
315 User: $transfer_info->{user}
316 Client: $transfer_info->{client}
317
318 File: $file $attached
319 Size: $transfer_info->{size} $bytes_str
320 At: $transfer_info->{timestamp}
321 Duration: $transfer_info->{duration} $secs_str
322 Status: $status
323 Transfer type: $type_str
324
325 Cheers,
326 --$program
327
328 EOT
329
330 my $email_info = {
331 smtp => $smtp_server,
332 From => $from,
333 Subject => $subject,
334 };
335
336 if ($transfer_info->{direction} eq 'i') {
337 $email_info->{To} = join(', ', @$upload_recipients);
338
339 } elsif ($transfer_info->{direction} eq 'o') {
340 $email_info->{To} = join(', ', @$download_recipients);
341 }
342
343 if ($opts->{'auth'}) {
344 $email_info->{'auth'} = $smtp_auth;
345 }
346
347 if ($opts->{'attach-file'}) {
348 if (-e $file) {
349 $email_info->{'MIME-Version'} = '1.0';
350
351 my $boundary = '====' . time() . '====';
352 $email_info->{'Content-Type'} = "multipart/mixed; boundary=\"$boundary\"";
353 $boundary = '--' . $boundary;
354
355 $email_info->{Body} .= "$boundary\n";
356 $email_info->{Body} .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
357 $email_info->{Body} .= "Content-Transfer-Encoding: quoted-printable\n\n";
358 $email_info->{Body} .= "$text\n";
359
360 if (open(my $fh, "< $file")) {
361 binmode($fh);
362
363 # Note: this reads the entire file into memory, and can fail if
364 # the file is too big.
365
366 local $/;
367 my $attach;
368 while (my $data = <$fh>) {
369 $attach .= $data;
370 }
371 close($fh);
372
373 $email_info->{Body} .= "$boundary\n";
374
375 $email_info->{Body} .= "Content-Disposition: attachment; filename=\"$file\"\n";
376 if ($transfer_info->{transfer_type} eq 'a') {
377 $email_info->{Body} .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n\n";
378 $email_info->{Body} .= $attach;
379
380 } else {
381 $email_info->{Body} .= "Content-Type: application/octet-stream\n";
382 $email_info->{Body} .= "Content-Transfer-Encoding: base64\n\n";
383 $email_info->{Body} .= encode_base64($attach);
384 }
385
386 $email_info->{Body} .= "\n";
387
388 } else {
389 my $timestamp = scalar(localtime());
390 print STDERR "$program: $timestamp: error reading file '$file' for attaching: $!\n";
391 }
392
393 } else {
394 # Couldn't find/access the uploaded file on the filesystem. This usually
395 # indicates either a permissions problem, or a munged filename.
396 #
397 # XXX Need to handle this better.
398 }
399
400 } else {
401 $email_info->{Body} = $text;
402 }
403
404 my $res = Mail::Sendmail::sendmail(%$email_info);
405 unless ($res) {
406 my $timestamp = scalar(localtime());
407
408 print STDERR "$program: $timestamp: error sending email: $Mail::Sendmail::error\n";
409 }
410 }
411
412 sub usage {
413 print <<EOH;
414
415 usage: $program [--help] [--fifo \$path] [--from \$addr] [--log \$path]
416 [--recipient \$addrs] [--upload-recipient \$addrs]
417 [--download-recipient \$addrs] [--subject \$string] [--smtp-server \$addr]
418 [--attach-file] [--ignore-users \$regex | --watch-users \$regex]
419
420 The purpose of this script is to monitor the TransferLog written by proftpd
421 for uploaded files. Whenever a file is uploaded by a user, an email will be
422 sent to the specified recipients. In the email there will be the timestamp,
423 the name of the user who uploaded the file, the path to the uploaded file, the
424 size of the uploaded file, and the time it took to upload.
425
426 Command-line options:
427
428 --attach-file If used, this will cause a copy of the uploaded file
429 to be included, as an attachment, in the generated
430 email.
431
432 --auth \$path Configures the path to a file containing SMTP
433 authentication information.
434
435 The configured file should look like this:
436
437 user = \$user
438 password = \$password
439
440 --fifo \$path Indicates the path to the FIFO to which proftpd is
441 writing its TransferLog. That is, this is the path
442 that you used for the TransferLog directive in your
443 proftpd.conf. This parameter is REQUIRED.
444
445 --from \$addr Specifies the email address to use in the From header.
446 This parameter is REQUIRED.
447
448 --help Displays this message.
449
450 --ignore-users \$regex
451 Specifies a Perl regular expression. If the uploading
452 user name matches this regular expression, then NO
453 email notification is sent; otherwise, an email is
454 sent.
455
456 --log \$path Since this script reads the TransferLog using FIFOs,
457 the actual TransferLog file is not written by default.
458 Use this option to write the normal TransferLog file,
459 in addition to watching for uploads.
460
461 --recipient \$addr Specifies an email address to which to send an email
462 notification of the upload. This option can be
463 used multiple times to specify multiple recipients.
464 AT LEAST ONE recipient is REQUIRED.
465
466 --upload-recipient Same as --recipient.
467
468 --download-recipient \$addr
469 Specifies an email address to which to send an email
470 notification of the B<download>. This option can be
471 used multiple times to specify multiple recipients.
472
473 If this option is specified, then C<ftpmail> will
474 watch for FTP downloads as well as uploads.
475
476 --smtp-server \$addr Specifies the SMTP server to which to send the email.
477 This parameter is REQUIRED.
478
479 --subject \$string Specify a custom Subject header for the email sent.
480 The default Subject is:
481
482 User '\$user' uploaded file '\$file' via FTP
483
484 --watch-users \$regex Specifies a Perl regular expression. If the uploading
485 user name matches this regular expression, then an
486 email notification is sent; otherwise, no email is
487 sent.
488
489 EOH
490 }