import rt 3.0.12
[freeside.git] / rt / lib / RT / Interface / Email.pm
1 # BEGIN LICENSE BLOCK
2
3 # Copyright (c) 1996-2003 Jesse Vincent <jesse@bestpractical.com>
4
5 # (Except where explictly superceded by other copyright notices)
6
7 # This work is made available to you under the terms of Version 2 of
8 # the GNU General Public License. A copy of that license should have
9 # been provided with this software, but in any event can be snarfed
10 # from www.gnu.org.
11
12 # This work is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # General Public License for more details.
16
17 # Unless otherwise specified, all modifications, corrections or
18 # extensions to this work which alter its source code become the
19 # property of Best Practical Solutions, LLC when submitted for
20 # inclusion in the work.
21
22
23 # END LICENSE BLOCK
24 package RT::Interface::Email;
25
26 use strict;
27 use Mail::Address;
28 use MIME::Entity;
29 use RT::EmailParser;
30 use File::Temp;
31
32 BEGIN {
33     use Exporter ();
34     use vars qw ($VERSION  @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
35     
36     # set the version for version checking
37     $VERSION = do { my @r = (q$Revision: 1.1.1.3 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker
38     
39     @ISA         = qw(Exporter);
40     
41     # your exported package globals go here,
42     # as well as any optionally exported functions
43     @EXPORT_OK   = qw(
44               &CreateUser
45                       &GetMessageContent
46                       &CheckForLoops 
47                       &CheckForSuspiciousSender
48                       &CheckForAutoGenerated 
49                       &MailError 
50                       &ParseCcAddressesFromHead
51                       &ParseSenderAddressFromHead 
52                       &ParseErrorsToAddressFromHead
53                       &ParseAddressFromHeader
54               &Gateway);
55
56 }
57
58 =head1 NAME
59
60   RT::Interface::Email - helper functions for parsing email sent to RT
61
62 =head1 SYNOPSIS
63
64   use lib "!!RT_LIB_PATH!!";
65   use lib "!!RT_ETC_PATH!!";
66
67   use RT::Interface::Email  qw(Gateway CreateUser);
68
69 =head1 DESCRIPTION
70
71
72 =begin testing
73
74 ok(require RT::Interface::Email);
75
76 =end testing
77
78
79 =head1 METHODS
80
81 =cut
82
83
84 # {{{ sub CheckForLoops 
85
86 sub CheckForLoops  {
87     my $head = shift;
88     
89     #If this instance of RT sent it our, we don't want to take it in
90     my $RTLoop = $head->get("X-RT-Loop-Prevention") || "";
91     chomp ($RTLoop); #remove that newline
92     if ($RTLoop eq "$RT::rtname") {
93         return (1);
94     }
95     
96     # TODO: We might not trap the case where RT instance A sends a mail
97     # to RT instance B which sends a mail to ...
98     return (undef);
99 }
100
101 # }}}
102
103 # {{{ sub CheckForSuspiciousSender
104
105 sub CheckForSuspiciousSender {
106     my $head = shift;
107
108     #if it's from a postmaster or mailer daemon, it's likely a bounce.
109     
110     #TODO: better algorithms needed here - there is no standards for
111     #bounces, so it's very difficult to separate them from anything
112     #else.  At the other hand, the Return-To address is only ment to be
113     #used as an error channel, we might want to put up a separate
114     #Return-To address which is treated differently.
115     
116     #TODO: search through the whole email and find the right Ticket ID.
117
118     my ($From, $junk) = ParseSenderAddressFromHead($head);
119     
120     if (($From =~ /^mailer-daemon/i) or
121         ($From =~ /^postmaster/i)){
122         return (1);
123         
124     }
125     
126     return (undef);
127
128 }
129
130 # }}}
131
132 # {{{ sub CheckForAutoGenerated
133 sub CheckForAutoGenerated {
134     my $head = shift;
135     
136     my $Precedence = $head->get("Precedence") || "" ;
137     if ($Precedence =~ /^(bulk|junk)/i) {
138         return (1);
139     }
140     else {
141         return (0);
142     }
143 }
144
145 # }}}
146
147
148 # {{{ sub MailError 
149 sub MailError {
150     my %args = (To => $RT::OwnerEmail,
151                 Bcc => undef,
152                 From => $RT::CorrespondAddress,
153                 Subject => 'There has been an error',
154                 Explanation => 'Unexplained error',
155                 MIMEObj => undef,
156         Attach => undef,
157                 LogLevel => 'crit',
158                 @_);
159
160
161     $RT::Logger->log(level => $args{'LogLevel'}, 
162                      message => $args{'Explanation'}
163                     );
164     my $entity = MIME::Entity->build( Type  =>"multipart/mixed",
165                                       From => $args{'From'},
166                                       Bcc => $args{'Bcc'},
167                                       To => $args{'To'},
168                                       Subject => $args{'Subject'},
169                                       'X-RT-Loop-Prevention' => $RT::rtname,
170                                     );
171
172     $entity->attach(  Data => $args{'Explanation'}."\n");
173     
174     my $mimeobj = $args{'MIMEObj'};
175     if ($mimeobj) {
176         $mimeobj->sync_headers();
177         $entity->add_part($mimeobj);
178     }
179    
180     if ($args{'Attach'}) {
181         $entity->attach(Data => $args{'Attach'}, Type => 'message/rfc822');
182
183     }
184
185     if ($RT::MailCommand eq 'sendmailpipe') {
186         open (MAIL, "|$RT::SendmailPath $RT::SendmailArguments") || return(0);
187         print MAIL $entity->as_string;
188         close(MAIL);
189     }
190     else {
191         $entity->send($RT::MailCommand, $RT::MailParams);
192     }
193 }
194
195 # }}}
196
197 # {{{ Create User
198
199 sub CreateUser {
200     my ($Username, $Address, $Name, $ErrorsTo, $entity) = @_;
201     my $NewUser = RT::User->new($RT::SystemUser);
202
203     my ($Val, $Message) = 
204       $NewUser->Create(Name => ($Username || $Address),
205                        EmailAddress => $Address,
206                        RealName => $Name,
207                        Password => undef,
208                        Privileged => 0,
209                        Comments => 'Autocreated on ticket submission'
210                       );
211     
212     unless ($Val) {
213         
214         # Deal with the race condition of two account creations at once
215         #
216         if ($Username) {
217             $NewUser->LoadByName($Username);
218         }
219         
220         unless ($NewUser->Id) {
221             $NewUser->LoadByEmail($Address);
222         }
223         
224         unless ($NewUser->Id) {  
225             MailError( To => $ErrorsTo,
226                        Subject => "User could not be created",
227                        Explanation => "User creation failed in mailgateway: $Message",
228                        MIMEObj => $entity,
229                        LogLevel => 'crit'
230                      );
231         }
232     }
233
234     #Load the new user object
235     my $CurrentUser = RT::CurrentUser->new();
236     $CurrentUser->LoadByEmail($Address);
237
238     unless ($CurrentUser->id) {
239             $RT::Logger->warning("Couldn't load user '$Address'.".  "giving up");
240                 MailError( To => $ErrorsTo,
241                            Subject => "User could not be loaded",
242                            Explanation => "User  '$Address' could not be loaded in the mail gateway",
243                            MIMEObj => $entity,
244                            LogLevel => 'crit'
245                      );
246     }
247
248     return $CurrentUser;
249 }
250 # }}}       
251 # {{{ ParseCcAddressesFromHead 
252
253 =head2 ParseCcAddressesFromHead HASHREF
254
255 Takes a hashref object containing QueueObj, Head and CurrentUser objects.
256 Returns a list of all email addresses in the To and Cc 
257 headers b<except> the current Queue\'s email addresses, the CurrentUser\'s 
258 email address  and anything that the configuration sub RT::IsRTAddress matches.
259
260 =cut
261   
262 sub ParseCcAddressesFromHead {
263     my %args = ( Head => undef,
264                  QueueObj => undef,
265                  CurrentUser => undef,
266                  @_ );
267     
268     my (@Addresses);
269         
270     my @ToObjs = Mail::Address->parse($args{'Head'}->get('To'));
271     my @CcObjs = Mail::Address->parse($args{'Head'}->get('Cc'));
272     
273     foreach my $AddrObj (@ToObjs, @CcObjs) {
274         my $Address = $AddrObj->address;
275         $Address = $args{'CurrentUser'}->UserObj->CanonicalizeEmailAddress($Address);
276         next if ($args{'CurrentUser'}->EmailAddress =~ /^$Address$/i);
277         next if ($args{'QueueObj'}->CorrespondAddress =~ /^$Address$/i);
278         next if ($args{'QueueObj'}->CommentAddress =~ /^$Address$/i);
279         next if (RT::EmailParser::IsRTAddress(undef, $Address));
280         
281         push (@Addresses, $Address);
282     }
283     return (@Addresses);
284 }
285
286
287 # }}}
288
289 # {{{ ParseSenderAdddressFromHead
290
291 =head2 ParseSenderAddressFromHead
292
293 Takes a MIME::Header object. Returns a tuple: (user@host, friendly name) 
294 of the From (evaluated in order of Reply-To:, From:, Sender)
295
296 =cut
297
298 sub ParseSenderAddressFromHead {
299     my $head = shift;
300     #Figure out who's sending this message.
301     my $From = $head->get('Reply-To') || 
302       $head->get('From') || 
303         $head->get('Sender');
304     return (ParseAddressFromHeader($From));
305 }
306 # }}}
307
308 # {{{ ParseErrorsToAdddressFromHead
309
310 =head2 ParseErrorsToAddressFromHead
311
312 Takes a MIME::Header object. Return a single value : user@host
313 of the From (evaluated in order of Errors-To:,Reply-To:, From:, Sender)
314
315 =cut
316
317 sub ParseErrorsToAddressFromHead {
318     my $head = shift;
319     #Figure out who's sending this message.
320
321     foreach my $header ('Errors-To' , 'Reply-To', 'From', 'Sender' ) {
322         # If there's a header of that name
323         my $headerobj = $head->get($header);
324         if ($headerobj) {
325                 my ($addr, $name ) = ParseAddressFromHeader($headerobj);
326                 # If it's got actual useful content...
327                 return ($addr) if ($addr);
328         }
329     }
330 }
331 # }}}
332
333 # {{{ ParseAddressFromHeader
334
335 =head2 ParseAddressFromHeader ADDRESS
336
337 Takes an address from $head->get('Line') and returns a tuple: user@host, friendly name
338
339 =cut
340
341
342 sub ParseAddressFromHeader{
343     my $Addr = shift;
344     
345     my @Addresses = Mail::Address->parse($Addr);
346     
347     my $AddrObj = $Addresses[0];
348
349     unless (ref($AddrObj)) {
350         return(undef,undef);
351     }
352  
353     my $Name =  ($AddrObj->phrase || $AddrObj->comment || $AddrObj->address);
354     
355     #Lets take the from and load a user object.
356     my $Address = $AddrObj->address;
357
358     return ($Address, $Name);
359 }
360 # }}}
361
362
363
364 =head2 Gateway ARGSREF
365
366
367 Takes parameters:
368
369     action
370     queue
371     message
372
373
374 This performs all the "guts" of the mail rt-mailgate program, and is
375 designed to be called from the web interface with a message, user
376 object, and so on.
377
378 Can also take an optional 'ticket' parameter; this ticket id overrides
379 any ticket id found in the subject.
380
381 Returns:
382
383     An array of:
384     
385     (status code, message, optional ticket object)
386
387     status code is a numeric value.
388
389     for temporary failures, status code should be -75
390
391     for permanent failures which are handled by RT, status code should be 0
392     
393     for succces, the status code should be 1
394
395
396
397 =cut
398
399 sub Gateway {
400     my $argsref = shift;
401
402     my %args = %$argsref;
403
404     # Set some reasonable defaults
405     $args{'action'} = 'correspond' unless ( $args{'action'} );
406     $args{'queue'}  = '1'          unless ( $args{'queue'} );
407
408     # Validate the action
409     unless ( $args{'action'} =~ /^(comment|correspond|action)$/ ) {
410
411         # Can't safely loc this. What object do we loc around?
412         $RT::Logger->crit("Mail gateway called with an invalid action paramenter '".$args{'action'}."' for queue '".$args{'queue'}."'");
413
414         return ( -75, "Invalid 'action' parameter", undef );
415     }
416
417     my $parser = RT::EmailParser->new();
418     my ( $fh, $temp_file );
419     for ( 1 .. 10 ) {
420
421         # on NFS and NTFS, it is possible that tempfile() conflicts
422         # with other processes, causing a race condition. we try to
423         # accommodate this by pausing and retrying.
424         last if ( $fh, $temp_file ) = eval { File::Temp::tempfile(undef, UNLINK => 0) };
425         sleep 1;
426     }
427     if ($fh) {
428         binmode $fh;    #thank you, windows
429         $fh->autoflush(1);
430         print $fh $args{'message'};
431         close($fh);
432
433         if ( -f $temp_file ) {
434             $parser->ParseMIMEEntityFromFile($temp_file);
435             unlink( $temp_file );
436             if ($parser->Entity) {
437                 delete $args{'message'};
438             }
439         }
440
441     }
442
443     #If for some reason we weren't able to parse the message using a temp file 
444     # try it with a scalar
445     if ($args{'message'}) {
446         $parser->ParseMIMEEntityFromScalar($args{'message'});
447
448     } 
449
450     if (!$parser->Entity()) {
451         MailError(
452             To          => $RT::OwnerEmail,
453             Subject     => "RT Bounce: Unparseable message",
454             Explanation => "RT couldn't process the message below",
455             Attach     => $args{'message'}
456         );
457
458         return(0,"Failed to parse this message. Something is likely badly wrong with the message");
459     }
460
461     my $Message = $parser->Entity();
462     my $head    = $Message->head;
463
464     my ( $CurrentUser, $AuthStat, $status, $error );
465
466     # Initalize AuthStat so comparisons work correctly
467     $AuthStat = -9999999;
468
469     my $ErrorsTo = ParseErrorsToAddressFromHead($head);
470
471     my $MessageId = $head->get('Message-Id')
472       || "<no-message-id-" . time . rand(2000) . "\@.$RT::Organization>";
473
474     #Pull apart the subject line
475     my $Subject = $head->get('Subject') || '';
476     chomp $Subject;
477
478     $args{'ticket'} ||= $parser->ParseTicketId($Subject);
479
480     my $SystemTicket;
481     if ( $args{'ticket'} ) {
482         $SystemTicket = RT::Ticket->new($RT::SystemUser);
483         $SystemTicket->Load( $args{'ticket'} );
484     }
485
486     #Set up a queue object
487     my $SystemQueueObj = RT::Queue->new($RT::SystemUser);
488     $SystemQueueObj->Load( $args{'queue'} );
489
490     # We can safely have no queue of we have a known-good ticket
491     unless ( $args{'ticket'} || $SystemQueueObj->id ) {
492         return ( -75, "RT couldn't find the queue: " . $args{'queue'}, undef );
493     }
494
495     # Authentication Level
496     # -1 - Get out.  this user has been explicitly declined
497     # 0 - User may not do anything (Not used at the moment)
498     # 1 - Normal user
499     # 2 - User is allowed to specify status updates etc. a la enhanced-mailgate
500
501     push @RT::MailPlugins, "Auth::MailFrom" unless @RT::MailPlugins;
502
503     # Since this needs loading, no matter what
504
505     for (@RT::MailPlugins) {
506         my $Code;
507         my $NewAuthStat;
508         if ( ref($_) eq "CODE" ) {
509             $Code = $_;
510         }
511         else {
512             $_ = "RT::Interface::Email::$_" unless /^RT::Interface::Email::/;
513             eval "require $_;";
514             if ($@) {
515                 die ("Couldn't load module $_: $@");
516                 next;
517             }
518             no strict 'refs';
519             if ( !defined( $Code = *{ $_ . "::GetCurrentUser" }{CODE} ) ) {
520                 die ("No GetCurrentUser code found in $_ module");
521                 next;
522             }
523         }
524
525         ( $CurrentUser, $NewAuthStat ) = $Code->(
526             Message     => $Message,
527             CurrentUser => $CurrentUser,
528             AuthLevel   => $AuthStat,
529             Action      => $args{'action'},
530             Ticket      => $SystemTicket,
531             Queue       => $SystemQueueObj
532         );
533
534         # If a module returns a "-1" then we discard the ticket, so.
535         $AuthStat = -1 if $NewAuthStat == -1;
536
537         # You get the highest level of authentication you were assigned.
538         $AuthStat = $NewAuthStat if $NewAuthStat > $AuthStat;
539         last if $AuthStat == -1;
540     }
541
542     # {{{ If authentication fails and no new user was created, get out.
543     if ( !$CurrentUser or !$CurrentUser->Id or $AuthStat == -1 ) {
544
545         # If the plugins refused to create one, they lose.
546         unless ( $AuthStat == -1 ) {
547
548             # Notify the RT Admin of the failure.
549             # XXX Should this be configurable?
550             MailError(
551                 To          => $RT::OwnerEmail,
552                 Subject     => "Could not load a valid user",
553                 Explanation => <<EOT,
554 RT could not load a valid user, and RT's configuration does not allow
555 for the creation of a new user for this email ($ErrorsTo).
556
557 You might need to grant 'Everyone' the right 'CreateTicket' for the
558 queue @{[$args{'queue'}]}.
559
560 EOT
561                 MIMEObj  => $Message,
562                 LogLevel => 'error'
563             );
564
565             # Also notify the requestor that his request has been dropped.
566             MailError(
567                 To          => $ErrorsTo,
568                 Subject     => "Could not load a valid user",
569                 Explanation => <<EOT,
570 RT could not load a valid user, and RT's configuration does not allow
571 for the creation of a new user for your email.
572
573 EOT
574                 MIMEObj  => $Message,
575                 LogLevel => 'error'
576             );
577         }
578         return ( 0, "Could not load a valid user", undef );
579     }
580
581     # }}}
582
583     # {{{ Lets check for mail loops of various sorts.
584     my $IsAutoGenerated = CheckForAutoGenerated($head);
585
586     my $IsSuspiciousSender = CheckForSuspiciousSender($head);
587
588     my $IsALoop = CheckForLoops($head);
589
590     my $SquelchReplies = 0;
591
592     #If the message is autogenerated, we need to know, so we can not
593     # send mail to the sender
594     if ( $IsSuspiciousSender || $IsAutoGenerated || $IsALoop ) {
595         $SquelchReplies = 1;
596         $ErrorsTo       = $RT::OwnerEmail;
597     }
598
599     # }}}
600
601     # {{{ Drop it if it's disallowed
602     if ( $AuthStat == 0 ) {
603         MailError(
604             To          => $ErrorsTo,
605             Subject     => "Permission Denied",
606             Explanation => "You do not have permission to communicate with RT",
607             MIMEObj     => $Message
608         );
609     }
610
611     # }}}
612     # {{{ Warn someone  if it's a loop
613
614     # Warn someone if it's a loop, before we drop it on the ground
615     if ($IsALoop) {
616         $RT::Logger->crit("RT Recieved mail ($MessageId) from itself.");
617
618         #Should we mail it to RTOwner?
619         if ($RT::LoopsToRTOwner) {
620             MailError(
621                 To          => $RT::OwnerEmail,
622                 Subject     => "RT Bounce: $Subject",
623                 Explanation => "RT thinks this message may be a bounce",
624                 MIMEObj     => $Message
625             );
626
627             #Do we actually want to store it?
628             return ( 0, "Message Bounced", undef ) unless ($RT::StoreLoops);
629         }
630     }
631
632     # }}}
633
634     # {{{ Squelch replies if necessary
635     # Don't let the user stuff the RT-Squelch-Replies-To header.
636     if ( $head->get('RT-Squelch-Replies-To') ) {
637         $head->add(
638             'RT-Relocated-Squelch-Replies-To',
639             $head->get('RT-Squelch-Replies-To')
640         );
641         $head->delete('RT-Squelch-Replies-To');
642     }
643
644     if ($SquelchReplies) {
645         ## TODO: This is a hack.  It should be some other way to
646         ## indicate that the transaction should be "silent".
647
648         my ( $Sender, $junk ) = ParseSenderAddressFromHead($head);
649         $head->add( 'RT-Squelch-Replies-To', $Sender );
650     }
651
652     # }}}
653
654     my $Ticket = RT::Ticket->new($CurrentUser);
655
656     # {{{ If we don't have a ticket Id, we're creating a new ticket
657     if ( !$args{'ticket'} ) {
658
659         # {{{ Create a new ticket
660
661         my @Cc;
662         my @Requestors = ( $CurrentUser->id );
663
664         if ($RT::ParseNewMessageForTicketCcs) {
665             @Cc = ParseCcAddressesFromHead(
666                 Head        => $head,
667                 CurrentUser => $CurrentUser,
668                 QueueObj    => $SystemQueueObj
669             );
670         }
671
672         my ( $id, $Transaction, $ErrStr ) = $Ticket->Create(
673             Queue     => $SystemQueueObj->Id,
674             Subject   => $Subject,
675             Requestor => \@Requestors,
676             Cc        => \@Cc,
677             MIMEObj   => $Message
678         );
679         if ( $id == 0 ) {
680             MailError(
681                 To          => $ErrorsTo,
682                 Subject     => "Ticket creation failed",
683                 Explanation => $ErrStr,
684                 MIMEObj     => $Message
685             );
686             $RT::Logger->error("Create failed: $id / $Transaction / $ErrStr ");
687             return ( 0, "Ticket creation failed", $Ticket );
688         }
689
690         # }}}
691     }
692
693     # }}}
694
695     #   If the action is comment, add a comment.
696     elsif ( $args{'action'} =~ /^(comment|correspond)$/i ) {
697         $Ticket->Load( $args{'ticket'} );
698         unless ( $Ticket->Id ) {
699             my $message = "Could not find a ticket with id " . $args{'ticket'};
700             MailError(
701                 To          => $ErrorsTo,
702                 Subject     => "Message not recorded",
703                 Explanation => $message,
704                 MIMEObj     => $Message
705             );
706
707             return ( 0, $message );
708         }
709
710         my ( $status, $msg );
711         if ( $args{'action'} =~ /^correspond$/ ) {
712             ( $status, $msg ) = $Ticket->Correspond( MIMEObj => $Message );
713         }
714         else {
715             ( $status, $msg ) = $Ticket->Comment( MIMEObj => $Message );
716         }
717         unless ($status) {
718
719             #Warn the sender that we couldn't actually submit the comment.
720             MailError(
721                 To          => $ErrorsTo,
722                 Subject     => "Message not recorded",
723                 Explanation => $msg,
724                 MIMEObj     => $Message
725             );
726             return ( 0, "Message not recorded", $Ticket );
727         }
728     }
729
730     else {
731
732         #Return mail to the sender with an error
733         MailError(
734             To          => $ErrorsTo,
735             Subject     => "RT Configuration error",
736             Explanation => "'"
737               . $args{'action'}
738               . "' not a recognized action."
739               . " Your RT administrator has misconfigured "
740               . "the mail aliases which invoke RT",
741             MIMEObj => $Message
742         );
743         $RT::Logger->crit( $args{'action'} . " type unknown for $MessageId" );
744         return (
745             -75,
746             "Configuration error: "
747               . $args{'action'}
748               . " not a recognized action",
749             $Ticket
750         );
751
752     }
753
754     return ( 1, "Success", $Ticket );
755 }
756
757 eval "require RT::Interface::Email_Vendor";
758 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Vendor.pm});
759 eval "require RT::Interface::Email_Local";
760 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Local.pm});
761
762 1;