#!/usr/bin/perl -w
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2018 Best Practical Solutions, LLC
#                                          <sales@bestpractical.com>
#
# (Except where explicitly superseded by other copyright notices)
#
#
# LICENSE:
#
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
#
# This work is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
#
#
# CONTRIBUTION SUBMISSION POLICY:
#
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
#
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
#
# END BPS TAGGED BLOCK }}}
=head1 NAME

rt-mailgate - Mail interface to RT.

=cut

use strict;
use warnings;

use Getopt::Long;

my $opts = { };
GetOptions( $opts,   "queue=s", "action=s", "url=s",
            "jar=s", "help",    "debug",    "extension=s",
            "timeout=i", "verify-ssl!", "ca-file=s",
          );

my $gateway = RT::Client::MailGateway->new();

$gateway->run($opts);

package RT::Client::MailGateway;

use LWP::UserAgent;
use HTTP::Request::Common qw($DYNAMIC_FILE_UPLOAD);
use File::Temp qw(tempfile tempdir);
$DYNAMIC_FILE_UPLOAD = 1;

use constant EX_TEMPFAIL => 75;
use constant BUFFER_SIZE => 8192;

sub new {
    my $class = shift;
    my $self = bless {}, $class;
    return $self;
}

sub run {
    my $self = shift;
    my $opts = shift;

    if ( $opts->{running_in_test_harness} ) {
        $self->{running_in_test_harness} = 1;
    }

    $self->validate_cli_flags($opts);

    my $ua          = $self->get_useragent($opts);
    my $post_params = $self->setup_session($opts);
    $self->upload_message( $ua => $post_params );
    $self->exit_with_success();
}

sub exit_with_success {
    my $self = shift;
    if ( $self->{running_in_test_harness} ) {
        return 1;
    } else {
        exit 0;
    }
}

sub tempfail {
    my $self = shift;
    if ( $self->{running_in_test_harness} ) {
        die "tempfail";
    } else {

        exit EX_TEMPFAIL;
    }
}

sub permfail {
    my $self = shift;
    if ( $self->{running_in_test_harness} ) {
        die "permfail";
    } else {

        exit 1;
    }
}

sub validate_cli_flags {
    my $self = shift;
    my $opts = shift;
    if ( $opts->{'help'} ) {
        require Pod::Usage;
        Pod::Usage::pod2usage( { verbose => 2 } );
        return $self->permfail()
            ;    # Don't want to succeed if this is really an email!
    }

    unless ( $opts->{'url'} ) {
        print STDERR
            "$0 invoked improperly\n\nNo 'url' provided to mail gateway!\n";
        return $self->permfail();
    }

    $opts->{"verify-ssl"} = 1 unless defined $opts->{"verify-ssl"};
}

sub get_useragent {
    my $self = shift;
    my $opts = shift;
    my $ua   = LWP::UserAgent->new();
    $ua->agent("rt-mailgate/4.4.3 ");
    $ua->cookie_jar( { file => $opts->{'jar'} } ) if $opts->{'jar'};

    $ua->ssl_opts( verify_hostname => $opts->{'verify-ssl'} );
    $ua->ssl_opts( SSL_ca_file => $opts->{'ca-file'} )
        if $opts->{'ca-file'};

    return $ua;
}

