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
|
#!/usr/bin/perl
use strict;
use warnings;
use utf8;
use Time::Piece;
use Sys::Syslog qw(:standard :macros);
use Socket qw(AF_UNIX SOCK_STREAM PF_UNSPEC);
use OpenBSD::Pledge;
use OpenBSD::Unveil;
my $dict_dir = '/var/www/var/lex/dict';
my $state_file = '/var/www/var/lex/mailer.tsv';
my $to = 'me@example.com';
my $from = 'lex@example.com';
my $from_header = "Lex <$from>";
my $subject = 'Daily word';
my $sendmail = '/usr/sbin/sendmail';
my $syslog_tag = 'lex-mail';
my $max_interval = 365; # Upper bound limit (1 year)
my $timeout_sec = 30; # Execution timeout for child/sendmail
# Connect to syslog before pledge/unveil
openlog($syslog_tag, 'ndelay,pid', LOG_MAIL);
sub log_die {
my ($msg) = @_;
syslog(LOG_ERR, "%s", $msg);
closelog();
die $msg;
}
# Socket pair for parent/child IPC
socketpair(my $parent_sock, my $child_sock, AF_UNIX, SOCK_STREAM, PF_UNSPEC)
or log_die("socketpair failed: $!");
my $pid = fork();
log_die("fork failed: $!") unless defined $pid;
if ($pid == 0) {
# Child process for handling mail pipe
close($parent_sock);
# 'exec' no longer exposed to parent proc
pledge(qw(stdio proc exec)) or die "child pledge failed";
# Read email message from socket
my $raw_email;
{
local $/;
$raw_email = <$child_sock>;
}
close($child_sock);
if (!$raw_email) {
exit 0; # Parent aborted or sent no mail
}
open(my $mail_pipe, '|-', $sendmail, '-i', '-f', $from, $to)
or die "child failed to exec $sendmail: $!";
binmode($mail_pipe, ':utf8');
print $mail_pipe $raw_email;
if (!close($mail_pipe)) {
my $status = $?;
my $exit_val = $status >> 8;
my $sig_num = $status & 127;
if ($sig_num) {
die "sendmail killed by signal $sig_num";
}
die "sendmail exited with status $exit_val";
}
exit 0;
}
# Parent process: spaced-repetition + fair scheduling
close($child_sock);
unveil($dict_dir, 'r') or log_die("unveil $dict_dir: $!");
unveil($state_file, 'rwc') or log_die("unveil $state_file: $!");
unveil('/dev/log', 'w') or log_die("unveil /dev/log: $!");
unveil(); # Lock unveil rules
# Main process drops 'exec'
pledge(qw(stdio rpath wpath cpath proc)) or log_die("parent pledge: $!");
# Read dictionary files
my $dh;
if (!opendir($dh, $dict_dir)) {
log_die("Cannot open $dict_dir: $!");
}
my @current_files = grep { -f "$dict_dir/$_" && !/^\./ } readdir($dh);
closedir($dh);
if (!@current_files) {
syslog(LOG_WARNING, "No files found in %s", $dict_dir);
if (-f $state_file) {
if (open(my $clear_fh, '>', $state_file)) {
close($clear_fh);
} else {
syslog(LOG_ERR, "Failed to clear %s: %s", $state_file, $!);
}
}
close($parent_sock);
waitpid($pid, 0);
closelog();
exit 0;
}
my %active_files = map { $_ => 1 } @current_files;
my %state;
my $today = localtime->ymd;
if (-f $state_file) {
my $sfh;
if (!open($sfh, '<', $state_file)) {
log_die("Cannot open $state_file: $!");
}
while (my $line = <$sfh>) {
chomp $line;
next if $line =~ /^\s*$/;
my ($file, $next_due, $interval, $reviews, $factor) = split(/\t/, $line);
if ($file && $active_files{$file}) {
$state{$file} = {
next_due => $next_due // $today,
interval => $interval // 1,
reviews => $reviews // 0,
factor => $factor // 2.5,
};
}
}
close($sfh);
}
# Initialize new files
foreach my $file (@current_files) {
if (!$state{$file}) {
$state{$file} = {
next_due => $today,
interval => 1,
reviews => 0,
factor => 2.5,
};
}
}
# Candidate selection (spaced repetition + fair scheduling)
my @due_files = grep { $state{$_}{next_due} le $today } @current_files;
my $selected_file;
if (@due_files == 1) {
$selected_file = $due_files[0];
} elsif (@due_files > 1) {
my %weights;
my $total_weight = 0;
foreach my $file (@due_files) {
my $w = 1.0 / ($state{$file}{reviews} + 1);
$weights{$file} = $w;
$total_weight += $w;
}
# Weighted random selection (roulette wheel algorithm)
# Higher weight = larger target segment = higher probability of selection
my $rand_point = rand($total_weight);
my $accum = 0;
foreach my $file (@due_files) {
$accum += $weights{$file};
if ($rand_point <= $accum) {
$selected_file = $file;
last;
}
}
# Guard against IEEE 754 floating-point rounding edge cases at boundary
$selected_file //= $due_files[-1];
} else {
@current_files = sort { $state{$a}{next_due} cmp $state{$b}{next_due} } @current_files;
$selected_file = $current_files[0];
syslog(LOG_INFO, "No files due today; falling back to nearest due file: %s", $selected_file);
}
# Read candidate file content
my $file_path = "$dict_dir/$selected_file";
my $fh;
if (!open($fh, '<:utf8', $file_path)) {
log_die("Cannot open $file_path: $!");
}
my $body;
{
local $/; # slurp mode
$body = <$fh>;
}
close($fh);
# Construct payload and send to helper process over socket
my $email_data = "From: $from_header\n"
. "To: $to\n"
. "Subject: $subject - $selected_file\n"
. "Content-Type: text/plain; charset=UTF-8\n\n"
. $body;
binmode($parent_sock, ':utf8');
print $parent_sock $email_data;
close($parent_sock);
# Wait for child execution to complete
eval {
local $SIG{ALRM} = sub { die "TIMEOUT\n" };
alarm($timeout_sec);
waitpid($pid, 0);
alarm(0);
};
if ($@) {
if ($@ eq "TIMEOUT\n") {
kill('KILL', $pid);
log_die("Mailer child process timed out after ${timeout_sec}s");
} else {
log_die("Error waiting for mailer child process: $@");
}
}
if ($? != 0) {
my $status = $?;
my $exit_val = $status >> 8;
my $sig_num = $status & 127;
if ($sig_num) {
log_die("Mailer child process killed by signal $sig_num");
} else {
log_die("Mailer child process exited with status $exit_val");
}
}
# Update schedule state
my $item = $state{$selected_file};
my $interval = $item->{interval};
my $factor = $item->{factor};
if ($item->{reviews} == 0) {
$interval = 1;
} elsif ($item->{reviews} == 1) {
$interval = 6;
} else {
$interval = int($interval * $factor);
}
if ($interval > $max_interval) {
$interval = $max_interval;
}
$item->{interval} = $interval;
$item->{reviews} += 1;
my $now = localtime;
$item->{next_due} = ($now + ($interval * 86400))->ymd;
# Cleanup deleted items
foreach my $file (keys %state) {
delete $state{$file} unless $active_files{$file};
}
# Atomic write update
my $tmp_file = "$state_file.tmp";
my $out_fh;
if (!open($out_fh, '>', $tmp_file)) {
log_die("Cannot write to $tmp_file: $!");
}
foreach my $file (keys %state) {
my $i = $state{$file};
print $out_fh join("\t", $file, $i->{next_due}, $i->{interval}, $i->{reviews}, $i->{factor}), "\n";
}
close($out_fh) or log_die("Error closing $tmp_file: $!");
if (!rename($tmp_file, $state_file)) {
log_die("Cannot atomic swap $tmp_file to $state_file: $!");
}
syslog(LOG_INFO, "Mailed %s to %s (next due: %s)", $selected_file, $to, $item->{next_due});
closelog();
|