# SPDX-License-Identifier: GPL-2.0-or-later

package Amavis::UnmangleSender;
use strict;
use re 'taint';

BEGIN {
  require Exporter;
  use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $VERSION);
  $VERSION = '2.412';
  @ISA = qw(Exporter);
  @EXPORT_OK = qw(&first_received_from &oldest_public_ip_addr_from_received);
}
use subs @EXPORT_OK;

use Amavis::Conf qw(:platform c cr ca);
use Amavis::Lookup qw(lookup lookup2);
use Amavis::Lookup::IP qw(normalize_ip_addr);
use Amavis::rfc2821_2822_Tools qw(split_address parse_received fish_out_ip_from_received);
use Amavis::Util qw(ll do_log unique_list);

# Obtain and parse the first entry (oldest) in the 'Received:' header field
# path trace - to be used as the value of a macro %t in customized messages
#
sub first_received_from($) {
  my $msginfo = $_[0];
  my $first_received;
  my $fields_ref =
    parse_received($msginfo->get_header_field_body('received'));  # last
  if (exists $fields_ref->{'from'}) {
    $first_received = join(' ', unique_list(grep(defined($_),
                                  @$fields_ref{qw(from from-tcp from-com)})));
    do_log(5, "first_received_from: %s", $first_received);
  }
  $first_received;
}


# Try to extract sender's IP address from the Received trace.
# Search bottom-up, use the first public IP address from the trace.
#
sub oldest_public_ip_addr_from_received($) {
  my($msginfo) = @_;
  my $received_from_ip;
  my $ip_trace_ref = $msginfo->ip_addr_trace_public;  # top-down trace
  $received_from_ip = $ip_trace_ref->[-1]  if $ip_trace_ref;  # last is oldest
  do_log(5, "oldest_public_ip_addr_from_received: %s", $received_from_ip)
    if defined $received_from_ip;
  $received_from_ip;
}

1;
