# 02-Aug-92 Noah Friedman <friedman@prep.ai.mit.edu>
# Public domain.

# Args: smtphost, alias
sub expand_mail_alias
{
  local ($rhost, $username) = @_;
  local ($name, $aliases, $type, $len, $thisaddr, $rhostaddr);
  local ($proto, $child, $i, @result);

  local ($port) = 25;
  local ($sockaddr) = "S n a4 x8";

  # So we don't have to include socket.ph
  # These are probably correct, but not guaranteed to be. 
  local ($AF_INET) = 2;
  local ($SOCK_STREAM) = 1;

  local ($hostname) = `hostname`;
  chop $hostname;

  ($name, $aliases, $proto) = getprotobyname ("tcp");

  if ($port !~ /^\d+$/)
    {
      ($name, $aliases, $port) = getservbyname ($port, "tcp");
    }
      
  ($name, $aliases, $type, $len, $thisaddr) = gethostbyname ($hostname);
  ($name, $aliases, $type, $len, $rhostaddr) = gethostbyname ($rhost);

  $thishost = pack ($sockaddr, $AF_INET, 0, $thisaddr);
  $rhost    = pack ($sockaddr, $AF_INET, $port, $rhostaddr);

  # Make socket filehandle.
  socket (S, $AF_INET, $SOCK_STREAM, $proto) || die ("$0: socket: $!");

  # Give the socket an address.
  bind (S, $thishost) || die ("$0: bind: $!");

  # Connect to server.
  connect (S, $rhost) || die ("$0: connect: $!");

  # Set socket to be command buffered.
  select (S); $| = 1; select (STDOUT);

  # Avoid deadlock by forking.
  $child = fork(); 

  if ($child == 0)
    {
      # child
      print (S "expn $username\n");
      print (S "quit\n");
      close (S);
      exit (0);
    }
  else
    {
      $i = 0;
      while (<S>) 
        {
          if ($_ =~ /^250[- ]/)
            {
              s/.*<//;
              s/>.*//;
              chop;
              $result[$i] = $_;
              $i++;
            }
        }
      close (S);
    }

  return @result;
}