sub setup_session {
    my $self = shift;
    my $opts = shift;
    my %post_params;
    foreach (qw(queue action)) {
        $post_params{$_} = $opts->{$_} if defined $opts->{$_};
    }

    if ( ( $opts->{'extension'} || '' ) =~ /^(?:action|queue|ticket)$/i ) {
        $post_params{ lc $opts->{'extension'} } = $ENV{'EXTENSION'}
            || $opts->{ $opts->{'extension'} };
    } elsif ( $opts->{'extension'} && $ENV{'EXTENSION'} ) {
        print STDERR
            "Value of the --extension argument is not action, queue or ticket"
            . ", but environment variable EXTENSION is also defined. The former is ignored.\n";
    }

    # add ENV{'EXTENSION'} as X-RT-MailExtension to the message header
    if ( my $value = ( $ENV{'EXTENSION'} || $opts->{'extension'} ) ) {

        # prepare value to avoid MIME format breakage
        # strip trailing newline symbols
        $value =~ s/(\r*\n)+$//;

        # make a correct multiline header field,
        # with tabs in the beginning of each line
        $value =~ s/(\r*\n)/$1\t/g;
        $opts->{'headers'} .= "X-RT-Mail-Extension: $value\n";
    }

    # Read the message in from STDIN
    # _raw_message is used for testing
    my $message = $opts->{'_raw_message'} || $self->slurp_message();
    unless ( $message->{'filename'} ) {
        $post_params{'message'} = [
                                 undef, '',
                                 'Content-Type' => 'application/octet-stream',
                                 Content        => ${ $message->{'content'} },
        ];
    } else {
        $post_params{'message'} = [
                                 $message->{'filename'}, '',
                                 'Content-Type' => 'application/octet-stream',
        ];
    }

    return \%post_params;
}

sub upload_message {
    my $self        = shift;
    my $ua          = shift;
    my $post_params = shift;
    my $full_url    = $opts->{'url'} . "/REST/1.0/NoAuth/mail-gateway";
    print STDERR "$0: connecting to $full_url\n" if $opts->{'debug'};

    $ua->timeout( exists( $opts->{'timeout'} ) ? $opts->{'timeout'} : 180 );
    my $r = $ua->post( $full_url, $post_params, Content_Type => 'form-data' );

    # Follow 3 redirects
    my $n = 0;
    while ($n++ < 3 and $r->is_redirect) {
        $full_url = $r->header( "Location" );
        $r = $ua->post( $full_url, $post_params, Content_Type => 'form-data' );
    }

    $self->check_failure($r);

    my $content = $r->content;
    print STDERR $content . "\n" if $opts->{'debug'};

    return if ( $content =~ /^(ok|not ok)/ );

 # It's not the server's fault if the mail is bogus. We just want to know that
 # *something* came out of the server.
    print STDERR <<EOF;
RT server error.

The RT server which handled your email did not behave as expected. It
said:

$content
EOF

    return $self->tempfail();
}

sub check_failure {
    my $self = shift;
    my $r    = shift;
    return if $r->is_success;

    print STDERR "HTTP request failed: @{[ $r->status_line ]}. "
                ."Your webserver logs may have more information or there may be a network problem.\n";
    print STDERR "\n$0: undefined server error\n" if $opts->{'debug'};
    return $self->tempfail();
}

sub slurp_message {
    my $self = shift;

    local $@;

    my %message;
    my ( $fh, $filename )
        = eval { tempfile( DIR => tempdir( CLEANUP => 1 ) ) };
    if ( !$fh || $@ ) {
        print STDERR "$0: Couldn't create temp file, using memory\n";
        print STDERR "error: $@\n" if $@;

        my $message = \do { local ( @ARGV, $/ ); <STDIN> };
        unless ( $$message =~ /\S/ ) {
            print STDERR "$0: no message passed on STDIN\n";
            $self->exit_with_success;
        }
        $$message = $opts->{'headers'} . $$message if $opts->{'headers'};
        return ( { content => $message } );
    }

    binmode $fh;
    binmode \*STDIN;

    print $fh $opts->{'headers'} if $opts->{'headers'};

    my $buf;
    my $empty = 1;
    while (1) {
        my $status = read \*STDIN, $buf, BUFFER_SIZE;
        unless ( defined $status ) {
            print STDERR "$0: couldn't read message: $!\n";
            return $self->tempfail();
        } elsif ( !$status ) {
            last;
        }
        $empty = 0 if $buf =~ /\S/;
        print $fh $buf;
    }
    close $fh;

    if ($empty) {
        print STDERR "$0: no message passed on STDIN\n";
        $self->exit_with_success;
    }
    print STDERR "$0: temp file is '$filename'\n" if $opts->{'debug'};
    return ( { filename => $filename } );
}

