Master to 4.2.8
[usit-rt.git] / bin / rt-mailgate
CommitLineData
84fb5b46
MKG
1#!/usr/bin/perl -w
2# BEGIN BPS TAGGED BLOCK {{{
3#
4# COPYRIGHT:
5#
320f0092 6# This software is Copyright (c) 1996-2014 Best Practical Solutions, LLC
84fb5b46
MKG
7# <sales@bestpractical.com>
8#
9# (Except where explicitly superseded by other copyright notices)
10#
11#
12# LICENSE:
13#
14# This work is made available to you under the terms of Version 2 of
15# the GNU General Public License. A copy of that license should have
16# been provided with this software, but in any event can be snarfed
17# from www.gnu.org.
18#
19# This work is distributed in the hope that it will be useful, but
20# WITHOUT ANY WARRANTY; without even the implied warranty of
21# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22# General Public License for more details.
23#
24# You should have received a copy of the GNU General Public License
25# along with this program; if not, write to the Free Software
26# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
27# 02110-1301 or visit their web page on the internet at
28# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
29#
30#
31# CONTRIBUTION SUBMISSION POLICY:
32#
33# (The following paragraph is not intended to limit the rights granted
34# to you to modify and distribute this software under the terms of
35# the GNU General Public License and is only of importance to you if
36# you choose to contribute your changes and enhancements to the
37# community by submitting them to Best Practical Solutions, LLC.)
38#
39# By intentionally submitting any modifications, corrections or
40# derivatives to this work, or any other work intended for use with
41# Request Tracker, to Best Practical Solutions, LLC, you confirm that
42# you are the copyright holder for those contributions and you grant
43# Best Practical Solutions, LLC a nonexclusive, worldwide, irrevocable,
44# royalty-free, perpetual, license to use, copy, create derivative
45# works based on those contributions, and sublicense and distribute
46# those contributions and any derivatives thereof.
47#
48# END BPS TAGGED BLOCK }}}
49=head1 NAME
50
51rt-mailgate - Mail interface to RT.
52
53=cut
54
55use strict;
56use warnings;
57
58use Getopt::Long;
59
60my $opts = { };
61GetOptions( $opts, "queue=s", "action=s", "url=s",
62 "jar=s", "help", "debug", "extension=s",
63 "timeout=i", "verify-ssl!", "ca-file=s",
64 );
65
66my $gateway = RT::Client::MailGateway->new();
67
68$gateway->run($opts);
69
70package RT::Client::MailGateway;
71
72use LWP::UserAgent;
73use HTTP::Request::Common qw($DYNAMIC_FILE_UPLOAD);
74use File::Temp qw(tempfile tempdir);
75$DYNAMIC_FILE_UPLOAD = 1;
76
77use constant EX_TEMPFAIL => 75;
78use constant BUFFER_SIZE => 8192;
79
80sub new {
81 my $class = shift;
82 my $self = bless {}, $class;
83 return $self;
84}
85
86sub run {
87 my $self = shift;
88 my $opts = shift;
89
90 if ( $opts->{running_in_test_harness} ) {
91 $self->{running_in_test_harness} = 1;
92 }
93
94 $self->validate_cli_flags($opts);
95
96 my $ua = $self->get_useragent($opts);
97 my $post_params = $self->setup_session($opts);
98 $self->upload_message( $ua => $post_params );
99 $self->exit_with_success();
100}
101
102sub exit_with_success {
103 my $self = shift;
104 if ( $self->{running_in_test_harness} ) {
105 return 1;
106 } else {
107 exit 0;
108 }
109}
110
111sub tempfail {
112 my $self = shift;
113 if ( $self->{running_in_test_harness} ) {
114 die "tempfail";
115 } else {
116
117 exit EX_TEMPFAIL;
118 }
119}
120
121sub permfail {
122 my $self = shift;
123 if ( $self->{running_in_test_harness} ) {
124 die "permfail";
125 } else {
126
127 exit 1;
128 }
129}
130
131sub validate_cli_flags {
132 my $self = shift;
133 my $opts = shift;
134 if ( $opts->{'help'} ) {
135 require Pod::Usage;
136 Pod::Usage::pod2usage( { verbose => 2 } );
137 return $self->permfail()
138 ; # Don't want to succeed if this is really an email!
139 }
140
141 unless ( $opts->{'url'} ) {
142 print STDERR
143 "$0 invoked improperly\n\nNo 'url' provided to mail gateway!\n";
144 return $self->permfail();
145 }
146
84fb5b46
MKG
147 $opts->{"verify-ssl"} = 1 unless defined $opts->{"verify-ssl"};
148}
149
150sub get_useragent {
151 my $self = shift;
152 my $opts = shift;
153 my $ua = LWP::UserAgent->new();
c33a4027 154 $ua->agent("rt-mailgate/4.2.8 ");
84fb5b46
MKG
155 $ua->cookie_jar( { file => $opts->{'jar'} } ) if $opts->{'jar'};
156
af59614d
MKG
157 $ua->ssl_opts( verify_hostname => $opts->{'verify-ssl'} );
158 $ua->ssl_opts( SSL_ca_file => $opts->{'ca-file'} )
159 if $opts->{'ca-file'};
84fb5b46
MKG
160
161 return $ua;
162}
163
164sub setup_session {
165 my $self = shift;
166 my $opts = shift;
167 my %post_params;
168 foreach (qw(queue action)) {
169 $post_params{$_} = $opts->{$_} if defined $opts->{$_};
170 }
171
172 if ( ( $opts->{'extension'} || '' ) =~ /^(?:action|queue|ticket)$/i ) {
173 $post_params{ lc $opts->{'extension'} } = $ENV{'EXTENSION'}
174 || $opts->{ $opts->{'extension'} };
175 } elsif ( $opts->{'extension'} && $ENV{'EXTENSION'} ) {
176 print STDERR
177 "Value of the --extension argument is not action, queue or ticket"
178 . ", but environment variable EXTENSION is also defined. The former is ignored.\n";
179 }
180
181 # add ENV{'EXTENSION'} as X-RT-MailExtension to the message header
182 if ( my $value = ( $ENV{'EXTENSION'} || $opts->{'extension'} ) ) {
183
184 # prepare value to avoid MIME format breakage
185 # strip trailing newline symbols
186 $value =~ s/(\r*\n)+$//;
187
188 # make a correct multiline header field,
189 # with tabs in the beginning of each line
190 $value =~ s/(\r*\n)/$1\t/g;
191 $opts->{'headers'} .= "X-RT-Mail-Extension: $value\n";
192 }
193
194 # Read the message in from STDIN
195 # _raw_message is used for testing
196 my $message = $opts->{'_raw_message'} || $self->slurp_message();
197 unless ( $message->{'filename'} ) {
198 $post_params{'message'} = [
199 undef, '',
200 'Content-Type' => 'application/octet-stream',
201 Content => ${ $message->{'content'} },
202 ];
203 } else {
204 $post_params{'message'} = [
205 $message->{'filename'}, '',
206 'Content-Type' => 'application/octet-stream',
207 ];
208 }
209
210 return \%post_params;
211}
212
213sub upload_message {
214 my $self = shift;
215 my $ua = shift;
216 my $post_params = shift;
217 my $full_url = $opts->{'url'} . "/REST/1.0/NoAuth/mail-gateway";
218 print STDERR "$0: connecting to $full_url\n" if $opts->{'debug'};
219
220 $ua->timeout( exists( $opts->{'timeout'} ) ? $opts->{'timeout'} : 180 );
221 my $r = $ua->post( $full_url, $post_params, Content_Type => 'form-data' );
c33a4027
MKG
222
223 # Follow 3 redirects
224 my $n = 0;
225 while ($n++ < 3 and $r->is_redirect) {
226 $full_url = $r->header( "Location" );
227 $r = $ua->post( $full_url, $post_params, Content_Type => 'form-data' );
228 }
229
84fb5b46
MKG
230 $self->check_failure($r);
231
232 my $content = $r->content;
233 print STDERR $content . "\n" if $opts->{'debug'};
234
235 return if ( $content =~ /^(ok|not ok)/ );
236
237 # It's not the server's fault if the mail is bogus. We just want to know that
238 # *something* came out of the server.
239 print STDERR <<EOF;
240RT server error.
241
242The RT server which handled your email did not behave as expected. It
243said:
244
245$content
246EOF
247
248 return $self->tempfail();
249}
250
251sub check_failure {
252 my $self = shift;
253 my $r = shift;
254 return if $r->is_success;
255
af59614d
MKG
256 print STDERR "HTTP request failed: @{[ $r->status_line ]}. "
257 ."Your webserver logs may have more information or there may be a network problem.\n";
84fb5b46
MKG
258 print STDERR "\n$0: undefined server error\n" if $opts->{'debug'};
259 return $self->tempfail();
260}
261
262sub slurp_message {
263 my $self = shift;
264
265 local $@;
266
267 my %message;
268 my ( $fh, $filename )
269 = eval { tempfile( DIR => tempdir( CLEANUP => 1 ) ) };
270 if ( !$fh || $@ ) {
271 print STDERR "$0: Couldn't create temp file, using memory\n";
272 print STDERR "error: $@\n" if $@;
273
274 my $message = \do { local ( @ARGV, $/ ); <STDIN> };
275 unless ( $$message =~ /\S/ ) {
276 print STDERR "$0: no message passed on STDIN\n";
277 $self->exit_with_success;
278 }
279 $$message = $opts->{'headers'} . $$message if $opts->{'headers'};
280 return ( { content => $message } );
281 }
282
283 binmode $fh;
284 binmode \*STDIN;
285
286 print $fh $opts->{'headers'} if $opts->{'headers'};
287
288 my $buf;
289 my $empty = 1;
290 while (1) {
291 my $status = read \*STDIN, $buf, BUFFER_SIZE;
292 unless ( defined $status ) {
293 print STDERR "$0: couldn't read message: $!\n";
294 return $self->tempfail();
295 } elsif ( !$status ) {
296 last;
297 }
298 $empty = 0 if $buf =~ /\S/;
299 print $fh $buf;
300 }
301 close $fh;
302
303 if ($empty) {
304 print STDERR "$0: no message passed on STDIN\n";
305 $self->exit_with_success;
306 }
307 print STDERR "$0: temp file is '$filename'\n" if $opts->{'debug'};
308 return ( { filename => $filename } );
309}
310
311=head1 SYNOPSIS
312
313 rt-mailgate --help : this text
314
315Usual invocation (from MTA):
316
317 rt-mailgate --action (correspond|comment|...) --queue queuename
318 --url http://your.rt.server/
319 [ --debug ]
320 [ --extension (queue|action|ticket) ]
321 [ --timeout seconds ]
322
323
324
325=head1 OPTIONS
326
327=over 3
328
329=item C<--action>
330
331Specifies what happens to email sent to this alias. The avaliable
332basic actions are: C<correspond>, C<comment>.
333
334
335If you've set the RT configuration variable B<< C<UnsafeEmailCommands> >>,
336C<take> and C<resolve> are also available. You can execute two or more
337actions on a single message using a C<-> separated list. RT will execute
338the actions in the listed order. For example you can use C<take-comment>,
339C<correspond-resolve> or C<take-comment-resolve> as actions.
340
341Note that C<take> and C<resolve> actions ignore message text if used
342alone. Include a C<comment> or C<correspond> action if you want RT
343to record the incoming message.
344
345The default action is C<correspond>.
346
347=item C<--queue>
348
349This flag determines which queue this alias should create a ticket in if no ticket identifier
350is found.
351
352=item C<--url>
353
354This flag tells the mail gateway where it can find your RT server. You should
355probably use the same URL that users use to log into RT.
356
84fb5b46
MKG
357If you have a self-signed SSL certificate, you may also need to pass
358C<--ca-file> or C<--no-verify-ssl>, below.
359
360=item C<--ca-file> I<path>
361
362Specifies the path to the public SSL certificate for the certificate
363authority that should be used to verify the website's SSL certificate.
364If your webserver uses a self-signed certificate, you should
365preferentially use this option over C<--no-verify-ssl>, as it will
366ensure that the self-signed certificate that the mailgate is seeing the
367I<right> self-signed certificate.
368
369=item C<--no-verify-ssl>
370
371This flag tells the mail gateway to trust all SSL certificates,
372regardless of if their hostname matches the certificate, and regardless
373of CA. This is required if you have a self-signed certificate, or some
374other certificate which is not traceable back to an certificate your
375system ultimitely trusts.
376
84fb5b46
MKG
377=item C<--extension> OPTIONAL
378
379Some MTAs will route mail sent to user-foo@host or user+foo@host to user@host
380and present "foo" in the environment variable $EXTENSION. By specifying
381the value "queue" for this parameter, the queue this message should be
382submitted to will be set to the value of $EXTENSION. By specifying
383"ticket", $EXTENSION will be interpreted as the id of the ticket this message
384is related to. "action" will allow the user to specify either "comment" or
385"correspond" in the address extension.
386
387=item C<--debug> OPTIONAL
388
389Print debugging output to standard error
390
391
392=item C<--timeout> OPTIONAL
393
394Configure the timeout for posting the message to the web server. The
395default timeout is 3 minutes (180 seconds).
396
397=back
398
399
400=head1 DESCRIPTION
401
402The RT mail gateway is the primary mechanism for communicating with RT
403via email. This program simply directs the email to the RT web server,
404which handles filing correspondence and sending out any required mail.
405It is designed to be run as part of the mail delivery process, either
406called directly by the MTA or C<procmail>, or in a F<.forward> or
407equivalent.
408
409=head1 SETUP
410
411Much of the set up of the mail gateway depends on your MTA and mail
c33a4027 412routing configuration.
84fb5b46 413
c33a4027 414You need to route mail to C<rt-mailgate> for the queues you're
84fb5b46
MKG
415monitoring. For instance, if you're using F</etc/aliases> and you have a
416"bugs" queue, you will want something like this:
417
418 bugs: "|/opt/rt4/bin/rt-mailgate --queue bugs --action correspond
419 --url http://rt.mycorp.com/"
420
421 bugs-comment: "|/opt/rt4/bin/rt-mailgate --queue bugs --action comment
422 --url http://rt.mycorp.com/"
423
424Note that you don't have to run your RT server on your mail server, as
425the mail gateway will happily relay to a different machine.
426
427=head1 CUSTOMIZATION
428
429By default, the mail gateway will accept mail from anyone. However,
430there are situations in which you will want to authenticate users
431before allowing them to communicate with the system. You can do this
432via a plug-in mechanism in the RT configuration.
433
434You can set the array C<@MailPlugins> to be a list of plugins. The
435default plugin, if this is not given, is C<Auth::MailFrom> - that is,
436authentication of the person is done based on the C<From> header of the
437email. If you have additional filters or authentication mechanisms, you
438can list them here and they will be called in order:
439
440 Set( @MailPlugins =>
441 "Filter::SpamAssassin",
442 "Auth::LDAP",
443 # ...
444 );
445
446See the documentation for any additional plugins you have.
447
448You may also put Perl subroutines into the C<@MailPlugins> array, if
449they behave as described below.
450
451=head1 WRITING PLUGINS
452
453What's actually going on in the above is that C<@MailPlugins> is a
454list of Perl modules; RT prepends C<RT::Interface::Email::> to the name,
455to form a package name, and then C<use>'s this module. The module is
456expected to provide a C<GetCurrentUser> subroutine, which takes a hash of
457several parameters:
458
459=over 4
460
461=item Message
462
463A C<MIME::Entity> object representing the email
464
465=item CurrentUser
466
467An C<RT::CurrentUser> object
468
469=item AuthStat
470
471The authentication level returned from the previous plugin.
472
473=item Ticket [OPTIONAL]
474
475The ticket under discussion
476
477=item Queue [OPTIONAL]
478
479If we don't already have a ticket id, we need to know which queue we're talking about
480
481=item Action
482
483The action being performed. At the moment, it's one of "comment" or "correspond"
484
485=back
486
487It returns two values, the new C<RT::CurrentUser> object, and the new
488authentication level. The authentication level can be zero, not allowed
489to communicate with RT at all, (a "permission denied" error is mailed to
490the correspondent) or one, which is the normal mode of operation.
491Additionally, if C<-1> is returned, then the processing of the plug-ins
492stops immediately and the message is ignored.
493
494=head1 ENVIRONMENT
495
496=over 4
497
498=item EXTENSION
499
500Some MTAs will route mail sent to user-foo@host or user+foo@host to user@host
501and present "foo" in the environment variable C<EXTENSION>. Mailgate adds value
502of this variable to message in the C<X-RT-Mail-Extension> field of the message
503header.
504
505See also C<--extension> option. Note that value of the environment variable is
506always added to the message header when it's not empty even if C<--extension>
507option is not provided.
508
509=back
510
511=cut
512