import rt 3.8.10
[freeside.git] / rt / bin / rt-mailgate.in
1 #!@PERL@ -w
2 # BEGIN BPS TAGGED BLOCK {{{
3 #
4 # COPYRIGHT:
5 #
6 # This software is Copyright (c) 1996-2011 Best Practical Solutions, LLC
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
51 rt-mailgate - Mail interface to RT3.
52
53 =cut
54
55 use strict;
56 use warnings;
57
58 use Getopt::Long;
59 use LWP::UserAgent;
60 use HTTP::Request::Common qw($DYNAMIC_FILE_UPLOAD);
61 $DYNAMIC_FILE_UPLOAD = 1;
62
63 use constant EX_TEMPFAIL => 75;
64 use constant BUFFER_SIZE => 8192;
65
66 my %opts;
67 GetOptions( \%opts, "queue=s", "action=s", "url=s", "jar=s", "help", "debug", "extension=s", "timeout=i" );
68
69 if ( $opts{'help'} ) {
70     require Pod::Usage;
71     import Pod::Usage;
72     pod2usage("RT Mail Gateway\n");
73     exit 1;    # Don't want to succeed if this is really an email!
74 }
75
76 unless ( $opts{'url'} ) {
77     print STDERR "$0 invoked improperly\n\nNo 'url' provided to mail gateway!\n";
78     exit 1;
79 }
80
81 my $ua = new LWP::UserAgent;
82 $ua->cookie_jar( { file => $opts{'jar'} } ) if $opts{'jar'};
83
84 my %args = (
85     SessionType => 'REST', # Surpress login box
86 );
87 foreach ( qw(queue action) ) {
88     $args{$_} = $opts{$_} if defined $opts{$_};
89 };
90
91 if ( ($opts{'extension'} || '') =~ /^(?:action|queue|ticket)$/i ) {
92     $args{ lc $opts{'extension'} } = $ENV{'EXTENSION'} || $opts{$opts{'extension'}};
93 } elsif ( $opts{'extension'} && $ENV{'EXTENSION'} ) {
94     print STDERR "Value of the --extension argument is not action, queue or ticket"
95         .", but environment variable EXTENSION is also defined. The former is ignored.\n";
96 }
97
98 # add ENV{'EXTENSION'} as X-RT-MailExtension to the message header
99 if ( my $value = ( $ENV{'EXTENSION'} || $opts{'extension'} ) ) {
100     # prepare value to avoid MIME format breakage
101     # strip trailing newline symbols
102     $value =~ s/(\r*\n)+$//;
103     # make a correct multiline header field,
104     # with tabs in the beginning of each line
105     $value =~ s/(\r*\n)/$1\t/g;
106     $opts{'headers'} .= "X-RT-Mail-Extension: $value\n";
107 }
108
109 # Read the message in from STDIN
110 my %message = write_down_message();
111 unless( $message{'filename'} ) {
112     $args{'message'} = [
113         undef, '',
114         'Content-Type' => 'application/octet-stream',
115         Content => ${ $message{'content'} },
116     ];
117 } else {
118     $args{'message'} = [
119         $message{'filename'}, '',
120         'Content-Type' => 'application/octet-stream',
121     ];
122 }
123
124 my $full_url = $opts{'url'}. "/REST/1.0/NoAuth/mail-gateway";
125 print STDERR "$0: connecting to $full_url\n" if $opts{'debug'};
126
127 $ua->timeout( exists( $opts{'timeout'} )? $opts{'timeout'}: 180 );
128 my $r = $ua->post( $full_url, \%args, Content_Type => 'form-data' );
129 check_failure($r);
130
131 my $content = $r->content;
132 print STDERR $content ."\n" if $opts{'debug'};
133
134 if ( $content !~ /^(ok|not ok)/ ) {
135
136     # It's not the server's fault if the mail is bogus. We just want to know that
137     # *something* came out of the server.
138     print STDERR <<EOF;
139 RT server error.
140
141 The RT server which handled your email did not behave as expected. It
142 said:
143
144 $content
145 EOF
146
147     exit EX_TEMPFAIL;
148 }
149
150 exit;
151
152 END {
153     unlink $message{'filename'} if $message{'filename'};
154 }
155
156
157 sub check_failure {
158     my $r = shift;
159     return if $r->is_success;
160
161     # This ordinarily oughtn't to be able to happen, suggests a bug in RT.
162     # So only load these heavy modules when they're needed.
163     require HTML::TreeBuilder;
164     require HTML::FormatText;
165
166     my $error = $r->error_as_HTML;
167     my $tree  = HTML::TreeBuilder->new->parse( $error );
168     $tree->eof;
169
170     # It'll be a cold day in hell before RT sends out bounces in HTML
171     my $formatter = HTML::FormatText->new(
172         leftmargin  => 0,
173         rightmargin => 50,
174     );
175     print STDERR $formatter->format( $tree );
176     print STDERR "\n$0: undefined server error\n" if $opts{'debug'};
177     exit EX_TEMPFAIL;
178 }
179
180 sub write_down_message {
181     use File::Temp qw(tempfile);
182
183     local $@;
184     my ($fh, $filename) = eval { tempfile() };
185     if ( !$fh || $@ ) {
186         print STDERR "$0: Couldn't create temp file, using memory\n";
187         print STDERR "error: $@\n" if $@;
188
189         my $message = \do { local (@ARGV, $/); <STDIN> };
190         unless ( $$message =~ /\S/ ) {
191             print STDERR "$0: no message passed on STDIN\n";
192             exit 0;
193         }
194         $$message = $opts{'headers'} . $$message if $opts{'headers'};
195         return ( content => $message );
196     }
197
198     binmode $fh;
199     binmode \*STDIN;
200     
201     print $fh $opts{'headers'} if $opts{'headers'};
202
203     my $buf; my $empty = 1;
204     while(1) {
205         my $status = read \*STDIN, $buf, BUFFER_SIZE;
206         unless ( defined $status ) {
207             print STDERR "$0: couldn't read message: $!\n";
208             exit EX_TEMPFAIL;
209         } elsif ( !$status ) {
210             last;
211         }
212         $empty = 0 if $buf =~ /\S/;
213         print $fh $buf;
214     };
215     close $fh;
216
217     if ( $empty ) {
218         print STDERR "$0: no message passed on STDIN\n";
219         exit 0;
220     }
221     print STDERR "$0: temp file is '$filename'\n" if $opts{'debug'};
222     return (filename => $filename);
223 }
224
225
226 =head1 SYNOPSIS
227
228     rt-mailgate --help : this text
229
230 Usual invocation (from MTA):
231
232     rt-mailgate --action (correspond|comment|...) --queue queuename
233                 --url http://your.rt.server/
234                 [ --debug ]
235                 [ --extension (queue|action|ticket) ]
236                 [ --timeout seconds ]
237
238
239
240 =head1 OPTIONS
241
242 =over 3
243
244 =item C<--action>
245
246 Specifies what happens to email sent to this alias.  The avaliable
247 basic actions are: C<correspond>, C<comment>.
248
249
250 If you've set the RT configuration variable B<< C<UnsafeEmailCommands> >>,
251 C<take> and C<resolve> are also available.  You can execute two or more
252 actions on a single message using a C<-> separated list.  RT will execute
253 the actions in the listed order.  For example you can use C<take-comment>,
254 C<correspond-resolve> or C<take-comment-resolve> as actions.
255
256 Note that C<take> and C<resolve> actions ignore message text if used
257 alone.  Include a  C<comment> or C<correspond> action if you want RT
258 to record the incoming message.
259
260 The default action is C<correspond>.
261
262 =item C<--queue>
263
264 This flag determines which queue this alias should create a ticket in if no ticket identifier
265 is found.
266
267 =item C<--url>
268
269 This flag tells the mail gateway where it can find your RT server. You should 
270 probably use the same URL that users use to log into RT.
271
272
273 =item C<--extension> OPTIONAL
274
275 Some MTAs will route mail sent to user-foo@host or user+foo@host to user@host
276 and present "foo" in the environment variable $EXTENSION. By specifying
277 the value "queue" for this parameter, the queue this message should be
278 submitted to will be set to the value of $EXTENSION. By specifying
279 "ticket", $EXTENSION will be interpreted as the id of the ticket this message
280 is related to.  "action" will allow the user to specify either "comment" or
281 "correspond" in the address extension.
282
283 =item C<--debug> OPTIONAL
284
285 Print debugging output to standard error
286
287
288 =item C<--timeout> OPTIONAL
289
290 Configure the timeout for posting the message to the web server.  The
291 default timeout is 3 minutes (180 seconds).
292
293
294 =head1 DESCRIPTION
295
296 The RT mail gateway is the primary mechanism for communicating with RT
297 via email. This program simply directs the email to the RT web server,
298 which handles filing correspondence and sending out any required mail.
299 It is designed to be run as part of the mail delivery process, either
300 called directly by the MTA or C<procmail>, or in a F<.forward> or
301 equivalent.
302
303 =head1 SETUP
304
305 Much of the set up of the mail gateway depends on your MTA and mail
306 routing configuration. However, you will need first of all to create an
307 RT user for the mail gateway and assign it a password; this helps to
308 ensure that mail coming into the web server did originate from the
309 gateway.
310
311 Next, you need to route mail to C<rt-mailgate> for the queues you're
312 monitoring. For instance, if you're using F</etc/aliases> and you have a
313 "bugs" queue, you will want something like this:
314
315     bugs:         "|/opt/rt3/bin/rt-mailgate --queue bugs --action correspond
316               --url http://rt.mycorp.com/"
317
318     bugs-comment: "|/opt/rt3/bin/rt-mailgate --queue bugs --action comment
319               --url http://rt.mycorp.com/"
320
321 Note that you don't have to run your RT server on your mail server, as
322 the mail gateway will happily relay to a different machine.
323
324 =head1 CUSTOMIZATION
325
326 By default, the mail gateway will accept mail from anyone. However,
327 there are situations in which you will want to authenticate users
328 before allowing them to communicate with the system. You can do this
329 via a plug-in mechanism in the RT configuration.
330
331 You can set the array C<@MailPlugins> to be a list of plugins. The
332 default plugin, if this is not given, is C<Auth::MailFrom> - that is,
333 authentication of the person is done based on the C<From> header of the
334 email. If you have additional filters or authentication mechanisms, you
335 can list them here and they will be called in order:
336
337     Set( @MailPlugins =>
338         "Filter::SpamAssassin",
339         "Auth::LDAP",
340         # ...
341     );
342
343 See the documentation for any additional plugins you have.
344
345 You may also put Perl subroutines into the C<@MailPlugins> array, if
346 they behave as described below.
347
348 =head1 WRITING PLUGINS
349
350 What's actually going on in the above is that C<@MailPlugins> is a
351 list of Perl modules; RT prepends C<RT::Interface::Email::> to the name,
352 to form a package name, and then C<use>'s this module. The module is
353 expected to provide a C<GetCurrentUser> subroutine, which takes a hash of
354 several parameters:
355
356 =over 4
357
358 =item Message
359
360 A C<MIME::Entity> object representing the email
361
362 =item CurrentUser
363
364 An C<RT::CurrentUser> object
365
366 =item AuthStat
367
368 The authentication level returned from the previous plugin.
369
370 =item Ticket [OPTIONAL]
371
372 The ticket under discussion
373
374 =item Queue [OPTIONAL]
375
376 If we don't already have a ticket id, we need to know which queue we're talking about
377
378 =item Action
379
380 The action being performed. At the moment, it's one of "comment" or "correspond"
381
382 =back 4
383
384 It returns two values, the new C<RT::CurrentUser> object, and the new
385 authentication level. The authentication level can be zero, not allowed
386 to communicate with RT at all, (a "permission denied" error is mailed to
387 the correspondent) or one, which is the normal mode of operation.
388 Additionally, if C<-1> is returned, then the processing of the plug-ins
389 stops immediately and the message is ignored.
390
391 =head1 ENVIRONMENT
392
393 =over 4
394
395 =item EXTENSION
396
397 Some MTAs will route mail sent to user-foo@host or user+foo@host to user@host
398 and present "foo" in the environment variable C<EXTENSION>. Mailgate adds value
399 of this variable to message in the C<X-RT-Mail-Extension> field of the message
400 header.
401
402 See also C<--extension> option. Note that value of the environment variable is
403 always added to the message header when it's not empty even if C<--extension>
404 option is not provided.
405
406 =back 4
407
408 =cut
409