=head1 SYNOPSIS

    rt-mailgate --help : this text

Usual invocation (from MTA):

    rt-mailgate --action (correspond|comment|...) --queue queuename
                --url http://your.rt.server/
                [ --debug ]
                [ --extension (queue|action|ticket) ]
                [ --timeout seconds ]



=head1 OPTIONS

=over 3

=item C<--action>

Specifies what happens to email sent to this alias.  The avaliable basic
actions are: C<correspond>, C<comment>.  Additional actions, such as
C<take> or C<resolve>, may be available depending on your local
C<@MailPlugins> configuration.

You can execute two or more actions on a single message using a C<->
separated list.  RT will execute the actions in the listed order.  For
example you can use C<take-comment>, C<correspond-resolve> or
C<take-comment-resolve> as actions.

Note that C<take> and C<resolve> actions ignore message text if used
alone.  Include a  C<comment> or C<correspond> action if you want RT
to record the incoming message.

The default action is C<correspond>.

=item C<--queue>

This flag determines which queue this alias should create a ticket in if no ticket identifier
is found.

=item C<--url>

This flag tells the mail gateway where it can find your RT server. You should 
probably use the same URL that users use to log into RT.  

If you have a self-signed SSL certificate, you may also need to pass
C<--ca-file> or C<--no-verify-ssl>, below.

=item C<--ca-file> I<path>

Specifies the path to the public SSL certificate for the certificate
authority that should be used to verify the website's SSL certificate.
If your webserver uses a self-signed certificate, you should
preferentially use this option over C<--no-verify-ssl>, as it will
ensure that the self-signed certificate that the mailgate is seeing the
I<right> self-signed certificate.

=item C<--no-verify-ssl>

This flag tells the mail gateway to trust all SSL certificates,
regardless of if their hostname matches the certificate, and regardless
of CA.  This is required if you have a self-signed certificate, or some
other certificate which is not traceable back to an certificate your
system ultimitely trusts.

=item C<--extension> OPTIONAL

Some MTAs will route mail sent to user-foo@host or user+foo@host to user@host
and present "foo" in the environment variable $EXTENSION. By specifying
the value "queue" for this parameter, the queue this message should be
submitted to will be set to the value of $EXTENSION. By specifying
"ticket", $EXTENSION will be interpreted as the id of the ticket this message
is related to.  "action" will allow the user to specify either "comment" or
"correspond" in the address extension.

=item C<--debug> OPTIONAL

Print debugging output to standard error


=item C<--timeout> OPTIONAL

Configure the timeout for posting the message to the web server.  The
default timeout is 3 minutes (180 seconds).

=back


=head1 DESCRIPTION

The RT mail gateway is the primary mechanism for communicating with RT
via email. This program simply directs the email to the RT web server,
which handles filing correspondence and sending out any required mail.
It is designed to be run as part of the mail delivery process, either
called directly by the MTA or C<procmail>, or in a F<.forward> or
equivalent.

=head1 SETUP

Much of the set up of the mail gateway depends on your MTA and mail
routing configuration.

You need to route mail to C<rt-mailgate> for the queues you're
monitoring. For instance, if you're using F</etc/aliases> and you have a
"bugs" queue, you will want something like this:

    bugs:         "|/usr/local/bin/rt-mailgate --queue bugs --action correspond
              --url http://rt.mycorp.com/"

    bugs-comment: "|/usr/local/bin/rt-mailgate --queue bugs --action comment
              --url http://rt.mycorp.com/"

Note that you don't have to run your RT server on your mail server, as
the mail gateway will happily relay to a different machine.

=head1 ENVIRONMENT

=over 4

=item EXTENSION

Some MTAs will route mail sent to user-foo@host or user+foo@host to user@host
and present "foo" in the environment variable C<EXTENSION>. Mailgate adds value
of this variable to message in the C<X-RT-Mail-Extension> field of the message
header.

See also C<--extension> option. Note that value of the environment variable is
always added to the message header when it's not empty even if C<--extension>
option is not provided.

=back

=cut

