Debian Codegraph @

contrib/hashcash-sendmail

raw
1 #!/usr/bin/perl
2
3 my $RCS = '$Id: hashcash-sendmail,v 1.18 2004/08/07 18:36:16 kyle Exp $';
4
5 #
6 # hashcash-sendmail -- queues messages for later delivery after adding hashcash
7 # This is meant to be a program called AS sendmail from a MUA.
8 #
9 # An up-to-date version is normally here:
10 # http://www.toehold.com/~kyle/hashcash/
11 #
12
13 # Consider this ALPHA software. It works for me, but it has not been through
14 # much real testing.
15
16 #
17 # Copyright (C) 2004 Kyle Hasselbacher <[email protected]>
18 #
19 # This program is free software; you can redistribute it and/or modify it
20 # under the terms of the GNU General Public License as published by the
21 # Free Software Foundation; either version 2 of the License, or (at your
22 # option) any later version.
23 #
24 # This program is distributed in the hope that it will be useful, but
25 # WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
27 # Public License for more details.
28 #
29 # You should have received a copy of the GNU General Public License along
30 # with this program; if not, write to the Free Software Foundation, Inc.,
31 # 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 #
33
34 #
35 # This script is supposed to be a stand-in for sendmail. It records the
36 # arguments its given and the standard input it receives, and those are
37 # eventually passed on to sendmail. Typically the arguments are passed
38 # faithfully to sendmail, but we meddle with them if there's a Bcc. The
39 # message is always modified by adding X-Hashcash to the end of the headers.
40 #
41
42 use strict;
43 use Data::Dumper;
44 use File::Copy;
45 use Fcntl qw(:DEFAULT :flock);
46 use POSIX qw( setsid );
47 use IO::File;
48 use vars qw( @rcpt @args );
49 use IPC::Open3;
50
51 my $home = $ENV{'HOME'} || $ENV{'LOGDIR'} || (getpwid($<))[7];
52
53 #
54 # The workdir is expected to have a queue directory and a tmp directory.
55 # hashcash-sendmail looks for bitconf there later.
56 # All messages that I haven't seen yet are in queue/*.msg files, and they
57 # each have a corresponding *.dat file with instructions. The .msg file
58 # is exactly the standard input for sendmail. The *.dat file is a Perl
59 # parsable file which contains two arrays. One is the exact argument list
60 # for sendmail. The other is instructions for what hashcash to add to the
61 # message. The .dat files never move from the queue, but the .msg files
62 # move to tmp/ when they're being worked on.
63 #
64 my $workdir = "$home/.hashcash";
65
66 END {
67 cleanup();
68 }
69
70 # When I get a signal, cleanup() is called twice. I use this flag to avoid
71 # doing anything the second time. It also serves to keep from doing cleanup
72 # if I die before even entering the queue.
73 my $need_cleanup = 0;
74
75 # Where to write log messages.
76 my $logfile = "$workdir/hashcash-log";
77
78 # Where to find the recipients file. See read_bitconf() comments for format.
79 my $conffile = "$workdir/bitconf";
80
81 # Create my directories if they're not there already.
82 foreach my $dir ( $workdir, "$workdir/queue", "$workdir/tmp" ) {
83 if ( ! -d $dir && ! mkdir( $dir ) ) {
84 die "Can't make nonexistant workdir '$dir': $!\n";
85 }
86 }
87
88 my @bitconf = read_bitconf();
89
90 # This is the number of bits we use if nothing else is specified.
91 my $bits_to_compute = 20;
92
93 # Part of the filename used for output.
94 my $filebase = time() . ".$$";
95
96 my $extra_expense = 0; # Whether this message is extra expensive (low priority)
97 my $confirmed = 0; # Whether this is a confirmed message (needing no cash)
98
99 # This is used for the Received: line I add to messages, and it gets logged
100 # by the daemon when it starts.
101 my $hostname = `hostname -f 2> /dev/null`;
102 $hostname =~ s/\s//g;
103
104 # If there are no args, read a request and queue that.
105 # hashcash-request just opens a pipe to hashcash-sendmail and ships
106 # in a Data::Dumper file.
107
108 if ( ! @ARGV ) {
109 my $rcptcode = join( '', <STDIN> );
110 eval $rcptcode;
111 if ( $@ ) {
112 fatal( "input request does not parse: $@\n" );
113 }
114 queue( $filebase, undef, \@rcpt, \@bitconf );
115 }
116 else {
117 my @args = @ARGV;
118
119 # This will be all the sendmail arguments BEFORE the list of envelope
120 # recipients (so that we can meddle with them later).
121 my @pre_args = ();
122
123 # Try to figure out our envelope recipients.
124 # This is probably NOT close enough to sendmail compatibility for prime time.
125 my @env_recip = ();
126
127 process_args( \@args, \@pre_args, \@env_recip );
128
129 my @to = (); # According-to-headers message recipients.
130
131 my $msgfh = new IO::File;
132 if ( ! open( $msgfh, ">$workdir/tmp/$filebase.msg" ) ) {
133 die "Can't write $workdir/tmp/$filebase.msg: $!\n";
134 }
135 else {
136 process_msg( $msgfh, \@to );
137 close( $msgfh );
138 }
139
140 queue_messages( \@args, \@env_recip, \@to, \@pre_args );
141
142 # Done with the temp file.
143 unlink( "$workdir/tmp/$filebase.msg" ) || die "Can't unlink '$workdir/tmp/$filebase.msg': $!\n";
144 }
145
146 ####
147 #### DAEMON STARTS HERE
148 ####
149
150 #
151 # At this point, the incoming message/request has been queued. We're about
152 # to fork away from the caller to work on processing the queue in the
153 # background. If there's already an earlier daemon doing this, we just
154 # send it a wake-up call and die.
155 #
156
157 # For now, at least, the daemon code and the sendmail code are distinct.
158 # They haven't needed to call the other's functions. That having been
159 # said, I haven't really marked which functions are which. If you're
160 # doing some work in here, make sure that the daemon calls fatal() and
161 # complain() rather than 'die' and 'warn'. There's nothing stopping
162 # sendmail from using those (and logline), but it hasn't yet.
163
164 use sigtrap qw( handler cleanup normal-signals );
165
166 #
167 # Ignore the USR1 signal for now. We toggle this on and off. When waiting
168 # for a token to finish, we set a handler that will process the interrupt
169 # (by rescanning the queue for a better job to do). When working (not
170 # waiting), we ignore the hangup.
171 #
172 $SIG{ USR1 } = 'IGNORE';
173
174 # Separate myself from the shell.
175 # It's important to do this before doing the pidfile stuff
176 # because daemonize() forks, and we want to get the right PID in the pidfile.
177 daemonize();
178
179 # $pidfile is where we store the daemon's process ID.
180 my $pidfile = "$workdir/daemon.pid";
181 handle_pidfile( $pidfile );
182
183 # Check for leftover queue items.
184 recover_dead_queue();
185
186 if ( $hostname =~ /\S/ ) {
187 logline( "daemon started on $hostname; computing $bits_to_compute bits" );
188 }
189 else {
190 logline( "daemon started; computing $bits_to_compute bits" );
191 }
192 logline( $RCS );
193
194 #
195 # This is our stack of tasks. Whatever we're working on right now is always
196 # at the end of this list. When we see something more important, we SIGSTOP
197 # the process and start a new one, adding the new task to the stack.
198 # Each element of the stack is a reference to a hash of stuff we need to
199 # retain. Its elements are:
200 #
201 # 'msg' -- the name of the file that has the message
202 # 'dat' -- the name of the job's .dat file
203 # 'sendmailfh' -- where I write the message
204 # 'sendmailpid' -- the sendmail PID
205 # 'msgfh' -- whence I read the message
206 # 'hashcashfh' -- whence I read a token
207 # 'hashcashpid' -- what to signal with STOP and CONT
208 # 'blankline' -- the line between the headers and the body
209 # 'cashinfo' -- a string describing the hashcash we're making
210 # It looks like 12:3456:[email protected] where the fields
211 # are bits:expiry:resource
212 #
213 my @stack = ();
214
215 # At this point we'll need to do a cleanup if we die.
216 $need_cleanup = 1;
217
218 # How many seconds to sleep when waiting.
219 my $sleep_time = 60 * 60;
220
221 # If this is true, we'll just process what's in the queue and then go away.
222 # The daemon won't wait around polling for something else to show up.
223 my $run_queue_and_die = 1;
224
225 while ( 1 ) {
226 # This looks for messages in the queue that we haven't processed yet.
227 opendir( QUEUE, "$workdir/queue" ) || fatal( "Can't opendir queue: $!\n" );
228 my @messages = sort prioritize grep( /\.(msg|req)$/, readdir( QUEUE ) );
229 closedir( QUEUE );
230
231 # Nothing to do. Look again in a while, or after an interrupt.
232 if ( ! @messages && ! @stack ) {
233 if ( $run_queue_and_die ) {
234 logline( "queue is empty; exiting." );
235 exit 0;
236 }
237 $SIG{ USR1 } = sub { logline( "awoke on $_[0]" ); die; };
238 eval {
239 sleep( $sleep_time );
240 };
241 $SIG{ USR1 } = 'IGNORE';
242 next;
243 }
244
245 if ( @messages ) {
246 # This is the most important message that's not being worked on.
247 my $msg = $messages[ 0 ];
248
249 if ( ! @stack ) {
250 # If there's nothing on the stack, we don't have to worry about
251 # priorities or stopping any current process. Just go to work.
252 begin_delivery( $msg, \@stack );
253 }
254 else {
255 my $topstate = $stack[ -1 ];
256
257 # First we check if the new message we found is more important
258 # than what we're working on right now.
259 my @check = ( $msg, $$topstate{ 'msg' } );
260 @check = sort prioritize @check;
261
262 if ( $check[ 0 ] eq $msg ) {
263 # The new best message is better than the previous.
264 # Stop the current job and push a new one on the stack.
265 interrupt_with( $msg, \@stack );
266 }
267 }
268 }
269
270 # The only way the stack is empty at this point is if we had nothing
271 # to work on and found a message with no recipients. In that case,
272 # it's already been delivered.
273 if ( @stack ) {
274 my $topstate = $stack[ -1 ];
275
276 # I'm doing this here because there's probably time. We're waiting
277 # on some token to mint. I'd do this when I'm about to exit, but I
278 # don't want to fool some baby daemon into thinking that I'm on the
279 # job when I'm not.
280 expire_premade();
281
282 # We're going to wait for a short time for the hascash process
283 # to be ready to read (i.e., it gave us our token). Once it
284 # does, we continue delivery. If it turns out delivery is
285 # finished, we pop the task off the stack and try to continue
286 # anything that's left.
287 my $rin = fhbits( $$topstate{ 'hashcashfh' } );
288 my $finished_token = 0; # If this stays zero, no token was finished.
289
290 $SIG{ USR1 } = sub { logline( "awoke on $_[0]" ); die; };
291 eval {
292 $finished_token = select( $rin, undef, undef, $sleep_time );
293 };
294 $SIG{ USR1 } = 'IGNORE';
295
296 if ( $finished_token && ! continue_delivery( $topstate ) ) {
297 # Delivery finished. Throw away the state
298 pop( @stack );
299
300 while ( @stack ) {
301 $topstate = $stack[ -1 ];
302 my $restart = $$topstate{ 'hashcashpid' };
303 logline( "continuing $$topstate{ 'msg' }" );
304
305 last if kill( 'CONT', $restart );
306
307 logline( "failed to restart $$topstate{ 'msg' } (pid $restart)" );
308 pop( @stack );
309 }
310 }
311 }
312 }
313
314 ####
315 #### SUBROUTINES START HERE
316 ####
317
318 #
319 # This converts a resource name to something that's appropriate to a filename.
320 # It's basically URL encoding with '-' instead of '%'. You can decode what
321 # the original resource was, but we never actually need to do that. This is
322 # just so I can find files that contain tokens for the resource I want.
323 #
324 sub res2file {
325 my ( $resource ) = @_;
326
327 my $filename = $resource;
328
329 $filename =~ s/(\W)/uc sprintf( "-%02x", ord( $1 ) )/eg;
330
331 return $filename;
332 }
333
334 #
335 # We know the addresses for the envelope (@env_recip),
336 # and the addresses listed in the headers (@to).
337 # For which do we compute hashcash? (@hash_to)
338 #
339 # This figures out what messages to queue and does the queueing. Though
340 # only one message was given, we may queue several, depending on Bccs.
341 #
342 sub queue_messages {
343 my ( $args, $env_recip, $to, $pre_args ) = @_;
344
345 my @hash_to = ();
346 if ( scalar @$env_recip == 1 ) {
347 # There's only one envelope recipient. That's who gets hashcash!
348 @hash_to = @$env_recip;
349 }
350 else {
351 # This looks for the intersection of envelope recipients and header
352 # recipients. An envelope recipient who's not listed in headers is
353 # a Bcc, and we don't want to leak that otherwise private info.
354 # A recipient in the headers who's not on the envelope isn't really
355 # getting the message, so there's no point wasting our time.
356 my %envelope_map = ();
357 foreach my $arg ( @$env_recip ) {
358 $arg =~ tr/A-Z/a-z/;
359 $envelope_map{ $arg }++;
360 }
361 foreach my $addr ( @$to ) {
362 my $flat = $addr;
363 $flat =~ tr/A-Z/a-z/;
364 if ( $envelope_map{ $flat } ) {
365 delete( $envelope_map{ $flat } );
366 push( @hash_to, $addr );
367 }
368 }
369 # Anything left here is a Bcc.
370 # We need to strip them out of the arguments list that we're about to
371 # write, and we need to queue separate messages for each of them.
372 # This is the only case where we change the argument list from what we
373 # got to something else.
374 if ( %envelope_map ) {
375 foreach my $bcc ( keys %envelope_map ) {
376 my $shortarg = [ @$pre_args, $bcc ];
377 queue( $filebase, $shortarg, [ msgrcpt( [ $bcc ] ) ], \@bitconf );
378 }
379 @$args = ( @$pre_args, @hash_to );
380 }
381 }
382
383 # This queues the "main" message.
384 # It's possible to send a message of all Bcc and no header recipients,
385 # in which case, everything's been queued already.
386 if ( @hash_to ) {
387 queue( $filebase, $args, [ msgrcpt( \@hash_to ) ], \@bitconf );
388 }
389 }
390
391 # Try to figure out my time zone.
392 sub time_zone {
393 my @lt = localtime();
394 my @gt = gmtime();
395
396 my $tz = $lt[ 2 ] - $gt[ 2 ];
397
398 if ( $gt[ 7 ] > $lt[ 7 ] || $gt[ 5 ] > $lt[ 5 ] ) {
399 $tz -= 24;
400 }
401 if ( $gt[ 7 ] < $lt[ 7 ] || $gt[ 5 ] < $lt[ 5 ] ) {
402 $tz += 24;
403 }
404
405 $tz .= "00";
406 $tz =~ s/^(-)?(\d)00$/${1}0${2}00/;
407 $tz =~ s/^(\d)/+$1/;
408
409 return $tz;
410 }
411
412 # RFC2821, section 4.4
413 sub add_trace_line {
414 my ( $msgfh ) = @_;
415
416 my $progname = $0;
417 $progname =~ s:^.*/([^/]+)$:$1:;
418
419 print $msgfh "Received: ";
420 print $msgfh "by $hostname " if ( $hostname =~ /\S/ );
421 print $msgfh "($progname, from uid $>);\n";
422
423 # Format this produces:
424 # Wed, 25 Feb 2004 16:37:30 -0600
425
426 print $msgfh "\t";
427 my @lt = localtime;
428 my @days = qw( Sun Mon Tue Wed Thu Fri Sat );
429 print $msgfh $days[ $lt[ 6 ] ] . ", ";
430 print $msgfh $lt[ 3 ];
431 print $msgfh " ";
432 my @months = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
433 print $msgfh $months[ $lt[ 4 ] ];
434 print $msgfh " ";
435 print $msgfh $lt[ 5 ] + 1900;
436 print $msgfh " ";
437 foreach my $n ( @lt[ 0, 1, 2 ] ) {
438 $n = "0$n" while ( length( $n ) < 2 );
439 }
440 print $msgfh join( ':', @lt[ 2, 1, 0 ] );
441 print $msgfh " ";
442 print $msgfh time_zone();
443
444 print $msgfh "\n";
445 }
446
447 #
448 # This copies the incoming message to the filehandle given and in
449 # the process picks out what addresses are referenced as recipients in
450 # the headers of the message.
451 #
452 sub process_msg {
453 my ( $msgfh, $toref ) = @_;
454
455 add_trace_line( $msgfh );
456
457 my $in_headers = 1; # Whether we're still in the headers of the message.
458 my $in_to = 0; # Whether we're in a To: or Cc: line
459
460 while ( <STDIN> ) {
461 print $msgfh $_;
462
463 $in_to = 0 if ( $in_to && ! /^\s/ );
464 $in_headers = 0 if ( $in_headers && !/\S/ );
465
466 my $line = $_;
467
468 # This is a challenge sent to an unknown party. I make it extra
469 # expensive so it's "last in line" for processing.
470 if ( $in_headers && ( $line =~ /^Reply-To: kyle-cnf-/ ) ) {
471 $extra_expense = 1;
472 }
473 # This is a message on its way to me locally. It needs no cash.
474 if ( $in_headers && ( $line =~ /^X-TMDA-Confirm-Done: / ) ) {
475 $confirmed = 1;
476 }
477 # Pull addresses off Cc: and To: lines. This is used to tell
478 # which envelope recipients are blind carbon copies.
479 if ( $in_headers && ( $in_to || $line =~ s/^(Cc|To): // ) ) {
480 # Get rid of all whitespace
481 $line =~ s/\s+//g;
482
483 # Get rid of any quoted text
484 $line =~ s/\"[^\"]*\"//g;
485
486 foreach my $addr ( split( ',', $line ) ) {
487 next if ( $addr =~ m/undisclosed-recipients/i );
488 next if ( $addr =~ m/recipientlistsuppressed/i );
489
490 # Does it contain a route-addr?
491 if ($addr =~ m/<(.*)>/) {
492 # Use the route-addr
493 $addr = $1;
494 }
495
496 # Does it have single quotes around it?
497 # Microsoft Exchange sometimes does this
498 $addr =~ s/^\'//;
499 $addr =~ s/\'$//;
500
501 # Get rid of comments in ()'s
502 $addr =~ s/\(.*\)//g;
503
504 if ( defined( $addr ) && $addr =~ m/^[-_.+\w]+\@[-_.+\w]+$/ ) {
505 push( @$toref, $addr );
506 }
507 }
508
509 $in_to = 1;
510 }
511 }
512 }
513
514 #
515 # This looks at the arguments that were passed in (meant for sendmail)
516 # and tries to pick out the envelope recipients and the "pre args" that
517 # I should maintain if I end up meddling with the evenlope recipients.
518 #
519 sub process_args {
520 my ( $args, $pre_args, $env_recip ) = @_;
521
522 if ( @$env_recip = grep( /^--$/ .. undef, @$args ) ) {
523 shift( @$env_recip );
524
525 my @tmp = @$args;
526 while ( my $t = shift( @tmp ) ) {
527 push( @$pre_args, $t );
528 last if ( $t eq '--' );
529 }
530 }
531 else {
532 # There's no '--' argument.
533 my @a = @$args;
534 while ( my $arg = shift( @a ) ) {
535 if ( $arg eq '-f' ) {
536 push( @$pre_args, $arg );
537 push( @$pre_args, shift( @a ) );
538 next;
539 }
540 if ( $arg =~ /^-/ ) {
541 push( @$pre_args, $arg );
542 }
543 else {
544 push( @$env_recip, $arg );
545 }
546 }
547 }
548 }
549
550 #
551 # Interrupt the currently running hashcash to deliver a more important message.
552 # If the interruption is successful, this calls begin_delivery() for the
553 # specified message and puts it on the stack.
554 #
555 sub interrupt_with {
556 my ( $msg, $stackr ) = @_;
557
558 # This is what's running right now.
559 my $topstate = $$stackr[ -1 ];
560
561 my $stoppid = $$topstate{ 'hashcashpid' };
562 if ( kill( 'STOP', $stoppid ) ) {
563 logline( "interrupted $$topstate{ 'msg' } for $msg" );
564
565 if ( ! begin_delivery( $msg, $stackr ) ) {
566 # In this case, the message was delivered without any work done.
567 # We need to restart the message we just interrupted.
568 logline( "continuing $$topstate{ 'msg' }" );
569 if ( ! kill( 'CONT', $stoppid ) ) {
570 fatal( "failed to restart $$topstate{ 'msg' } (pid $stoppid)" );
571 }
572 }
573 }
574 }
575
576 #
577 # This is used to sort the messages. We expect two filenames of the form:
578 # 1234-1234567890.1234.msg
579 # The first number is the expense, the second is when it entered the queue,
580 # and the third is just the PID of the queue writer.
581 # Above all, a .msg comes before a .req.
582 # Then we compare expenses and dates, and lower number wins for each.
583 # If they're equal on all counts, we just string compare the names, which
584 # probably means we're deciding based on a PID.
585 #
586 sub prioritize {
587 my ( $ap, $ad, $bp, $bd ) = ( undef, undef, undef, undef );
588 my ( $ae, $be ) = ( undef, undef );
589
590 if ( $a =~ /\.(\w{3})$/ ) {
591 $ae = $1;
592 }
593 if ( $b =~ /\.(\w{3})$/ ) {
594 $be = $1;
595 }
596
597 if ( defined( $ae ) && defined( $be ) && $ae ne $be ) {
598 # It just so happens that ( 'msg' cmp 'req' ) comes out "right".
599 # If not, I'd have to be explicit about which I wanted first.
600 return $ae cmp $be;
601 }
602
603 if ( $a =~ /^(\d+)-(\d+)\./ ) {
604 $ap = $1; #priority (expense)
605 $ad = $2; #date
606 }
607 if ( $b =~ /^(\d+)-(\d+)\./ ) {
608 $bp = $1;
609 $bd = $2;
610 }
611 if ( defined( $bp ) && defined( $ap ) && $bp != $ap ) {
612 return ( $ap <=> $bp );
613 }
614 if ( defined( $bd ) && defined( $ad ) && $bd != $ad ) {
615 return ( $ad <=> $bd );
616 }
617
618 return ( $a cmp $b );
619 }
620
621
622 #
623 # Call begin_delivery with a message to deliver.
624 # From there, everything spawns and runs.
625 # When hashcashfh is ready, call continue_delivery( $state )
626 # Delivery is finished when *_delivery() returns zero.
627 #
628
629 #
630 # begin_delivery takes a filename (of a message to work on) and returns
631 # a $state hash reference. It returns zero if the message is already
632 # delivered (i.e., when it had no hashcash to compute).
633 #
634 # Its job is basically to set up the process. It does everything up to
635 # where we need to invoke the hashcash executable, and then it calls
636 # continue_delivery() which does that invocation.
637 #
638 # This pushes a state onto the stack and it expects it to stay on top.
639 # If it calls continue_delivery() and finds that the message is all done,
640 # it pops the top item off the stack.
641 # XXX Perhaps I should verify it's the same state I pushed.
642 #
643 sub begin_delivery {
644 my ( $msg, $stackr ) = @_;
645
646 # The state we'll eventually return.
647 my $state = { 'msg' => $msg };
648
649 logline( "found $msg\n" );
650
651 # Move the message out of the queue and into the tmp directory.
652 # If this fails, we skip it. Maybe some other daemon got it first?
653 if ( rename( "$workdir/queue/$msg", "$workdir/tmp/$msg" ) ) {
654
655 push( @$stackr, $state );
656
657 # Get the name of the corresponding .dat file and import its data.
658 my $dat = "$workdir/tmp/$msg";
659 # If $msg is a .req, $dat isn't changed.
660 $dat =~ s:/tmp/(.*)\.msg$:/queue/$1.dat:;
661
662 # XXX It might be nice to handle errors in the dat file.
663 require "$dat";
664
665 $$state{ 'dat' } = $dat;
666 $$state{ 'recip' } = [ @rcpt ]; # This was read from .dat
667
668 # A .req doesn't need all this sendmail and stuff.
669 if ( $msg =~ /\.msg$/ ) {
670 # Open the message for reading.
671 my $msgfh = new IO::File;
672 open( $msgfh, "$workdir/tmp/$msg" ) || fatal( "Can't read $workdir/tmp/$msg: $!\n" );
673 $$state{ 'msgfh' } = $msgfh;
674
675 # Build the sendmail command line.
676 my $com = "|/usr/sbin/sendmail";
677 foreach my $arg ( @args ) {
678 $com .= " \"" . shell_escape( $arg ) . "\"";
679 }
680
681 # Open the pipe to sendmail.
682 spawn_sendmail( $state, $com );
683 my $sendmailfh = $$state{ 'sendmailfh' };
684
685 # Read the header of the message and send it to sendmail.
686 my $line = '';
687 while ( $line = $msgfh->getline ) {
688 last if ( $line !~ /\S/ );
689 print $sendmailfh $line;
690 }
691 # Remember exactly what the blank line was.
692 $$state{ 'blankline' } = $line;
693 }
694
695 # go get some hashcash
696 my $out = continue_delivery( $state );
697 if ( ! $out ) {
698 pop( @$stackr );
699 }
700 return $out;
701 }
702
703 return 0;
704 }
705
706 #
707 # This starts up the sendmail process and puts the writable filehandle in
708 # the given $state for later. We also open sendmail's stdout/stderr for
709 # reading, and this function forks to read what it has to say without
710 # blocking. Whatever sendmail outputs is logged.
711 #
712 sub spawn_sendmail {
713 my ( $state, $com ) = @_;
714
715 # Open3 knows this is a pipe; it's an error to have it there.
716 $com =~ s/^\|//;
717
718 my $smin = new IO::File;
719 my $smout = new IO::File;
720
721 # XXX Doc says failures don't return; they raise an exception. What?
722 my $smpid = open3( $smin, $smout, $smout, $com );
723
724 if ( ! $smpid ) {
725 fatal( "Can't open sendmail: $!\n" );
726 }
727
728 $$state{ 'sendmailfh' } = $smin;
729 $$state{ 'sendmailpid' } = $smpid;
730
731 # Now, fork a reader just to get and log sendmail's error messages.
732
733 my $pid;
734 if ( $pid = fork() ) {
735 # parent
736 close( $smout ); # parent does not read
737 $$state{ 'loggerpid' } = $pid;
738
739 return;
740 }
741 elsif ( ! defined( $pid ) ) {
742 # child
743 $need_cleanup = 0;
744 fatal( "Can't fork: $!\n" );
745 }
746 # This should NOT do cleanup. It's not THE daemon, just a little logger.
747 $need_cleanup = 0;
748
749 close( $smin ); # child does not write
750
751 while ( my $line = $smout->getline ) {
752 logline( "sendmail[$smpid] said: $line" );
753 }
754 close( $smout );
755
756 exit;
757 }
758
759 #
760 # There's a hashcash subprocess with a token ready. Read it, and do the
761 # right thing with it. We'll either feed it to waiting sendmail or put
762 # it in a premade token file for later. If it does not go to sendmail,
763 # we return 0 so the caller knows to call finish_delivery() and clean up.
764 #
765 sub take_new_token {
766 my ( $state ) = @_;
767
768 my $hc = $$state{ 'hashcashfh' };
769 my $tok = join( '', $hc->getlines );
770 close( $hc );
771 waitpid( $$state{ 'hashcashpid' }, 0 );
772
773 logline( "made token $tok" );
774
775 if ( exists( $$state{ 'sendmailfh' } ) ) {
776 my $sm = $$state{ 'sendmailfh' };
777 print $sm $tok if ( $tok );
778 }
779 else {
780 # If there's no sendmailfh, this is a request, not a message.
781
782 my ( $bits, $expiry, $r ) = ( $$state{ 'cashinfo' } =~ /^(\d+):(\d*):(.*)/ );
783 # Take the expiry on the token regardless of what we thought
784 # it would be.
785 # v0 = 0:date
786 # v1 = 1:bits:date
787 if ( $tok =~ /X-Hashcash: (?:0|1:\d+):(\d+):/ ) {
788 $expiry = $1;
789 }
790
791 # Make sure the premade directory exists
792 if ( ! -d "$workdir/premade" && ! mkdir( "$workdir/premade" ) ) {
793 fatal( "Can't create $workdir/premade: $!\n" );
794 }
795
796 # Initial filename. That '0' on the end gets incremented until
797 # we find one that's not taken.
798 my $prefile = "$workdir/premade/" . res2file( $r ) . ".$expiry.$bits.0";
799 my $fh = new IO::File;
800 while ( -e $prefile ||
801 ! sysopen( $fh, $prefile, O_RDWR|O_CREAT ) ||
802 ! flock( $fh, LOCK_EX|LOCK_NB ) )
803 {
804 $prefile =~ s/\.(\d+)$/"." . ($1 + 1)/e;
805 }
806 logline( "saving to $prefile" );
807
808 if ( ! truncate( $fh, 0 ) ) {
809 fatal( "Can't truncate $prefile: $!\n" );
810 }
811 print $fh $tok if ( $tok );
812 close( $fh );
813
814 # Multiple recipients in one .req not supported.
815 return 0;
816 }
817 }
818
819 #
820 # continue_delivery takes a state as an argument and returns a state. It
821 # returns zero if the delivery is finished.
822 #
823 # What this does is invoke hashcash and then return the state information
824 # used to keep track of the job. If there's a job already in progress, it
825 # pulls in the token and adds it to the outgoing message. The caller is
826 # responsible for making sure the job is ready to read.
827 #
828 sub continue_delivery {
829 my ( $state ) = @_;
830
831 # If there's hashcash to read, read it and add it to the outgoing
832 # message. This won't happen the first time continue_delivery is
833 # called for a message.
834 if ( exists( $$state{ 'hashcashfh' } ) && ! take_new_token( $state ) ) {
835 return finish_delivery( $state );
836 }
837
838 # Look through the recip list to find a recipient.
839 my $recipient = undef;
840 my $expiry = undef;
841 my $bits = $bits_to_compute;
842 my $r = undef;
843 while ( @{ $$state{ 'recip' } } && ! defined( $recipient ) ) {
844 $recipient = shift( @{ $$state{ 'recip' } } );
845 if ( defined( $recipient ) ) {
846 if ( $$recipient{ 'bits' } ) {
847 $bits = $$recipient{ 'bits' };
848 }
849 if ( exists( $$recipient{ 'expiry' } ) ) {
850 $expiry = $$recipient{ 'expiry' };
851 }
852
853 # The guess is used in places where I always want to have
854 # something. The $expiry is used for the command line.
855 my $expguess = $expiry ? $expiry : expire_today();
856
857 $$state{ 'cashinfo' } = "$bits:$expguess:$$recipient{ 'addr' }";
858
859 if ( exists( $$state{ 'sendmailfh' } ) ) {
860 my $tok = get_premade( $bits, $expguess, $$recipient{ 'addr' },
861 $$state{ 'sendmailfh' } );
862 if ( $tok ) {
863 # Using this means we don't need to process this recipient
864 # any further, so pretend we didn't find it.
865 $recipient = undef;
866 }
867 }
868 }
869 }
870 # If there are no more recipients, call finish_delivery(),
871 # which always returns zero.
872 if ( ! defined( $recipient ) ) {
873 return finish_delivery( $state );
874 }
875
876 # Figure out the command line for hashcash.
877 if ( defined( $$recipient{ 'reso' } ) ) {
878 $r = shell_escape( $$recipient{ 'reso' } );
879 }
880 else {
881 $r = shell_escape( $$recipient{ 'addr' } );
882 }
883 my $nice = ( $$recipient{ 'nice' } > 0 ) ? "nice -$$recipient{ 'nice' }" : '';
884 my $ex = defined( $expiry ) ? "-t $expiry" : '';
885
886 logline( "making token for $r ($bits bits)" );
887
888 # Spawn the hashcash executable to do the grunt work.
889 # We retain the PID and filehandle for later communication.
890 my $rdfh = new IO::File;
891 my $pid = open( $rdfh, "$nice hashcash -qm $ex -b $bits -r \"$r\" -X|" );
892 if ( ! $pid ) {
893 complain( "failed to execute hashcash: $!\n" );
894 # Go on to next recipient.
895 return continue_delivery( $state );
896 }
897
898 # Search the stack for another message that's making the same stamp
899 my $steal = undef;
900 foreach my $s ( @stack ) {
901 next if ( $s == $state );
902
903 if ( $$state{ 'cashinfo' } eq $$s{ 'cashinfo' } ) {
904 $steal = $s;
905 last;
906 }
907 }
908
909 if ( ! $steal ) {
910 # We're not stealing an existing process. Just store the
911 # PID and filehandle and go.
912 $$state{ 'hashcashpid' } = $pid;
913 $$state{ 'hashcashfh' } = $rdfh;
914 }
915 else {
916 # This can most easily happen if the daemon is processing a .req
917 # but hasn't finished. We'll steal the request's work-so-far
918 # and have it start over.
919 # This can also happen if there's one message with many recipients,
920 # and the recipient being computed right now gets another message
921 # addressed just to that one recipient. The new message will be
922 # lower cost than the old, and it'll take its work.
923 # Otherwise this only happens if you edit the bitconf between
924 # messages, which is how I tested (meddle with the nice value).
925 # NOTE that in the first and third case, the 'nice' level of the
926 # process we steal is not necessarily what we want.
927 logline( "using PID $$steal{ 'hashcashpid' } in progress for $r" );
928
929 # Stop the new one.
930 # logline( "stopping $pid" );
931 if ( ! kill( 'STOP', $pid ) ) {
932 fatal( "Can't stop hashcash (pid $pid): $!\n" );
933 }
934
935 # Take the PID and filehandle of the (stopped) one already in progress.
936 $$state{ 'hashcashpid' } = $$steal{ 'hashcashpid' };
937 $$state{ 'hashcashfh' } = $$steal{ 'hashcashfh' };
938
939 # The one in progress becomes the one we just started.
940 $$steal{ 'hashcashpid' } = $pid;
941 $$steal{ 'hashcashfh' } = $rdfh;
942
943 # Restart the old one.
944 # logline( "starting $$state{ 'hashcashpid' }" );
945 if ( ! kill( 'CONT', $$state{ 'hashcashpid' } ) ) {
946 fatal( "Can't restart hashcash: $!\n" );
947 }
948 }
949
950 return $state;
951 }
952
953 # What the 'expire' part of a token will look like for something made now.
954 sub expire_today {
955 my ( $sec,$min,$hour, $mday,$mon,$year, $wday,$yday, $isdst ) = gmtime;
956
957 $year =~ s/^\d*(\d\d)$/$1/;
958 $mon++;
959
960 $year = "0$year" while ( length( $year ) < 2 );
961 $mon = "0$mon" while ( length( $mon ) < 2 );
962 $mday = "0$mday" while ( length( $mday ) < 2 );
963
964 return "$year$mon$mday";
965 }
966
967 sub get_recipient_premade {
968 my ( $recipient, $outfh ) = @_;
969
970 return unless ( $recipient );
971 return unless ( $outfh );
972
973 my $bits = $bits_to_compute;
974 if ( $$recipient{ 'bits' } ) {
975 $bits = $$recipient{ 'bits' };
976 }
977
978 my $expiry = undef;
979 if ( exists( $$recipient{ 'expiry' } ) ) {
980 $expiry = $$recipient{ 'expiry' };
981 }
982
983 # The guess is used in places where I always want to have
984 # something. The $expiry is used for the command line.
985 my $expguess = $expiry ? $expiry : expire_today();
986
987 # $$state{ 'cashinfo' } = "$bits:$expguess:$$recipient{ 'addr' }";
988
989 return get_premade( $bits, $expguess, $$recipient{ 'addr' }, $outfh );
990 }
991
992 #
993 # Look through the premade tokens to find one that satisfies the given
994 # requirements. The expiry and resource must match, but we'll take any
995 # token with the given bits or more.
996 #
997 sub get_premade {
998 my ( $bits, $expiry, $r, $outfh ) = @_;
999
1000 my $out = undef;
1001
1002 if ( $outfh && opendir( PREMADE, "$workdir/premade" ) ) {
1003 # This sorts the premade files by their cost in bits.
1004 # This way I can take the cheapest token that matches.
1005 my $bybits = sub {
1006 if ( $a =~ /^[\w-]*\.\d*\.(\d+)\./ ) {
1007 my $abits = $1;
1008 if ( $b =~ /^[\w-]*\.\d*\.(\d+)\./ ) {
1009 my $bbits = $1;
1010 return ( $abits <=> $bbits );
1011 }
1012 }
1013 return ( $a cmp $b );
1014 };
1015
1016 my $sha = res2file( $r );
1017 # All premade tokens for this recipient, sorted by bits.
1018 my @premade_files = sort $bybits readdir( PREMADE );
1019 closedir( PREMADE );
1020
1021 foreach my $premade ( @premade_files ) {
1022 my ( $fsha, $fexpiry, $fbits ) = ( $premade =~ /^([\w-]*)\.(\d*)\.(\d+)\./ );
1023 next if ( $fsha ne $sha );
1024 next if ( $fexpiry ne $expiry );
1025 next if ( $fbits < $bits );
1026
1027 my $pfh = undef;
1028 # If I'm able to rename the file, that ensures no other daemon
1029 # got a hold of it first.
1030 if ( rename( "$workdir/premade/$premade", "$workdir/tmp/$premade" ) ) {
1031 if ( ! open( $pfh, "$workdir/tmp/$premade" ) ) {
1032 complain( "Can't open $workdir/tmp/$premade: $!\n" );
1033 next;
1034 }
1035 $out = join( '', $pfh->getlines );
1036 close( $pfh );
1037 if ( ! unlink( "$workdir/tmp/$premade" ) ) {
1038 complain( "Can't unlink $workdir/tmp/$premade: $!\n" );
1039 }
1040 # Look at no more files.
1041 last;
1042 }
1043 }
1044 }
1045
1046 if ( $out ) {
1047 # If we have a premade token, use it.
1048 logline( "using premade token $out" );
1049 print $outfh $out;
1050 }
1051
1052 return $out;
1053 }
1054
1055 #
1056 # finish_delivery() takes a state as an argument and returns zero.
1057 # This function's job is just to push the message body out to sendmail.
1058 #
1059 sub finish_delivery {
1060 my ( $state ) = @_;
1061
1062 my $msg = $$state{ 'msg' };
1063 my $sm = $$state{ 'sendmailfh' };
1064 my $msgfh = $$state{ 'msgfh' };
1065
1066 if ( $sm ) {
1067 if ( exists( $$state{ 'blankline' } ) ) {
1068 print $sm $$state{ 'blankline' };
1069 delete( $$state{ 'blankline' } );
1070 }
1071
1072 if ( $msgfh ) {
1073 while ( my $line = $msgfh->getline ) {
1074 print $sm $line;
1075 }
1076 }
1077
1078 # This checks sendmail's exit status. If something's wrong, we
1079 # put the message back in the queue, whine, and abort with the same
1080 # exit code that sendmail gave.
1081 if ( ! close( $sm ) && ! $! ) {
1082 # Propogate the exit code.
1083 my $exit_code = $?;
1084
1085 logline( "putting $msg back in queue" );
1086 rename( "$workdir/tmp/$msg", "$workdir/queue/$msg" );
1087 complain( "sendmail exited with $exit_code\n" );
1088 exit( $exit_code );
1089 }
1090
1091 # Reap my subprocesses properly.
1092 if ( $$state{ 'sendmailpid' } ) {
1093 waitpid( $$state{ 'sendmailpid' }, 0 );
1094 }
1095 if ( $$state{ 'loggerpid' } ) {
1096 waitpid( $$state{ 'loggerpid' }, 0 );
1097 }
1098 }
1099 close( $msgfh ) if ( $msgfh );
1100
1101 # Delete the message and the dat file.
1102 if ( ! unlink( "$workdir/tmp/$msg", $$state{ 'dat' } ) ) {
1103 fatal( "Can't unlink: $!\n" );
1104 }
1105
1106 if ( $msg =~ /^\d+-(\d+)\.\d+\.msg/ ) {
1107 my $intime = $1;
1108 my $qtime = time() - $intime;
1109 logline( "delivered $msg about $qtime seconds since it was queued" );
1110 }
1111 else {
1112 logline( "delivered $msg" );
1113 }
1114
1115 %{ $state } = ();
1116
1117 return 0;
1118 }
1119
1120 # It's a 'warn' that logs as well.
1121 sub complain {
1122 my ( $line ) = @_;
1123
1124 logline( $line );
1125 warn $line;
1126 }
1127
1128 # It's a 'die' that logs as well.
1129 sub fatal {
1130 my ( $line ) = @_;
1131
1132 logline( "FATAL: $line" );
1133 die $line;
1134 }
1135
1136 # Writes a line to the log. It does nice stuff like add a datestamp
1137 # and the program name and such.
1138 sub logline {
1139 my ( $line ) = @_;
1140
1141 if ( $line =~ /\S/ ) {
1142 my $out = scalar localtime();
1143
1144 my $name = $0;
1145 $name =~ s:^/.*/([^/]+)$:$1:;
1146
1147 $out .= " $name\[$$]: ";
1148
1149 $line =~ tr/\r\n/ /;
1150 $line =~ s/^\s+//;
1151 $line =~ s/\s+$//;
1152
1153 $out .= "$line\n";
1154
1155 lograw( $out );
1156 }
1157 }
1158
1159 # Logs stuff. It does locking on the log file, but it does no formatting.
1160 sub lograw {
1161 my @logstuff = @_;
1162
1163 my $fh = new IO::File;
1164 sysopen( $fh, $logfile, O_RDWR|O_CREAT ) || die "Can't write $logfile: $!\n";
1165 flock( $fh, LOCK_EX ) || die "Can't LOCK_EX $logfile: $!\n";
1166 seek( $fh, 0, SEEK_END ) || die "Can't seek on $logfile: $!\n";
1167
1168 print $fh @logstuff;
1169
1170 close( $fh );
1171 }
1172
1173 # Camel book, 3rd ed, page 782
1174 sub fhbits {
1175 my @fhlist = @_;
1176 my $bits;
1177 for ( @fhlist ) {
1178 vec( $bits, fileno( $_ ), 1 ) = 1;
1179 }
1180 return $bits;
1181 }
1182
1183 # This is called any time we're about to die. Its job is to put .msg
1184 # files back in the queue and kill lingering hashcash jobs.
1185 sub cleanup {
1186 my ( $sig ) = @_;
1187
1188 my $sigmess = ( $sig ) ? " on signal $sig" : '';
1189
1190 if ( ! $need_cleanup ) {
1191 logline( "exit$sigmess" ) if ( $sigmess );
1192 }
1193 else {
1194 $need_cleanup = 0;
1195
1196 logline( "cleanup$sigmess" );
1197 foreach my $state ( @stack ) {
1198 my $pid = $$state{ 'sendmailpid' };
1199 if ( $pid ) {
1200 logline( "TERM sendmail PID $pid" );
1201 kill( 'TERM', $pid );
1202 }
1203 # This was 'TERM', but that didn't get it.
1204 $pid = $$state{ 'hashcashpid' };
1205 logline( "KILL hashcash PID $pid" );
1206 kill( 'KILL', $pid );
1207
1208 my $msg = $$state{ 'msg' };
1209 logline( "putting $msg back in queue" );
1210 rename( "$workdir/tmp/$msg", "$workdir/queue/$msg" );
1211 }
1212 # It's tempting to unlink $pidfile here, but it's possible
1213 # someone has it open for reading. If I unlink it, they'll
1214 # write to a file that disappears when they close it.
1215 }
1216 exit;
1217 }
1218
1219 # This looks through premade tokens looking for things that are expired.
1220 sub expire_premade {
1221 if ( opendir( PREMADE, "$workdir/premade" ) ) {
1222 my $now = expire_today();
1223 while ( my $premade = readdir( PREMADE ) ) {
1224 if ( $premade =~ /^[\w-]*\.(\d+)\./ ) {
1225 my $e = $1;
1226 if ( $e < $now ) {
1227 logline( "discarding expired premade token in $premade" );
1228 if ( ! unlink( "$workdir/premade/$premade" ) ) {
1229 complain( "Can't unlink $premade: $!\n" );
1230 }
1231 }
1232 }
1233 }
1234 closedir( PREMADE );
1235 }
1236 }
1237
1238 #
1239 # Look for a .msg or .req in tmp/ and return it to the queue/
1240 # This is called after we've determined that this is to be the one and only
1241 # daemon but before we start processing messages, so we know tmp/ SHOULD
1242 # be empty. Messages might be left in tmp/ if hashcash-sendmail was running
1243 # during a power failure, for instance.
1244 #
1245 sub recover_dead_queue {
1246 if ( ! opendir( TMP, "$workdir/tmp" ) ) {
1247 complain( "Can't opendir( $workdir/tmp ): $!\n" );
1248 return;
1249 }
1250 my @replace = grep( !/^\./ && /\.(req|msg)$/, readdir( TMP ) );
1251 closedir( TMP );
1252
1253 if ( @replace ) {
1254 complain( "Earlier hashcash daemon must have died; replacing lost queue items." );
1255 foreach my $file ( @replace ) {
1256 if ( -f "$workdir/queue/$file" ) {
1257 complain( "'$file' exists in both tmp and queue!" );
1258 next;
1259 }
1260 rename( "$workdir/tmp/$file", "$workdir/queue/$file" ) || complain( "Can't rename tmp/$file to queue: $!\n" );
1261 }
1262 }
1263 }
1264
1265 #
1266 # This checks if another daemon is running and exits if there is.
1267 # If not, we write our PID to the pidfile.
1268 #
1269 sub handle_pidfile {
1270 my ( $pidfile ) = @_;
1271
1272 # Open for read and write, create if not there.
1273 my $pidfh = new IO::File;
1274 if ( ! sysopen( $pidfh, "$pidfile", O_RDWR|O_CREAT ) ) {
1275 fatal( "Can't write $pidfile: $!\n" );
1276 }
1277
1278 # Locking avoids race conditions. I can share a lock with someone else
1279 # who's also trying to read, but I can't share with a writer.
1280 flock( $pidfh, LOCK_SH ) || fatal( "Can't LOCK_SH $pidfile: $!\n" );
1281 my $oldpid = $pidfh->getline;
1282
1283 # Check if the old daemon is still alive.
1284 if ( $oldpid && kill( 0, $oldpid ) ) {
1285 # There's already a daemon running.
1286 logline( "waking PID $oldpid" );
1287 kill( 'USR1', $oldpid );
1288 exit 0;
1289 }
1290
1291 # Truncate the file and write my own PID there.
1292 flock( $pidfh, LOCK_EX|LOCK_NB ) || fatal( "Can't lock $pidfile: $!\n" );
1293 seek( $pidfh, 0, SEEK_SET ) || fatal( "Can't seek on $pidfile: $!\n" );
1294 truncate( $pidfh, 0 ) || fatal( "Can't truncate $pidfile: $!\n" );
1295 print $pidfh "$$\n";
1296 close( $pidfh );
1297 }
1298
1299 # This is to disconnect from the shell that ran me.
1300 sub daemonize {
1301 my $pid;
1302
1303 # Doing this instead of just closing them makes some oddball case work.
1304 # I wish I knew why.
1305 open( STDIN, "/dev/null" ) || fatal( "Can't reopen STDIN: $!\n" );
1306 open( STDOUT, ">/dev/null" ) || fatal( "Can't reopen STDOUT: $!\n" );
1307 open( STDERR, ">/dev/null" ) || fatal( "Can't reopen STDERR: $!\n" );
1308
1309 # Ignore the fact that the parent dies.
1310 $SIG{ HUP } = sub { logline( "ignored $_[0]" ); };
1311
1312 if ( $pid = fork() ) {
1313 # Parent exits immediately.
1314 exit 0;
1315 }
1316 elsif ( ! defined( $pid ) ) {
1317 complain( "Can't fork: $!\n" );
1318 }
1319
1320 setpgrp( 0, $$ );
1321 setsid();
1322 }
1323
1324 # Escapes shell meta characters, so I can safely use it on the command line.
1325 # This does NOT escape spaces. What you get from this is meant to be put in
1326 # double quotes on the command line.
1327 sub shell_escape {
1328 my ( $string ) = @_;
1329
1330 $string =~ s/\\/\\\\/g;
1331 $string =~ s/\"/\\\"/g;
1332 $string =~ s/\$/\\\$/g;
1333 $string =~ s/\`/\\\`/g;
1334
1335 return $string;
1336 }
1337
1338 #
1339 # Given a reference to a list of hashcash recipients, this will construct a
1340 # simple @rcpt list, which is just a bunch of references to hashes. Each
1341 # hash this produces will have JUST the recipient set, but other things will
1342 # be added to those hashes later.
1343 #
1344 sub msgrcpt {
1345 my ( $hashref ) = @_;
1346
1347 my @rcpt = ();
1348 if ( ! $confirmed ) {
1349 foreach my $addr ( @$hashref ) {
1350 my $add = { 'addr' => $addr };
1351 push( @rcpt, $add );
1352 }
1353 }
1354
1355 return @rcpt;
1356 }
1357
1358 #
1359 # Given a reference to a @rcpt list, and a reference to a @bitconf, this
1360 # will add missing information to the @rcpt list. For each thing in the
1361 # @rcpt list, we add 'bits' and 'nice' if they're not there.
1362 #
1363 sub heed_bitconf {
1364 my ( $rcptref, $confref ) = @_;
1365
1366 foreach my $add ( @$rcptref ) {
1367 next unless ( defined( $$add{ 'addr' } ) );
1368
1369 my $addr = $$add{ 'addr' };
1370 my $need_bitconf = 0;
1371
1372 $need_bitconf = 1 if ( ! defined( $$add{ 'bits' } ) );
1373 $need_bitconf = 1 if ( ! defined( $$add{ 'nice' } ) );
1374 $need_bitconf = 1 if ( ! defined( $$add{ 'reso' } ) );
1375
1376 next unless ( $need_bitconf );
1377
1378 foreach my $pair ( @$confref ) {
1379 # These are the fields in the bitconf, separated by colons.
1380 # $pat -- a regular expression
1381 # $bits -- how many bits to compute
1382 # $nice -- what nice value to run at.
1383 # $reso -- non-standard resource (optional)
1384 my ( $pat, $bits, $nice, $reso ) = split( /:/, $pair );
1385
1386 # If this address matches the pattern, we treat it as the
1387 # config says.
1388 if ( $addr =~ /$pat/i ) {
1389 if ( ! defined( $$add{ 'bits' } ) ) {
1390 $$add{ 'bits' } = $bits;
1391 }
1392 if ( ! defined( $$add{ 'nice' } ) ) {
1393 $$add{ 'nice' } = $nice;
1394 }
1395 if ( ! defined( $$add{ 'reso' } ) && defined( $reso ) ) {
1396 $$add{ 'reso' } = $reso;
1397 }
1398 last;
1399 }
1400 }
1401
1402 # It's possible that $addr does not match any pattern.
1403 # I'd still like to have some defaults in that case.
1404 $$add{ 'bits' } = $bits_to_compute if ( ! defined( $$add{ 'bits' } ) );
1405 # $$add{ 'nice' } = 19 if ( ! defined( $$add{ 'nice' } ) );
1406 }
1407 }
1408
1409 #
1410 # Given a reference to a @rcpt list, this computes the expense of the message.
1411 # Assumes that heed_bitconf was called, so there's 'nice' and 'bits' for all.
1412 #
1413 sub message_expense {
1414 my ( $rcptref ) = @_;
1415
1416 # For each recipient, we take log-base-2 of the number of bits we need
1417 # and multiply by 100. Without the multiplier, lots of values for
1418 # $bits would be indistinguishable. Then we multiply by the nice value
1419 # assigned because I figure the less we want to hog the CPU, the less
1420 # we care about this recipient, and the more "expensive" we should
1421 # consider it. The cost of all the recipients are summed.
1422
1423 my $expense = 0;
1424
1425 foreach my $add ( @$rcptref ) {
1426 next if ( ! defined( $add ) );
1427
1428 my $bits = $$add{ 'bits' } || $bits_to_compute;
1429
1430 my $exp = int( 100 * log( $bits ) / log( 2 ) );
1431 $exp *= $$add{ 'nice' } if ( $$add{ 'nice' } );
1432
1433 $expense += $exp;
1434 }
1435
1436 $expense *= 10 if ( $extra_expense );
1437
1438 return $expense;
1439 }
1440
1441 #
1442 # This queues one message.
1443 # $filebase -- the name of the temp file that has the message text.
1444 # $argsref -- (ref to) the arguments that'll be passed to sendmail.
1445 # $rcptref -- list of refs to hashes with recipient info.
1446 # $confref -- the config file we read in
1447 #
1448 # $filebase will be COPIED, so the caller is responsible for unlinking it.
1449 # This function computes the expense of the message and writes out
1450 # everything that will go to the queue.
1451 #
1452 # If $argsref is false or points to an empty list, queue() thinks this is
1453 # a request for a premade token. In that case, $filebase doesn't exist,
1454 # and we do things a little differently to queue the .req
1455 #
1456 sub queue {
1457 my ( $filebase, $argsref, $rcptref, $confref ) = @_;
1458
1459 # Add bitconf info to the recipients.
1460 heed_bitconf( $rcptref, $confref );
1461
1462 my $is_req = ( $argsref && @$argsref ) ? 0 : 1;
1463 my $ext = $is_req ? 'req' : 'msg';
1464
1465 my $tmpfile = "$workdir/tmp/msgcopy$$";
1466 if ( ! $is_req ) {
1467 if ( ! copy_with_premade( "$workdir/tmp/$filebase.msg", "$tmpfile",
1468 $rcptref ) )
1469 {
1470 unlink( "$workdir/tmp/$filebase.msg" );
1471 die "Can't copy $filebase.msg: $!\n";
1472 }
1473 }
1474
1475 # Compute expense based on the recipients who need hashcash.
1476 my $expense = message_expense( $rcptref );
1477
1478 # Make sure we're not about to overwrite something. If so, we
1479 # increment $expense until we find a place to write.
1480 my $outbase = "$workdir/queue/$expense-$filebase";
1481 while ( -e "$outbase.$ext" ) {
1482 $expense++;
1483 $outbase = "$workdir/queue/$expense-$filebase";
1484 }
1485
1486 # This is where we'll write the metadata for the message.
1487 # For requests, this is the only thing we'll write.
1488 my $dat = ( $is_req ) ? "$workdir/tmp/$expense-$filebase.req" : "$outbase.dat";
1489
1490
1491 # Now we write our .dat file with the stuff the daemon will need.
1492 # If this is a request, we're writing the final .req file that will go in the
1493 # queue. We write it to tmp so we can do a nice atomic rename() later.
1494 if ( ! open( META, ">$dat" ) ) {
1495 die "Can't write $dat: $!\n";
1496 }
1497
1498 $Data::Dumper::Useqq = 1;
1499 my $dump;
1500 if ( $argsref && @$argsref ) {
1501 $dump = Data::Dumper->Dump( [ $argsref, $rcptref ],
1502 [ qw( *args *rcpt ) ] );
1503 }
1504 else {
1505 $dump = Data::Dumper->Dump( [ $rcptref ],
1506 [ qw( *rcpt ) ] );
1507 }
1508 $dump .= "\n1;\n";
1509
1510 print META $dump;
1511 close( META );
1512
1513 # Put the message in the queue.
1514 # This is the point at which it's "live" and ready for processing.
1515 # Make no more modifications to the message after this! The daemon may
1516 # already be working on it.
1517
1518 if ( $is_req ) {
1519 $tmpfile = $dat;
1520 }
1521
1522 # I use a temp file to avoid a race condition where the daemon starts
1523 # reading the message before copy() is done writing it.
1524 if ( rename( $tmpfile, "$outbase.$ext" ) ) {
1525 my $rpt = "$outbase.$ext";
1526 $rpt =~ s:^.*/([^/]+)$:$1:;
1527 logline( "queued $rpt" );
1528 }
1529 else {
1530 unlink( $tmpfile );
1531 if ( ! $is_req ) {
1532 unlink( $dat, "$workdir/tmp/$filebase.msg" );
1533 }
1534 die "Can't rename $tmpfile: $!\n";
1535 }
1536
1537 return;
1538 }
1539
1540 #
1541 # This makes a copy of a message (for queueing) and also adds any premade
1542 # hashcash that is available. Pass in a recipient list reference so it
1543 # knows what recipients need hashcash. It will remove from that list
1544 # any recipients it was able to find premade tokens for. Returns 1 for
1545 # success and undef for failure.
1546 #
1547 sub copy_with_premade {
1548 my ( $msgfile, $outfile, $rcptref ) = @_;
1549
1550 # Open the input message for reading.
1551 my $msgfh = new IO::File;
1552 if ( ! open( $msgfh, $msgfile ) ) {
1553 complain( "Can't read $msgfile: $!\n" );
1554 return undef;
1555 }
1556
1557 # Open the output file for writing.
1558 my $outfh = new IO::File;
1559 if ( ! open( $outfh, ">$outfile" ) ) {
1560 complain( "Can't write $outfile: $!\n" );
1561 close( $msgfh );
1562 return undef;
1563 }
1564
1565 # Copy the headers (everything up to a line that does not contain
1566 # any non-whitespace characters).
1567 my $line;
1568 while ( $line = $msgfh->getline ) {
1569 last if ( $line !~ /\S/ );
1570 print $outfh $line;
1571 }
1572
1573 # Finished copying headers. Now loop through recipients and add what
1574 # hashcash we can.
1575 my @leftover = ();
1576 foreach my $r ( @$rcptref ) {
1577 if ( ! $r || ! get_recipient_premade( $r, $outfh ) ) {
1578 push( @leftover, $r );
1579 }
1580 }
1581
1582 # @leftover is just the ones for which we didn't have a premade token.
1583 # So @$rcptref is now smaller if we found premade tokens for things in it.
1584 @$rcptref = @leftover;
1585
1586 print $outfh $line; # The blank line we read at the end of headers.
1587
1588 # Copy the rest of the message.
1589 while ( $line = $msgfh->getline ) {
1590 print $outfh $line;
1591 }
1592
1593 close( $outfh );
1594 close( $msgfh );
1595
1596 return 1;
1597 }
1598
1599 #
1600 # Read in the config file.
1601 #
1602 # Example line:
1603 # kyle\@(.+\.)*toehold\.com:20:0:kyleha
1604 #
1605 # It's three or four fields separated by colons.
1606 #
1607 # The first field is a Perl regular expression to match.
1608 # The second is how many bits to compute for that recipient.
1609 # The third is the nice level to run at for that recipient.
1610 # The fourth is a resource value to use instead of the email address.
1611 #
1612 # The fourth field is optional. Such an entry looks like this:
1613 #
1614 # kyle\@(.+\.)*toehold\.com:20:0
1615 #
1616 # Comments start with a "#".
1617 # Any line that doesn't match the format is ignored.
1618 #
1619 # First match wins. It's probably good to have a "default" at the end of the
1620 # file like this:
1621 #
1622 # ^:26:19
1623 #
1624 # ...which means anyone not listed gets 26 bits running at nice -19 (lowest
1625 # priority).
1626 #
1627 sub read_bitconf {
1628 my @bitconf = ();
1629 if ( open( BITCONF, $conffile ) ) {
1630 while ( <BITCONF> ) {
1631 next if /^#/;
1632 next unless /^[^:]+:\d+:\d+(:[^:]*)?$/;
1633 chomp;
1634 push( @bitconf, $_ );
1635 }
1636 close( BITCONF );
1637 }
1638
1639 return @bitconf;
1640 }
1641
1642 # $Log: hashcash-sendmail,v $
1643 # Revision 1.18 2004/08/07 18:36:16 kyle
1644 # Check for queue items in tmp in case of crash.
1645 # Read multi-line tokens.
1646 #
1647 # Revision 1.17 2004/06/24 16:13:39 kyle
1648 # Check for and complaint about not disconnecting from parent doesn't work
1649 # and isn't needed.
1650 #
1651 # Revision 1.16 2004/06/11 15:27:25 kyle
1652 # Daemonize better.
1653 # Use SIGUSR1 for IPC instead of SIGHUP.
1654 #
1655 # Revision 1.15 2004/06/02 17:18:56 kyle
1656 # Bitconf can specify an arbitrary resource for any address.
1657 # If hashcash gave us a v1 stamp, hashcash-sendmail finds the date correctly.
1658 #
1659 # Revision 1.14 2004/04/13 18:58:02 kyle
1660 # Make sure time zone always has either a + or a - before the digits.
1661 #
1662 # Revision 1.13 2004/04/12 20:27:19 kyle
1663 # Fix a bug related to the new Recieved: headers I'm inserting (thanks to
1664 # Jason Mastaler for finding it).
1665 #
1666 # Revision 1.12 2004/04/06 16:59:15 kyle
1667 # Avoid crashing via log( $bits = 0 ).
1668 # Create the premade token directory if it doesn't exist.
1669 # Use premade tokens at queue time to speed up delivery.
1670 #
1671 # Revision 1.11 2004/04/02 20:55:45 kyle
1672 # Add a Received: line on the way through.
1673 # Properly reap a couple of child processes.
1674 # Log my hostname and RCS ID when the daemon starts.
1675 #
1676 # Revision 1.10 2004/04/02 18:57:45 kyle
1677 # Fixed a bug where premade tokens would clobber each other.
1678 # Better error reporting when sendmail complains.
1679 # Fixed a bug where the daemon would hang (I think).
1680 #
1681 # Revision 1.9 2004/03/31 05:14:59 kyle
1682 # hashcash-daemon has been incorporated into hashcash-sendmail now. After
1683 # messages are queued, it disconnects from the caller and tries to process
1684 # the queue. All the code from hashcash-daemon has been basically pasted in
1685 # and adapted slightly.
1686 # If hashcash-sendmail is invoked with no arguments, it expects a token
1687 # request on standard input. There's been lots of reorganization to support
1688 # the new dual purpose.
1689 # This also fixes a bug where the daemon wouldn't die properly if it had a
1690 # hashcash-in-progress when it received the kill signal.
1691 #
1692 # Revision 1.8 2004/03/19 20:36:46 kyle
1693 # Fix a possible race condition when copying the message to the queue.
1694 # Invoke the daemon right before exit.
1695 #
1696 # Revision 1.7 2004/03/16 01:47:58 kyle
1697 # Make sure not to overwrite a message I just queued in the case where I'm
1698 # handling a Bcc by making multiple copies. Thanks to Gerhard A. Blab for
1699 # pointing this out.
1700 # Also fix a bug where a failed queue() call would stop future queue() calls
1701 # from working.
1702 #
1703 # Revision 1.6 2004/03/09 06:01:59 kyle
1704 # Correctly handle the case where we have ALL Bcc and NO visible header
1705 # recipients. Also did some comment maintenance.
1706 #
1707 # Revision 1.5 2004/03/08 21:38:49 kyle
1708 # Queue separate messages for Bcc recipients so they still get hashcash but
1709 # don't get revealed to other recipients. Thanks to Adam Back for the
1710 # suggestion.
1711 #
1712 # Revision 1.4 2004/03/08 17:40:10 kyle
1713 # Fix the env_recip grep line (thanks Adam Back for figuring out the problem)
1714 # so that it works on other versions of Perl.
1715 # Add my email address and URL to the comments.
1716 #
1717 # Revision 1.3 2004/03/08 02:03:32 kyle
1718 # Create the working directories if they don't exist.
1719 #
1720 # Revision 1.2 2004/03/07 22:20:14 kyle
1721 # Make the working directory less hardcoded.
1722 #
1723 # Revision 1.1 2004/03/07 22:14:24 kyle
1724 # Initial revision
1725 #