PMilter/Context.pm untested

filter: Statementstmt 0.0% 0 / 410 Branchbran 0.0% 0 / 148 Conditioncond 0.0% 0 / 70 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 0.0% 0 / 68 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 753 CC 75 SCAR 57.1
CC
75
Cov
0%
main
1190.0
call_hooks
156.0
addheader
20.0
CRAP 303.0
1 =pod
2  
3 =head1 LICENSE
4  
5 Copyright (c) 2016-2026 G.W. Haywood. All rights reserved.
6 With thanks to all those who have trodden these paths before,
7 including
8 Copyright (c) 2002-2004 Todd Vierling. All rights reserved.
9  
10 Redistribution and use in source and binary forms, with or without
11 modification, are permitted provided that the following conditions are met:
12  
13 1. Redistributions of source code must retain the above copyright notices,
14 this list of conditions and the following disclaimer.
15  
16 2. Redistributions in binary form must reproduce the above copyright
17 notices, this list of conditions and the following disclaimer in the
18 documentation and/or other materials provided with the distribution.
19  
20 3. Neither the name of the author nor the names of contributors may be used
21 to endorse or promote products derived from this software without specific
22 prior written permission. In the case of G.W. Haywood this permission is
23 hereby now granted.
24  
25 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
29 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
30 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
31 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
33 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
34 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
35 POSSIBILITY OF SUCH DAMAGE.
36  
37 =cut
38  
39 package Sendmail::PMilter::Context;
40  
41 use 5.014; # Don't use 5.016 yet. That would enable feature 'unicode_strings', and we
42 # probably aren't quite ready for that. We're counting *characters* passed
43 # between us and Sendmail, and Sendmail thinks that they're *bytes*.
44 use parent 'Exporter';
45  
46 use strict;
47 use warnings;
48  
49 use Carp;
50 use Socket;
51 use UNIVERSAL;
52  
53 use Sendmail::PMilter 1.28 qw(:all);
54  
55 # use Data::Dumper;
56  
57 our $VERSION = '1.28';
58 $VERSION = eval $VERSION;
59  
60 =pod
61  
62 =head1 SYNOPSIS
63  
64 Sendmail::PMilter::Context - per-connection milter context
65  
66 =head1 DESCRIPTION
67  
68 A Sendmail::PMilter::Context is the context object passed to milter callback
69 functions as the first argument, typically named "$ctx" for convenience.
70 This document details the publicly accessible operations on this object.
71  
72 =head1 METHODS
73  
74 =cut
75  
76 ##### Symbols exported to the caller
77  
78 use constant SMFIA_UNKNOWN => 'U';
79 use constant SMFIA_UNIX => 'L';
80 use constant SMFIA_INET => '4';
81 use constant SMFIA_INET6 => '6';
82  
83 our @EXPORT_OK = qw(
84 SMFIA_UNKNOWN
85 SMFIA_UNIX
86 SMFIA_INET
87 SMFIA_INET6
88 );
89 our %EXPORT_TAGS = ( all => [ @EXPORT_OK ] );
90  
91 ##### Protocol constants
92 # Commands:
93 use constant SMFIC_ABORT => 'A';
94 use constant SMFIC_BODY => 'B';
95 use constant SMFIC_CONNECT => 'C';
96 use constant SMFIC_MACRO => 'D';
97 use constant SMFIC_BODYEOB => 'E';
98 use constant SMFIC_HELO => 'H';
99 use constant SMFIC_HEADER => 'L';
100 use constant SMFIC_MAIL => 'M';
101 use constant SMFIC_EOH => 'N';
102 use constant SMFIC_OPTNEG => 'O';
103 use constant SMFIC_RCPT => 'R';
104 use constant SMFIC_QUIT => 'Q';
105 use constant SMFIC_DATA => 'T'; # v4
106 use constant SMFIC_UNKNOWN => 'U'; # v3
107 # Responses:
108 use constant SMFIR_ADDRCPT => '+';
109 use constant SMFIR_DELRCPT => '-';
110 use constant SMFIR_ADDRCPT_PAR => '2';
111 use constant SMFIR_ACCEPT => 'a';
112 use constant SMFIR_REPLBODY => 'b';
113 use constant SMFIR_CONTINUE => 'c';
114 use constant SMFIR_DISCARD => 'd';
115 use constant SMFIR_ADDHEADER => 'h';
116 use constant SMFIR_INSHEADER => 'i'; # v3, or v2 and Sendmail 8.13+
117 use constant SMFIR_SETSYMLIST => 'l';
118 use constant SMFIR_CHGHEADER => 'm';
119 use constant SMFIR_PROGRESS => 'p';
120 use constant SMFIR_QUARANTINE => 'q';
121 use constant SMFIR_REJECT => 'r';
122 use constant SMFIR_CHGFROM => 'e'; # Sendmail 8.14+
123 use constant SMFIR_TEMPFAIL => 't';
124 use constant SMFIR_REPLYCODE => 'y';
125  
126 ##### Private data
127  
128 no strict 'refs';
129 my %replynames = map { &{$_} => $_ } qw(
130 SMFIR_ADDRCPT
131 SMFIR_DELRCPT
132 SMFIR_ADDRCPT_PAR
133 SMFIR_ACCEPT
134 SMFIR_REPLBODY
135 SMFIR_CONTINUE
136 SMFIR_DISCARD
137 SMFIR_ADDHEADER
138 SMFIR_INSHEADER
139 SMFIR_SETSYMLIST
140 SMFIR_CHGHEADER
141 SMFIR_PROGRESS
142 SMFIR_QUARANTINE
143 SMFIR_REJECT
144 SMFIR_CHGFROM
145 SMFIR_TEMPFAIL
146 SMFIR_REPLYCODE
147 );
148 use strict 'refs';
149  
150 ##### Constructor, main loop, and internal calls
151  
152 sub new ($$$$$) {
153 my $this = bless {}, shift;
154 # The means of communicating with the MTA.
155 $this->{socket} = shift;
156 # A hash containing $key,$value pairs where $value is a reference to a
157 # callback sub in the milter e.g. \&xm_connect_callback and $key is a
158 # name for the callback (as passed to sub call_hooks below), e.g. 'connect'.
159 my $callbacks = $this->{callbacks} = shift;
160 # The capabilities we're going to request from the MTA.
161 $this->{callback_flags} = shift;
162 # The protocol version we're going to be using. Probably 6, could be 2.
163 $this->{'milter protocol version'} = shift;
164  
165 # Making the wild assumption that we're using a recent Sendmail version, offer to the milter all 'protocol' bits set.
166 $this->{protocol} = SMFI_CURR_PROT; # 0x001FFFFF
167 # Also all possible data chunk size bits. Two are available in milter protocol version 6.
168 $this->{protocol} |= SMFIP_MDS_256K; # 0x10000000 MILTER_MAX_DATA_SIZE=262143 bytes.
169 $this->{protocol} |= SMFIP_MDS_1M; # 0x20000000 MILTER_MAX_DATA_SIZE=1048575 bytes.
170  
171 $this;
172 }
173  
174 sub main ($) {
175 my $this = shift;
176 my $socket = $this->{socket} || return undef;
177  
178 my $buf = '';
179 my $gotquit = 0;
180  
181 my $split_buf = sub {
182 $buf =~ s/\0$//; # remove trailing NUL
183 return [ split(/\0/, $buf) ];
184 };
185  
186 $socket->autoflush(1);
187  
188 $this->{lastsymbol} = '';
189  
190 #my $time_now = localtime;
191  
192 eval {
193  
194 #$time_now = localtime;
195 #printf( "%s PID=%d Context.pm(%3d): main(eval): entered eval, about to enter main loop.\n", $time_now, $$, __LINE__ );
196 while (1) {
197 #$time_now = localtime;
198 #printf( "%s PID=%d Context.pm(%3d): main(eval): top of main loop\n", $time_now, $$, __LINE__ );
199 # Loop, reading packets 'from the wire' into $buf and then extracting the commands and any data from them.
200 # Note that commands are known by the symbolic constants 'SMFIC_something'. There are 14 of these commands;
201 # all are listed in the 'Commands' section under 'Protocol constants' above. Correspondigly the responses
202 # are known by symbolic constants 'SMFIR_something'. The 17 possible responses are listed in the 'Responses'
203 # section under 'Protocol data' above. There is just one little wrinkle in all this; the (success) response
204 # to the 'SMFIC_OPTNEG' command is also 'SMFIC_OPTNEG'. There is no 'SMFIR_OPTNEG' response defined.
205 $this->read_block(\$buf, 4) || last;
206 my $len = unpack('N', $buf);
207  
208 die "bad packet length $len\n" if ($len <= 0);
209  
210 # save the overhead of stripping the first byte from $buf
211 $this->read_block(\$buf, 1) || last;
212 my $cmd = $buf;
213  
214 #$time_now = localtime;
215 #printf( "%s PID=%d Context.pm(%3d): main(eval): got command=[%s]\n", $time_now, $$, __LINE__, $cmd );
216  
217 # get actual data
218 $this->read_block(\$buf, $len - 1) || die "EOF in stream\n";
219  
220 if ($cmd eq SMFIC_ABORT) {
221 delete $this->{symbols}{&SMFIC_MAIL};
222 $this->call_hooks('abort');
223 } elsif ($cmd eq SMFIC_BODY) {
224 $this->call_hooks('body', $buf, length($buf));
225 } elsif ($cmd eq SMFIC_CONNECT) {
226 # Perl RE doesn't like matching multiple \0 instances.
227 # To avoid problems, we slice the string to the first null,
228 # then use unpack for the rest.
229 unless ($buf =~ s/^([^\0]*)\0(.)//) {
230 die "SMFIC_CONNECT: invalid connect info\n";
231 # XXX should print a hexdump here?
232 }
233  
234 my $host = $1;
235 my $af = $2;
236 my ($port, $addr) = unpack('nZ*', $buf);
237 my $pack; # default undef
238  
239 if ($af eq SMFIA_INET) {
240 $pack = pack_sockaddr_in($port, inet_aton($addr));
241 } elsif ($af eq SMFIA_INET6) {
242 $pack = eval {
243 require Socket6;
244 $addr =~ s/^IPv6://;
245 Socket6::pack_sockaddr_in6($port,
246 Socket6::inet_pton(&Socket6::AF_INET6, $addr));
247 };
248 } elsif ($af eq SMFIA_UNIX) {
249 $pack = eval {
250 sockaddr_un($addr);
251 };
252 }
253 $this->call_hooks('connect', $host, $pack);
254 } elsif ($cmd eq SMFIC_MACRO) {
255 die "SMFIC_MACRO: empty packet\n" unless ($buf =~ s/^(.)//);
256 my $code = $this->{lastsymbol} = $1;
257 my $marray = &$split_buf;
258  
259 # odd number of entries: give last empty value
260 push(@$marray, '') if ((@$marray & 1) != 0);
261  
262 my %macros = @$marray;
263  
264 while (my ($name, $value) = each(%macros)) {
265 $this->{symbols}{$code}{$name} = $value;
266 }
267 } elsif ($cmd eq SMFIC_BODYEOB) {
268 $this->call_hooks('eom');
269 } elsif ($cmd eq SMFIC_HELO) {
270 my $helo = &$split_buf;
271 die "SMFIC_HELO: bad packet\n" unless (@$helo == 1);
272 $this->call_hooks('helo', @$helo);
273 } elsif ($cmd eq SMFIC_HEADER) {
274 my $header = &$split_buf;
275 # empty value: ensure an empty string
276 push(@$header, '') if (@$header == 1);
277 $this->call_hooks('header', @$header);
278 } elsif ($cmd eq SMFIC_MAIL) {
279 if ($this->{lastsymbol} ne SMFIC_MAIL) { delete $this->{symbols}{&SMFIC_MAIL}; }
280 my $envfrom = &$split_buf;
281 # null sender MAIL FROM:<> yields an empty arg list; ensure the
282 # envfrom hook still fires (and a reply is sent) instead of hanging.
283 push(@$envfrom, q{}) if (@$envfrom == 0);
284 $this->call_hooks(q{envfrom}, @$envfrom);
285 } elsif ($cmd eq SMFIC_EOH) {
286 $this->call_hooks('eoh');
287 } elsif ($cmd eq SMFIC_OPTNEG) {
288  
289 # Here we've established that the 'NEGOTIATE' command (SMFIC_OPTNEG) has been received in the incoming packet from the MTA.
290 # If it happens at all, the negotiation step should happen once (and only once) at the beginning of a connection.
291  
292 # Bleat about the packet size if it's not what's expected, perhaps somebody has, er, 'improved' the MTA.
293 # The expected size (including the command byte that we've already stripped off) is 13, so we
294 # expect 12 bytes to remain in the packet buffer $buf. Add 1 to the size and test for != 13.
295 my $packet_size = length( $buf ) + 1;
296 if( $packet_size != 13 ) {die "SMFIC_OPTNEG: unsupported packet size $packet_size\n"; }
297 # Extract the integers from the buffer into the @negotiate array.
298 my @negotiate = unpack( 'NNN', $buf ); # Three 32-bit numbers of four bytes each.
299 my $arraysize = scalar( @negotiate );
300 if( $arraysize != 3 ) { die "SMFIC_OPTNEG: bad packet: expected 3 integer values, found $arraysize.\n"; }
301 # Named scalars for clarity, could as easily have used the array elements themselves.
302 my $milter_protocol_version = $negotiate[0];
303 my $actions_available = $negotiate[1];
304 my $protocol_steps_available = $negotiate[2];
305  
306 $this->{'milter_protocol_version_ref'} # 6. We hope. Later we may insist.
307 = \$milter_protocol_version; #
308 $this->{'actions_available_ref'} # 1FF. We hope. Later we may insist.
309 = \$actions_available; # $actions_available contains an integer consisting of bits which flag various protocol capabilities ('actions' in Sendmail parlance) available from the MTA.
310 # These are things which the milter can ask the MTA to do to the message, such as add a message header (milters very commonly add headers) or replace the message body.
311 # Symbolic constants for these bits are all SMFIF_something. Over the years,the list of available actions has been extended as Sendmail has developed, and a 'version'
312 # of the milter protocol - a single digit - is implied by the state of development of the milter protocol (i.e. the capabilities which are available) in any particular
313 # version of Sendmail. Milter protocol Version 6 was introduced by Sendmail 8.14.0 in January 2007, and as of 2019 only versions of Sendmail which support this milter
314 # protocol version are in widespread use. For security reasons alone you probably should not be using older versions of Sendmail which do not support milter protocol
315 # version 6, but other MTAs may not support all the V6 capabilities so it is probably best to check their availability in your milter before attempting to use them.
316 # The available protocol actions, symbolic constants, and the corresponding bit values for the flags are:
317 # Action Symbolic constant Value Available in milter protocol version. There's a bit of a muddle about V3, but nobody's using it any more.
318 # - SMFIF_NONE 0x0000
319 # Add header SMFIF_ADDHDRS 0x0001 V1 A message header can be added at the end of the message headers, or inserted at a specified position.
320 # Replace body SMFIF_CHGBODY 0x0002 V2 The message body can be replaced.
321 # Add recipient SMFIF_ADDRCPT 0x0004 V1 A recipient can be added. ESMTP arguments cannot be included (see SMFIF_ADDRCPT_PAR below).
322 # Delete recipient SMFIF_DELRCPT 0x0008 V1 A recipient can be deleted.
323 # Change header SMFIF_CHGHDRS 0x0010 V2 A header can be modified.
324 # Replace body SMFIF_MODBODY == SMFIF_CHGBODY Historical - Milter Protocol V1 - exists for backward compatibility, do not use in new code.
325 # Quarantine message SMFIF_QUARANTINE 0x0020 V2 The MTA will not deliver the message, but instead place it in a holding area.
326 # Change envelope from SMFIF_CHGFROM 0x0040 V6 The sender (and ESMTP arguments) given by the client in the "MAIL FROM" command can be replaced.
327 # Add recipient + args SMFIF_ADDRCPT_PAR 0x0080 V6 A recipient (such as may have been received in a client "RCPT TO" command with ESMTP arguments) can be added.
328 # Request macro values SMFIF_SETSYMLIST 0x0100 V6 The MTA can provide a list of macros valid for a given protocol 'step'. See below for the protocol steps.
329 #
330 $this->{'protocol_steps_available_ref'} # 1FFFFF. We hope - later, we may even insist.
331 = \$protocol_steps_available; # $protocol_steps_available contains an integer consisting of bits which refer to four different types of configurable behaviour.
332 # Symbolic constants for these bits are all SMFIP_something. The first three of the four configuration types affect the protocol
333 # and are listed below in the same order as they are listed in the libmilter source (see st_optionneg() in libmilter/engine.c).
334 # A fourth type which is not related to protocol steps, and is not mentioned in that list, is included here for completness.
335 # Note that the positions of these bits in the integer are not significant - they merely reflect Sendmail development history.
336 # 1. The MTA offers to the milter the option for the milter to ask the MTA not to send a particular protocol step command to run one of the callbacks.
337 # The request may be made even if a callback for that step is defined in the milter, and has been 'hooked' by the MTA at startup.
338 # Symbolic constants for these bits are all SMFIP_NOsomething. There are NINE of these "Do not send protocol step command" features.
339 # The protocol step commands, symbolic constants, and the corresponding bits in this integer are:
340 # Step Symbolic constant Value Available in milter protocol version. There's a bit of a muddle about V3, but nobody's using it any more.
341 # CONNECT SMFIP_NOCONNECT 0x00000001 V1 It's difficult to imagine a milter not wanting to know that a connection has been made, but there you are.
342 # HELO SMFIP_NOHELO 0x00000002
343 # MAIL FROM SMFIP_NOMAIL 0x00000004
344 # RCPT TO SMFIP_NORCPT 0x00000008
345 # DATA SMFIP_NODATA 0x00000200
346 # HEADER SMFIP_NOHDRS 0x00000020
347 # EOH SMFIP_NOEOH 0x00000040
348 # BODY SMFIP_NOBODY 0x00000010
349 # UNKNOWN COMMAND SMFIP_NOUNKNOWN 0x00000100
350 # 2. The MTA understands if the milter requests certain additional features in the protocol.
351 # There are THREE of these features.
352 # Symbolic constants for these bits have, like the corresponding protocol features, nothing in common beyond the SMFIP_ prefix.
353 # The protocol step commands, the symbolic constants, and the corresponding bits are:
354 # SKIP SMFIP_SKIP 0x00000400 The MTA understands the 'SKIP' command, see Sendmail's libmilter documentation.
355 # SEND REJECTED RECIPIENT SMFIP_RCPT_REJ 0x00000800 The MTA should send the SMFIC_MAIL command even if the MTA has already decided to reject it as e.g. unknown.
356 # This will take effect only if Sendmail has been compiled with _FFR_MILTER_CHECK_REJECTIONS_TOO.
357 # HEADER LEADING SPACE SMFIP_HDR_LEADSPC 0x00100000 The MTA will not add leading spaces to header values, the milter must do that. See the Sendmail documentation.
358 # 3. The MTA will by prior negotiation permit the milter to make no reply to the MTA after a given individual milter callback has been run in response to an MTA command.
359 # Symbolic constants for these bits are all SMFIP_NR_something. There are NINE of these 'SEND NO REPLY' features.
360 # If the MTA and milter agree that the milter will not to send a reply to the MTA at a particular protocol step, it MUST NOT reply to that step.
361 # The protocol step 'NO REPLY' commands, the symbolic constants, and the corresponding bits are:
362 # No reply for CONNECT SMFIP_NR_CONN 0x00001000
363 # No reply for HELO SMFIP_NR_HELO 0x00002000
364 # No reply for MAIL SMFIP_NR_MAIL 0x00004000
365 # No reply for RCPT SMFIP_NR_RCPT 0x00008000
366 # No reply for DATA SMFIP_NR_DATA 0x00010000
367 # No reply for HEADER SMFIP_NR_HDR 0x00000080
368 # No reply for HEADER SMFIP_NOHREPL == SMFIP_NR_HDR Historical - exists for backward compatibility, do not use in new code.
369 # No reply for EOH SMFIP_NR_EOH 0x00040000
370 # No reply for BODY SMFIP_NR_BODY 0x00080000
371 # No reply for UNKNOWN SMFIP_NR_UNKN 0x00020000 An unknown command received from the client which is attempting to send mail.
372 # 4. The MTA offers to the milter the ability to use a data buffer larger than the default 65535 bytes.
373 # Here be dragons. The facility is not available in default Sendmail builds, it must be compiled with at least _FFR_MDS_NEGOTIATE to make use of this facility.
374 # Max data size 256K SMFIP_MDS_256K 0x10000000 262143 bytes.
375 # Max data size 1M SMFIP_MDS_1M 0x20000000 1048575 bytes. No sizes other than the three given are permitted.
376  
377 if( ${$this->{'milter_protocol_version_ref'}} != 2 && ${$this->{'milter_protocol_version_ref'}} != 6) { die "SMFIC_OPTNEG: unsupported milter protocol version " . ${$this->{'milter_protocol_version_ref'}} . "\n"; }
378  
379 # Next we call the milter's 'negotiate' callback, if there is one, via the 'call_hooks' sub. The 'call_hooks' sub is defined about 78 lines below in this file.
380 # The 'call_hooks' sub returns to the MTA a packet which contains (subject to translation of some symbolic constants) whatever the milter callback returned.
381 # The 'call_hooks' sub will unpack that packet into the three class variables $this->{'something_ref'} (where 'something' is one of 'milter_protocol_version', 'actions_available' and 'protocol_steps_available').
382 my @negotiate_refs = ();
383 if( ! defined $this->{callbacks}{'negotiate'} )
384 { # Default protocol steps if no negotiate callback registered.
385 ${$this->{'protocol_steps_available_ref'}} &= SMFIP_DEFAULTS;
386 }
387 push( @negotiate_refs, $this->{'milter_protocol_version_ref'}, $this->{'actions_available_ref'}, $this->{'protocol_steps_available_ref'} );
388 $this->call_hooks('negotiate', @negotiate_refs);
389  
390 } elsif ($cmd eq SMFIC_RCPT) {
391 my $envrcpt = &$split_buf;
392 $this->call_hooks('envrcpt', @$envrcpt)
393 if scalar @$envrcpt >= 1;
394 delete $this->{symbols}{&SMFIC_RCPT};
395  
396 } elsif ($cmd eq SMFIC_DATA) {
397 $this->call_hooks('data');
398 } elsif ($cmd eq SMFIC_QUIT) {
399 $this->call_hooks('quit'); # A long-felt want, but I'm not sure it will really do what I want. Is it called if the client does *not* send the 'QUIT' command?
400 last;
401 # that's all, folks!
402 } elsif ($cmd eq SMFIC_UNKNOWN) {
403 # This is not an unknown packet, but a packet to tell the milter that an unknown smtp command has been received.
404 # The argument passed to the milter is the unknown command plus any arguments there may have been, both of which can be null so we don't count arguments.
405 my $unknown = &$split_buf;
406 $this->call_hooks('unknown', @$unknown );
407 } else {
408 die "unknown milter packet type $cmd\n";
409 }
410 }
411  
412 #$time_now = localtime;
413 #printf( "%s PID=%d Context.pm(%3d): main: exited main loop.\n", $time_now, $$, __LINE__ );
414  
415 };
416  
417 my $err = $@;
418  
419 #$time_now = localtime;
420 #printf( "%s PID=%d Context.pm(%3d): main: exited eval, err=[%s], about to call 'close' callback.\n", $time_now, $$, __LINE__, $err );
421  
422 $this->call_hooks('close');
423  
424 # XXX better error handling? die here to let an eval further up get it?
425 if ($err) {
426 $this->write_packet(SMFIR_TEMPFAIL) if defined($socket);
427 #$time_now = localtime;
428 #printf( "%s PID=%d Context.pm(%3d): main: error found at loop exit: [%s]\n", $time_now, $$, __LINE__, $err );
429 warn $err;
430 die $err;
431 } else {
432 $this->write_packet(SMFIR_CONTINUE) if defined($socket);
433 }
434  
435 #$time_now = localtime;
436 #printf( "%s PID=%d Context.pm(%3d): main: exit.\n", $time_now, $$, __LINE__ );
437 undef;
438 }
439  
440 sub read_block {
441 my $this = shift;
442 my $bufref = shift;
443 my $len = shift;
444  
445 my $socket = $this->{socket};
446 my $sofar = 0;
447  
448 $$bufref = '';
449  
450 while ($len > $sofar) {
451 my $read = $socket->sysread($$bufref, $len - $sofar, $sofar);
452 return undef if (!defined($read) || $read <= 0); # if EOF
453 $sofar += $read;
454 }
455 1;
456 }
457  
458 sub write_packet {
459 my $this = shift;
460 my $code = shift;
461 my $out = shift;
462 $out = '' unless defined($out);
463 my $len = pack('N', length($out) + 1);
464 my $socket = $this->{socket};
465 $socket->syswrite($len);
466 $socket->syswrite($code);
467 $socket->syswrite($out);
468 return length($code) + length($out); # XXXX
469 }
470  
471 sub call_hooks ($$;@) {
472 my $this = shift;
473 my $what = $this->{cb} = shift;
474  
475 #my $time_now = localtime;
476 #printf( "%s PID=%d Context.pm(%3d): call_hooks: callback=[%s]\n", $time_now, $$, __LINE__, $what );
477  
478 my $rc = SMFIS_CONTINUE; # SMFIS_CONTINUE is the default behaviour if no callback is defined.
479 my $sub = $this->{callbacks}{$what};
480 #$time_now = localtime;
481 if( defined($sub) )
482 {
483 $rc = SMFIS_TEMPFAIL; # 2023.03.11: Without this assignment we would accept messages if the milter bombs out with some dumb Perl error. Under these circumstances I'd rather TEMPFAIL. Configuration?
484 #printf( "%s PID=%d Context.pm(%3d): call_hooks: about to call callback=[%s], rc=[%s]\n", $time_now, $$, __LINE__, $what, $rc );
485 $rc = &$sub($this, @_);
486 #$time_now = localtime;
487 #printf( "%s PID=%d Context.pm(%3d): call_hooks: after calling callback=[%s], rc=[%s]\n", $time_now, $$, __LINE__, $what, $rc );
488 }
489 else
490 {
491 #printf( "%s PID=%d Context.pm(%3d): call_hooks: (non-existent callback=[%s])\n", $time_now, $$, __LINE__, $what );
492 }
493  
494 # translate to response codes
495 if ($rc eq SMFIS_CONTINUE) {
496 $rc = SMFIR_CONTINUE;
497 } elsif ($rc eq SMFIS_ACCEPT) {
498 $rc = SMFIR_ACCEPT;
499 } elsif ($rc eq SMFIS_DISCARD) {
500 $rc = SMFIR_DISCARD;
501 } elsif ($rc eq SMFIS_REJECT) {
502 if (defined($this->{reply})) {
503 $rc = SMFIR_REPLYCODE;
504 } else {
505 $rc = SMFIR_REJECT;
506 }
507 } elsif ($rc eq SMFIS_TEMPFAIL) {
508 if (defined($this->{reply})) {
509 $rc = SMFIR_REPLYCODE;
510 } else {
511 $rc = SMFIR_TEMPFAIL;
512 }
513 } else {
514 die "invalid callback return $rc"; # XXXX Need to handle SMFIF_ALL_OPTS
515 }
516  
517 my $len = 0;
518 #$time_now = localtime;
519  
520 if( $what eq 'negotiate' )
521 {
522 $this->{protocol} = ${$this->{'protocol_steps_available_ref'}};
523 #printf( "%s PID=%d Context.pm(%3d): call_hooks: calling write_packet at [%s] callback, rc=[%s]\n", $time_now, $$, __LINE__, $what, $rc );
524 #print Dumper($this->{symbols})."\n";
525 $len = $this->write_packet
526 (
527 SMFIC_OPTNEG,
528 pack(
529 'NNN',
530 ${$this->{'milter_protocol_version_ref'}},
531 ${$this->{'actions_available_ref'}},
532 $this->{'protocol'}
533 )
534 );
535 }
536 elsif( $what eq 'abort' ) { ; } # According to the Sendmail docs the abort callback reply is ignored.
537 elsif( $rc ne SMFIR_REPLYCODE || $what eq 'close' )
538 {
539 #printf( "%s PID=%d Context.pm(%3d): call_hooks: calling write_packet at [%s] callback, rc=[%s]\n", $time_now, $$, __LINE__, $what, $rc );
540 ##printf( "%s Context.pm(%3d): call_hooks: calling write_packet at [%s] callback, rc=[%s] (symval{'_'}=[%s])\n", $time_now, __LINE__, $what, $rc, $this->{symbols}{SMFIC_CONNECT}{'_'}//'null' );
541 #print Dumper($this->{symbols})."\n";
542 $len = $this->write_packet($rc);
543 }
544 else
545 {
546 #printf( "%s PID=%d Context.pm(%3d): call_hooks: calling write_packet at [%s] callback, rc=[%s]\n", $time_now, $$, __LINE__, $what, $rc );
547 #print Dumper($this->{symbols})."\n";
548 $len = $this->write_packet($rc, $this->{reply}."\0");
549 }
550 #$time_now = localtime;
551 #printf( "%s PID=%d Context.pm(%3d): call_hooks: packet length written=[%2d]\n", $time_now, $$, __LINE__, $len );
552 undef $this->{reply};
553 }
554  
555 ##### General methods
556  
557 =pod
558  
559 =over 4
560  
561 =item $ctx->getpriv
562  
563 Returns the private data object for this milter instance, set by
564 $ctx->setpriv() (see below). Returns undef if setpriv has never been called
565 by this milter instance.
566  
567 =cut
568  
569 sub getpriv ($) {
570 my $this = shift;
571  
572 $this->{priv};
573 }
574  
575 =pod
576  
577 =item $ctx->getsymval(NAME)
578  
579 (The word 'macro' in Sendmail parlance refers to named variables which are
580 essentially text strings. They can be defined by the MTA, and populated as
581 messages are processed, or by milters, or by the MTA's configuration files.)
582  
583 The getsymval method retrieves the macro symbol named NAME from the macros
584 available from the MTA for the current callback. NAME is either a one-
585 character macro name, or a multi-character name enclosed in {curly braces}.
586 If macro NAME is undefined when getsymval is called, it returns undef.
587  
588 Some common macros are given below. The milter protocol was first
589 implemented in the Sendmail MTA, so these macro names are those used by
590 Sendmail itself; other MTAs e.g. Postfix may provide similar macros.
591  
592 =over 2
593  
594 =item $ctx->getsymval('_')
595  
596 The remote host name and address, in standard SMTP "name [address]" form.
597  
598 =item $ctx->getsymval('i')
599  
600 The MTA's queue ID for the current message.
601  
602 =item $ctx->getsymval('j')
603  
604 The MTA's idea of local host name.
605  
606 =item $ctx->getsymval('{if_addr}')
607  
608 The local address of the network interface upon which the connection was
609 received.
610  
611 =item $ctx->getsymval('{if_name}')
612  
613 The local hostname of the network interface upon which the connection was
614 received.
615  
616 =item $ctx->getsymval('{mail_addr}')
617  
618 The MAIL FROM: sender's address, canonicalized and angle bracket stripped.
619 (This is typically not the same value as the second argument to the
620 "envfrom" callback.) Will be defined to the empty string '' if the client
621 issued a MAIL FROM:<> null return path command.
622  
623 =item $ctx->getsymval('{rcpt_addr}')
624  
625 The RCPT TO: recipient's address, canonicalized and angle bracket stripped.
626 (This is typically not the same value as the second argument to the
627 "envrcpt" callback.)
628  
629 =back
630  
631 Not all macros may be available at all times. Some macros are only
632 available after a specific phase is reached, and some macros may only
633 be available from certain MTA implementations. Check returned values
634 for 'undef'. This version of the Sendmail::PMilter package collects
635 macro values only for the following callbacks:
636  
637 CONNECT
638 HELO
639 ENVFROM
640 ENVRCPT
641 DATA
642 EOH
643 EOM
644  
645 =cut
646  
647 sub getsymval ($$) {
648 my $this = shift;
649 my $key = shift;
650 foreach my $code (SMFIC_CONNECT, SMFIC_HELO, SMFIC_MAIL, SMFIC_RCPT, SMFIC_DATA, SMFIC_EOH, SMFIC_BODYEOB)
651 {
652 my $val = $this->{symbols}{$code}{$key};
653 if( defined $val ) { return $val; }
654 }
655 undef;
656 }
657  
658 =pod
659  
660 =item $ctx->setpriv(DATA)
661  
662 This is the place to store milter-private data that is sensitive to the
663 current SMTP client connection. Only one value can be stored, so typically
664 an arrayref or hashref is initialized in the "connect" callback and set with
665 $ctx->setpriv.
666  
667 This value can be retrieved on subsequent callback runs with $ctx->getpriv.
668  
669 =cut
670  
671 sub setpriv ($$) {
672 my $this = shift;
673 $this->{priv} = shift;
674 1;
675 }
676  
677 =pod
678  
679 =item $ctx->setreply(RCODE, XCODE, MESSAGE)
680  
681 Set an extended SMTP status reply (before returning SMFIS_REJECT or
682 SMFIS_TEMPFAIL). RCODE should be a short (4xx or 5xx) numeric reply
683 code, XCODE should be a long ('4.x.y' or '5.x.y') ESMTP reply code.
684 The first digit of RCODE must be the same as the first digit of XCODE.
685 There is no such restriction on the other digits. In RCODE and XCODE,
686 'x' should be one decimal digit; in XCODE 'y' should be either one or
687 two decimal digits. MESSAGE is the full text of the message to send.
688 Refer to the appropriate RFCs for actual codes and suggested messages.
689 Examples:
690  
691 $ctx->setreply(451, '4.7.0', 'Cannot authenticate you right now');
692 return SMFIS_TEMPFAIL;
693  
694 $ctx->setreply(550, '5.7.26', 'Multiple authentication failures');
695 return SMFIS_REJECT;
696  
697 Note that after setting a reply with this method, the SMTP result code
698 comes from RCODE, not from the symbolic constants SMFIS_REJECT and
699 SMFIS_TEMPFAIL. However for consistency, callbacks that set a 4xx
700 response code should use SMFIS_TEMPFAIL, and those that set a 5xx code
701 should return SMFIS_REJECT.
702  
703 Returns 1 on success, undef on failure. In the case of failure, which
704 is typically only caused by bad parameters, a generic message will be
705 sent based on the SMFIS_* return code.
706  
707 =cut
708  
709 sub setreply ($$$$) {
710 my $this = shift;
711 my $rcode = shift || '';
712 my $xcode = shift || '';
713 my $message = shift || '';
714  
715 if ($rcode !~ /^[45]\d\d$/ || $xcode !~ /^[45]\.\d\.\d{1,2}$/ || substr($rcode, 0, 1) ne substr($xcode, 0, 1)) {
716 warn 'setreply: bad reply arguments';
717 return undef;
718 }
719  
720 $this->{reply} = "$rcode $xcode $message";
721 1;
722 }
723  
724 =pod
725  
726 =item $ctx->setmlreply(RCODE, XCODE, MESSAGES)
727  
728 Set an extended SMTP status reply (before returning SMFIS_REJECT or
729 SMFIS_TEMPFAIL). See setreply() above for more information about the
730 reply codes RCODE and XCODE. MESSAGES is an array which contains a
731 multi-line reply. This array must contain no less than two string
732 elements. Sendmail dictates that it must contain no more than 32
733 elements, and that each string element must contain no more than 980
734 characters (although any of the strings may be NULL), and no string
735 may contain a newline ("\n") or a carriage return ("\r") character.
736  
737 Example:
738  
739 $ctx->setmlreply(451, '4.7.0', \('Cannot authenticate sender.',
740 'Please refer to our published policies at',
741 'http://www.example.com/policies')
742 );
743 return SMFIS_TEMPFAIL;
744  
745 Note that after setting a reply with this method, the SMTP result code
746 comes from RCODE, not from the symbolic constants SMFIS_REJECT and
747 SMFIS_TEMPFAIL. However for consistency, callbacks that set a 4xx
748 response code should use SMFIS_TEMPFAIL, and those that set a 5xx code
749 should return SMFIS_REJECT.
750  
751 Returns 1 on success, undef on failure. In the case of failure, which
752 is typically caused by bad parameters, a generic message will be sent
753 based on the SMFIS_* return code.
754  
755 =cut
756  
757 # See Sendmail::PMilter and .../libmilter/smfi.c in the Sendmail
758 # source for MAXREPLIES and MAXREPLYLEN.
759  
760 sub setmlreply ($$$$) {
761 my $this = shift;
762 my $rcode = shift || '';
763 my $xcode = shift || '';
764 my $messageref = shift || '';
765 if
766 (
767 ref( $messageref ) ne 'ARRAY' ||
768 $rcode !~ /^[45]\d\d$/ ||
769 $xcode !~ /^[45]\.\d\.\d{1,2}$/ ||
770 substr($rcode, 0, 1) ne substr($xcode, 0, 1) ||
771 @{$messageref} < 2 ||
772 @{$messageref} > MAXREPLIES
773 )
774 {
775 warn 'setmlreply: bad reply arguments';
776 return undef;
777 }
778 my $message = $rcode . '-' . $xcode . ' '; # Admittedly this is a bit willful.
779 foreach( @{$messageref} )
780 {
781 if( /[\r\n]/ ) # Sendmail does not allow these characters in the reply strings.
782 {
783 warn 'setmlreply: bad reply arguments';
784 return undef;
785 }
786 $message .= "\r\n" . $rcode . '-' . $xcode . ' ' . $_;
787 }
788 $message .= "\r\n" . $rcode . ' ' . $xcode . ' ';
789 $this->{reply} = $message;
790 1;
791 }
792  
793 =item $ctx->shutdown()
794  
795 A special case of C<< $ctx->setreply() >> which sets the short numeric reply
796 code to 421 and the ESMTP code to 4.7.0. Under Sendmail 8.13 and higher
797 (and you should not be using any version of Sendmail older than that),
798 this will close the MTA's communication channel quickly, which should
799 immediately result in a "close" callback and end of milter execution.
800  
801 Returns 1.
802  
803 =cut
804  
805 sub shutdown ($) {
806 my $this = shift;
807 $this->setreply(421, '4.7.0', 'Closing communications channel');
808 1;
809 }
810  
811 ##### Protocol action methods
812  
813 =pod
814  
815 =item $ctx->addheader(HEADER, VALUE)
816  
817 Add header HEADER with value VALUE to this mail. Does not change any
818 existing headers with the same name. Only callable from the "eom" callback.
819  
820 Returns 1 on success, undef on failure.
821  
822 =cut
823  
824 sub addheader ($$$) {
825 my $this = shift;
826 my $header = shift || die "addheader: no header name\n";
827 my $value = shift;
828 die "addheader: called outside of EOM\n" if ($this->{cb} ne 'eom');
829 die "addheader: SMFIF_ADDHDRS not in capability list\n" unless ($this->{callback_flags} & SMFIF_ADDHDRS);
830 die "addheader: no header value\n" unless defined $value;
831  
832 $this->write_packet(SMFIR_ADDHEADER, "$header\0$value\0");
833 1;
834 }
835  
836 =pod
837  
838 =item $ctx->insheader(HEADER, VALUE, POSITION)
839  
840 Insert header HEADER at position POSITION with value VALUE to this mail.
841 Does not change any existing headers with the same name. Only callable
842 from the "eom" callback. HEADER and VALUE are requred, but POSITION is
843 optional. A POSITION value of zero is acceptable and is the default if
844 not supplied - this inserts the HEADER before all existing headers.
845  
846 Returns 1 on success, undef on failure.
847  
848 =cut
849  
850 sub insheader ($$$;$) {
851 my $this = shift;
852 my $header = shift || die "insheader: no header name\n";
853 my $value = shift || die "insheader: no header value\n";
854 my $position = shift;
855 if( not defined $position ) { $position = 0; }
856  
857 die "insheader: called outside of EOM\n" if ($this->{cb} ne 'eom');
858 die "addheader: SMFIF_ADDHDRS not in capability list\n" unless ($this->{callback_flags} & SMFIF_ADDHDRS);
859  
860 $this->write_packet(SMFIR_INSHEADER, pack('N',$position)."$header\0$value\0");
861 1;
862 }
863  
864 =pod
865  
866 =item $ctx->chgheader(HEADER, INDEX, VALUE)
867  
868 Change the INDEX'th header of name HEADER to the value VALUE. Only callable
869 from the "eom" callback. If INDEX exceeds the number of existing headers of
870 name HEADER, adds another header of that name.
871  
872 Returns 1 on success, undef on failure.
873  
874 =cut
875  
876 sub chgheader ($$$$) {
877 my $this = shift;
878 my $header = shift || die "chgheader: no header name\n";
879 my $num = shift || 0;
880 my $value = shift;
881  
882 $value = '' unless defined($value);
883  
884 die "chgheader: called outside of EOM\n" if ($this->{cb} ne 'eom');
885 die "chgheader: SMFIF_CHGHDRS not in capability list\n" unless ($this->{callback_flags} & SMFIF_CHGHDRS);
886  
887 $this->write_packet(SMFIR_CHGHEADER, pack('N', $num)."$header\0$value\0");
888 1;
889 }
890  
891 =pod
892  
893 =item $ctx->addrcpt(ADDRESS)
894  
895 Add address ADDRESS to the list of recipients for this mail. Only callable
896 from the "eom" callback.
897  
898 Returns 1 on success, undef on failure.
899  
900 =cut
901  
902 sub addrcpt ($$) {
903 my $this = shift;
904 my $rcpt = shift || die "addrcpt: no recipient specified\n";
905  
906 die "addrcpt: called outside of EOM\n" if ($this->{cb} ne 'eom');
907 die "addrcpt: SMFIF_ADDRCPT not in capability list\n" unless ($this->{callback_flags} & SMFIF_ADDRCPT);
908  
909 $this->write_packet(SMFIR_ADDRCPT, "$rcpt\0");
910 1;
911 }
912  
913 =pod
914  
915 =item $ctx->addrcpt_par(ADDRESS,PARAMS)
916  
917 Add an address ADDRESS and its ESMTP arguments PARAMS to the list of
918 recipients for this mail. Only callable from the "eom" callback.
919  
920 Returns 1 on success, undef on failure.
921  
922 =cut
923  
924 sub addrcpt_par ($$$) {
925 my $this = shift;
926 my $rcpt = shift || die "addrcpt: no recipient specified\n";
927 my $params = shift;
928  
929 die "addrcpt_par: called outside of EOM\n" if ($this->{cb} ne 'eom');
930 die "addrcpt_par: SMFIF_ADDRCPT_PAR not in capability list\n" unless ($this->{callback_flags} & SMFIF_ADDRCPT_PAR);
931  
932 $this->write_packet(SMFIR_ADDRCPT_PAR, "$rcpt\0");
933 1;
934 }
935  
936 =pod
937  
938 =item $ctx->delrcpt(ADDRESS)
939  
940 Remove address ADDRESS from the list of recipients for this mail. The
941 ADDRESS argument must match a prior argument to the "envrcpt" callback
942 exactly (case sensitive, and including angle brackets if present). Only
943 callable from the "eom" callback.
944  
945 Returns 1 on success, undef on failure. A success return means that
946 the command was queued for processing. It does not necessarily mean
947 that the recipient was successfully removed, that information is not
948 available from Sendmail.
949  
950 =cut
951  
952 sub delrcpt ($$) {
953 my $this = shift;
954 my $rcpt = shift || die "delrcpt: no recipient specified\n";
955  
956 die "delrcpt: called outside of EOM\n" if ($this->{cb} ne 'eom');
957 die "delrcpt: SMFIF_DELRCPT not in capability list\n" unless ($this->{callback_flags} & SMFIF_DELRCPT);
958  
959 $this->write_packet(SMFIR_DELRCPT, "$rcpt\0");
960 1;
961 }
962  
963 =pod
964  
965 =item $ctx->progress()
966  
967 Sends an asynchronous "progress" message to the MTA, to allow longer
968 than normal operations such as extensive message body scanning or a
969 deliberate delay. This command should only be issued during the EOM
970 callback, it will fail (and return undef) if called at other times.
971  
972 Returns 1 if the call is made during EOM and is permitted, else undef.
973  
974 =cut
975  
976 sub progress ($) {
977 my $this = shift;
978 die "progress: called outside of EOM\n" if ($this->{cb} ne 'eom');
979 $this->write_packet(SMFIR_PROGRESS);
980 1;
981 }
982  
983 =pod
984  
985 =item $ctx->quarantine(REASON)
986  
987 Quarantine the current message in the MTA-defined quarantine area, using
988 the given REASON as a text string describing the quarantine status. Only
989 callable from the "eom" callback.
990  
991 Returns 1 on success, undef on failure.
992  
993 This method is an extension that is not available in the standard
994 Sendmail::Milter package.
995  
996 =cut
997  
998 sub quarantine ($$) {
999 my $this = shift;
1000 my $reason = shift;
1001  
1002 die "quarantine: called outside of EOM\n" if ($this->{cb} ne 'eom');
1003 die "quarantine: SMFIF_QUARANTINE not in capability list\n" unless ($this->{callback_flags} & SMFIF_QUARANTINE);
1004  
1005 $this->write_packet(SMFIR_QUARANTINE, "$reason\0");
1006 1;
1007 }
1008  
1009 =pod
1010  
1011 =item $ctx->replacebody(BUFFER)
1012  
1013 Replace the message body with the data in BUFFER (a scalar). This method
1014 may be called multiple times, each call appending to the replacement buffer.
1015 End-of-line should be represented by CR-LF ("\r\n"). Only callable from the
1016 "eom" callback.
1017  
1018 Returns 1 on success, undef on failure.
1019  
1020 =cut
1021  
1022 sub replacebody ($$) {
1023 my $this = shift;
1024 my $chunk = shift;
1025  
1026 die "replacebody: called outside of EOM\n" if ($this->{cb} ne 'eom');
1027 die "replacebody: SMFIF_CHGBODY not in capability list\n" unless ($this->{callback_flags} & SMFIF_CHGBODY);
1028  
1029 my $len = length($chunk);
1030 my $socket = $this->{socket};
1031  
1032 $len = pack('N', ($len + 1));
1033 $socket->syswrite($len);
1034 $socket->syswrite(SMFIR_REPLBODY);
1035 $socket->syswrite($chunk);
1036 1;
1037 }
1038  
1039 =pod
1040  
1041 =item $ctx->chgfrom(ADDRESS)
1042 =item $ctx->setsender(ADDRESS) (Deprecated)
1043  
1044 Replace the envelope sender address for the given mail message.
1045  
1046 Returns 1 on success, undef on failure. Successful return means that
1047 the command was queued for processing. It does not necessarily mean
1048 that the operation was successfully completed, that information is not
1049 available from Sendmail.
1050  
1051 =cut
1052  
1053 sub chgfrom ($$) {
1054 my $this = shift;
1055 my $sender = shift || die "chgfrom: no sender specified\n";
1056  
1057 die "chgfrom: called outside of EOM\n" if ($this->{cb} ne 'eom');
1058 die "chgfrom: SMFIF_CHGFROM not in capability list\n" unless ($this->{callback_flags} & SMFIF_CHGFROM);
1059  
1060 $this->write_packet(SMFIR_CHGFROM, "$sender\0");
1061 1;
1062 }
1063  
1064 # Deprecated, may be removed from a future version with little or no warning.
1065 sub setsender ($$) {
1066 my $this = shift;
1067 my $sender = shift || die "setsender: no sender specified\n";
1068  
1069 die "setsender: called outside of EOM\n" if ($this->{cb} ne 'eom');
1070 die "setsender: SMFIF_CHGFROM not in capability list\n" unless ($this->{callback_flags} & SMFIF_CHGFROM);
1071  
1072 $this->write_packet(SMFIR_CHGFROM, "$sender\0");
1073 1;
1074 }
1075  
1076 1;
1077  
1078 __END__