-
Notifications
You must be signed in to change notification settings - Fork 0
/
slgw
executable file
·407 lines (349 loc) · 11.8 KB
/
slgw
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
#!/usr/bin/perl
# vi:set sw=2 ai sm:
#
=encoding UTF-8
=head1 Name
slgw – sysline gateway
=cut
# Copyright ©2020, 2021, 2024 by Ambrose Li <ambrose.li@gmail.com>
use strict;
use integer;
# see https://stackoverflow.com/questions/6162484/why-does-modern-perl-avoid-utf-8-by-default for these crazy hacks
# THERE ARE MORE CRAZY HACKS THERE FOR MORE COMPLEX PROJECTS!!
#use v5.14; # //u modifier
use utf8;
use open qw( :encoding(UTF-8) :std );
use charnames qw( :full :short );
use feature "unicode_strings";
use POSIX;
use Fcntl qw(:flock);
use Time::HiRes;
use Getopt::Long qw(:config no_auto_abbrev bundling no_ignore_case);
use Data::Dumper;
use vars qw( $t0 );
use vars qw( $debug_p );
use vars qw( $force_log_p );
use vars qw( $dry_run_p );
use vars qw( $test_p );
use vars qw( $n $n_headers $n_header_lines $n_body_lines );
use vars qw( $dotlockfile_path );
use vars qw( $multilog_path );
use vars qw( $multilog_pid );
use vars qw( $output_path );
use vars qw( $queue_path );
use vars qw( $logdir $log_path );
use vars qw( $abend_reason );
use vars qw( $prefer_cr_hack_p );
$prefer_cr_hack_p = 1;
GetOptions(
'debug|d' => \$debug_p,
'dry-run|n' => \$dry_run_p,
'force-log' => \$force_log_p,
'test|t' => \$test_p,
'help' => \&show_usage_then_exit,
) || exit(1);
# Mutt uses this, this is probably part of mutt?
$dotlockfile_path = '/usr/bin/dotlockfile';
# don't use multilog, it can hang even if we killed it
if (0) {
# try to use multilog if it's available
$multilog_path = '/command/multilog'; # standard location
$multilog_path = '/usr/bin/multilog' if !-f $multilog_path; # Ubuntu standard location
undef $multilog_path unless -f $multilog_path;
}
# determine log locations. Note that if multilog is used
# we'll have to use a subdirectory to prevent multilog from blocking
# This is not ideal but there's no way around it
$logdir = $test_p? 'debug': -d "$ENV{HOME}/.debug"? "$ENV{HOME}/.debug/stupidweasel": "$ENV{HOME}/.cache/stupidweasel";
$log_path = "$logdir/log";
$output_path = $test_p? "$logdir/slgw.out": "/var/mail/$ENV{USER}";
$queue_path = $test_p? "$logdir/slgw.postponed": "$logdir/queue";
if (defined $multilog_path) {
my $suffix = sprintf('/%010d-%05d', $t0, $$);
$logdir .= $suffix;
}
# ZMailer style log output so that we don't get completely lost looking at the log file
sub zlog ($$) {
my($s, $type) = @_;
$s =~ s/\n+$//s;
printf STDERR "%010d-%05d%1.1s\t%s\n", time, $$, $type, $s;
STDERR->flush;
}
sub log_input ($) {
my($s) = @_;
zlog $s, '<';
}
sub log_output ($) {
my($s) = @_;
zlog $s, '>';
}
sub log_info ($) {
my($s) = @_;
zlog $s, '#';
}
# die handler copied from the organizer project
sub set_die_handler () {
$SIG{__DIE__} = sub {
my($sig) = @_;
die $sig if $^S;
if (defined $ARGV && $ARGV) {
log_info "\nARGV=($ARGV):$.";
}
# Go through the call stack backwards so that the offending line would appear right above the error message
my @msg;
for (my $i = 0; caller $i; $i += 1) {
unshift @msg, sprintf "%d: %s", $i, join(' ', caller $i);
}
push @msg, $sig;
for (my $i = 0; $i < @msg; $i += 1) {
log_info sprintf "%s%s\n", (' ' x ($_ == $#msg? $_ - 1: $_));
}
exit(2);
};
}
sub send_to_mbox_file (;*$) {
my($h, $label) = @_;
my($headers, $from);
my($encoding, $qp_p);
my($type, $multipart_p);
($h, $label) = (*STDIN, '(stdin)') unless defined $h;
my $mbox_input_p = 0;
for (;;) {
my $s = scalar <$h>;
last unless defined $s;
if (!defined $n) {
log_input $s;
if ($s =~ /^(From ).*?<(.*?)>(.*)$/s) { # From full name <email> date - probably only in saved mboxes
$s = $1 . $2 . $3;
$mbox_input_p = 1;
log_info 'mbox format detected, trying to fix invalid From_ header';
log_output $s;
} elsif ($s =~ /^From /s) {
$mbox_input_p = 1;
log_info 'mbox format detected';
}
} elsif ($debug_p > 2 || (defined $multilog_path && $debug_p > 1)) { # always log headers if multilog is used
log_input $s;
}
$headers .= $s;
last if $s eq "\n";
if ($s =~ /^From:.*<([^<>\s]*)>/si) {
$from = $1;
} elsif ($s =~ /^From:\s*(\S+)\s*$/si) {
$from = $1;
} elsif ($s =~ /^From:\s*(.*)\s*$/si) {
$from = $1;
$from =~ s/\([^\(\)]*?\)//sg;
$from =~ s/^\s+//s;
$from =~ s/\s+$//s;
$from = $1 if $from =~ /\s/ && $from =~ /([^\s\@]+\@[^\s\@]+)/; # XXX
} elsif ($s =~ /^Content-Type:\s*([^\s;]+)/is) {
$type = lc $1;
$multipart_p = $type =~ /^multipart\//;
log_info "Content-Type detected, type is $type\n" if $debug_p;
} elsif ($s =~ /^Content-Transfer-Encoding:\s*([^\s;]+)/is) {
$encoding = lc $1;
$qp_p = $encoding eq 'quoted-printable';
log_info "Content-Transfer-Encoding detected, encoding is $encoding\n" if $debug_p;
}
$n_headers += 1 if ($n > 0 || !$mbox_input_p) && $s !~ /^\s/s;
$n += 1;
}
if ($n) {
$n_header_lines = $n;
if ($mbox_input_p) {
;
} else {
if (defined $from && $from =~ /\@/ && $from !~ /\s/) {
log_info "Using ($from) for From_ header\n" if $debug_p;
} else {
$from = 'MAILER-DAEMON';
log_info "No From line seen, using ($from) for From_ header\n" if $debug_p;
}
print OUTPUT sprintf("From %s %s\n", $from, scalar gmtime) unless $dry_run_p;
}
print OUTPUT $headers unless $dry_run_p;
for (;;) {
my $s = scalar <$h>;
last unless defined $s;
$s = "$1$2" if $s =~ /^(.*?)\r(\n)$/s; # apparently Evolution adds \r to literally every single line, but only in the body
if ($s =~ /^From /s) {
log_info "Bare \"From \" in message body, trying to work around\n" if $debug_p;
if ($qp_p) {
$s =~ s/^F/=46/s;
} elsif ($multipart_p) { # do nothing if multipart, on the assumption that mail cannot terminate before the final MIME boundary
;
} elsif ($prefer_cr_hack_p) {
$s = "$1\r$2" if $s =~ /^(.*?[^\r])(\n)$/s; # re-insert \r on the assumption headers cannot end in \r\n
} else {
$s =~ s/^/>/s;
}
}
print OUTPUT $s unless $dry_run_p;
$n_body_lines += 1;
$n += 1;
}
}
print OUTPUT "\n" if $n; # doesn't matter for sysline; needed to keep the file actual mbox format
log_info sprintf "%d line(s) (%s%d header, %d body) [%d headers] read from $label\n", $n, ($mbox_input_p? '1 From_, ': ''), $n_header_lines, $n_body_lines, $n_headers, $label if $debug_p;
}
sub run_cmd (@) {
my(@cmd) = @_;
my $st = system { $cmd[0] } @cmd;
return $st;
}
sub acquire_lock ($) {
my($mbox_path) = @_;
my $lockfile_path = "$mbox_path.lock";
die "$lockfile_path: Invalid lock file name\n" unless $lockfile_path =~ /\.lock$/;
my @cmd = ($dotlockfile_path, '-p', $lockfile_path);
log_info "Attempting to acquire lock $lockfile_path" if $debug_p > 1;
my $it = -f $dotlockfile_path && 0 == run_cmd @cmd;
log_info($it? 'Lock acquired': 'Failed to acquire lock') if $debug_p > 1;
return $it;
}
sub release_lock ($) {
my($mbox_path) = @_;
my $lockfile_path = "$mbox_path.lock";
die "$lockfile_path: Invalid lock file name\n" unless $lockfile_path =~ /\.lock$/;
my @cmd = ($dotlockfile_path, '-u', $lockfile_path);
log_info 'Attempting to release lock' if $debug_p > 1;
my $it = -f $dotlockfile_path && 0 == run_cmd @cmd;
log_info($it? 'Lock released': 'Failed to release lock') if $debug_p > 1;
return $it;
}
sub send_to_queue () {
run_cmd ('mkdir', '-p', $queue_path);
my $id = sprintf('%ld-%d', time, $$);
my $output_path = "$queue_path/$id";
log_info "Attempting to queue mail to $output_path" if $debug_p > 1;
open(OUTPUT, '>', $output_path) or die "$output_path: $!\n";
for (;;) {
my $s = scalar <>;
last unless defined $s;
print OUTPUT;
}
close OUTPUT;
log_info "Queue file closed" if $debug_p > 1;
}
sub prepare_for_logging () {
run_cmd ('mkdir', '-p', $logdir);
if ($force_log_p || !$test_p) {
my $log_opened_p = 0;
if (defined $multilog_path) {
my @cmd = ($multilog_path, 't', '.');
$multilog_pid = open(LOG, '|-');
if (!defined $multilog_pid) { # pipe failed
;
} elsif (!$multilog_pid) {
chdir $logdir || die "$logdir: chdir: $!\n";
exec { $cmd[0] } @cmd;
die "$cmd[0]: exec: $!\n";
} elsif ($multilog_pid) {
binmode LOG, ':utf8';
$log_opened_p = 1;
}
}
if (!$log_opened_p && open(LOG, '>>:utf8', $log_path)) {
$log_opened_p = 1;
}
if ($log_opened_p) {
POSIX::dup2(fileno(LOG), 2); # make stderr same as log file
STDERR->autoflush(1);
$debug_p = 2;
}
}
}
sub show_usage_then_exit (;$) {
my($st) = @_;
my $h = $st? *STDERR: *STDOUT;
print $h <<EOF;
Usage: slgw [OPTION]...
Send input to mailbox so that sysline knows mail has arrived.
-d, --debug show debugging messages
-n, --dry-run do not do anything useful
--force-log force logging even in --test mode
-t, --test use debug directory; do not touch real mailbox and real logs
--help display this help and exit
slgw normally runs as a filter in Evolution.
EOF
exit $st;
}
BEGIN {
$t0 = Time::HiRes::time;
}
END {
no integer;
my $msg = defined $abend_reason? sprintf('ABEND: slgw abended due to %s', $abend_reason): 'slgw terminated normally';
$msg .= sprintf ' at %s', POSIX::strftime('%Y-%m-%d %H:%M:%S %z', localtime);
$msg .= sprintf "; run time was %g seconds", Time::HiRes::time - $t0;
log_info $msg;
STDERR->flush; # just in case
kill 'TERM', $multilog_pid if defined $multilog_pid; # must kill multilog via kill or exit, or we'll hang
}
### MAIN CODE STARTS HERE
prepare_for_logging;
set_die_handler;
$SIG{'TERM'} = sub {
my($sig) = @_;
$abend_reason = "SIG$sig";
release_lock($output_path) if -f $output_path;
exit(3);
};
$SIG{'HUP'} = $SIG{'TERM'};
log_info sprintf "slgw started at %s in directory (%s) with arguments [%s]\n",
POSIX::strftime('%Y-%m-%d %H:%M:%S %z', localtime),
POSIX::getcwd,
join(' ', map { sprintf '(%s)', s/([\(\)\\])/\\\1/sgr } @ARGV);
if (open(OUTPUT, '>>', $output_path) && acquire_lock($output_path)) {
send_to_mbox_file;
release_lock($output_path);
} else {
log_info "$output_path: $!\n";
send_to_queue;
$abend_reason = 'message postponement';
exit(1);
}
### CODE ENDS HERE
__END__
=head1 Synopsis
B<slgw> [B<-d>] [B<-n>] [B<-t>]
=head1 Description
F<slgw> uses Evolution’s filter feature to simulate mail delivery to a local mailbox,
so that L<sysline(1)>’s mail notification features can function on a system with no functional L<sendmail(8)>.
F<slgw> reads a maildir-format mail (the format used by Evolution) from standard input
and appends an equivalent mbox-format mail to an output file,
normally /var/mail/I<$USER>,
the per-user local mailbox.
Because the mbox format has trouble with lines starting with “From ”,
F<slgw> tries to compensate either by changing the F to =46
or inserting a > sign before the F.
The latter workaround is not done if the mail it receives
is a multipart mail.
=head1 Options
=over
=item -d, --debug
Debug mode. Displays debugging messages on standard error.
=item -n, --dry-run
Dry-run mode. Do not actually do anything meaningful. You don’t want this; you want --test instead.
=item --force-log
Force logging even in --test mode. This is used for debugging the logging code.
=item -t, --test
Test mode. Changes output file to debug/slgw.out and postponed directory to debug/slgw.postponed.
=back
=head1 Bugs
Sometimes you’ll get email from MAILER-DAEMON
with a Subject: No Subject and no contents.
This appears to be an Evolution bug;
the only thing you can do is to
save a copy of the missed message
and manually pipe it through F<slgw>.
If you run another filter in addition to this one,
sometimes F<slgw> will get stuck on the other filter.
=head1 See also
L<dotlockfile(1)>,
L<stupidweasel(1)>,
L<sysline(1)>
=head1 Reporting bugs
Please report bugs through L<Github|https://github.com/acli/stupidweasel/issues>.
=cut