1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2005 Best Practical Solutions, LLC
6 # <jesse@bestpractical.com>
8 # (Except where explicitly superseded by other copyright notices)
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 # General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 # CONTRIBUTION SUBMISSION POLICY:
30 # (The following paragraph is not intended to limit the rights granted
31 # to you to modify and distribute this software under the terms of
32 # the GNU General Public License and is only of importance to you if
33 # you choose to contribute your changes and enhancements to the
34 # community by submitting them to Best Practical Solutions, LLC.)
36 # By intentionally submitting any modifications, corrections or
37 # derivatives to this work, or any other work intended for use with
38 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
39 # you are the copyright holder for those contributions and you grant
40 # Best Practical Solutions, LLC a nonexclusive, worldwide, irrevocable,
41 # royalty-free, perpetual, license to use, copy, create derivative
42 # works based on those contributions, and sublicense and distribute
43 # those contributions and any derivatives thereof.
45 # END BPS TAGGED BLOCK }}}
46 package RT::Interface::Email;
56 use vars qw ($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
58 # set the version for version checking
59 $VERSION = do { my @r = (q$Revision: 1.1.1.5 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker
63 # your exported package globals go here,
64 # as well as any optionally exported functions
69 &CheckForSuspiciousSender
70 &CheckForAutoGenerated
72 &ParseCcAddressesFromHead
73 &ParseSenderAddressFromHead
74 &ParseErrorsToAddressFromHead
75 &ParseAddressFromHeader
82 RT::Interface::Email - helper functions for parsing email sent to RT
86 use lib "!!RT_LIB_PATH!!";
87 use lib "!!RT_ETC_PATH!!";
89 use RT::Interface::Email qw(Gateway CreateUser);
96 ok(require RT::Interface::Email);
106 # {{{ sub CheckForLoops
111 #If this instance of RT sent it our, we don't want to take it in
112 my $RTLoop = $head->get("X-RT-Loop-Prevention") || "";
113 chomp ($RTLoop); #remove that newline
114 if ($RTLoop eq "$RT::rtname") {
118 # TODO: We might not trap the case where RT instance A sends a mail
119 # to RT instance B which sends a mail to ...
125 # {{{ sub CheckForSuspiciousSender
127 sub CheckForSuspiciousSender {
130 #if it's from a postmaster or mailer daemon, it's likely a bounce.
132 #TODO: better algorithms needed here - there is no standards for
133 #bounces, so it's very difficult to separate them from anything
134 #else. At the other hand, the Return-To address is only ment to be
135 #used as an error channel, we might want to put up a separate
136 #Return-To address which is treated differently.
138 #TODO: search through the whole email and find the right Ticket ID.
140 my ($From, $junk) = ParseSenderAddressFromHead($head);
142 if (($From =~ /^mailer-daemon\@/i) or
143 ($From =~ /^postmaster\@/i)){
154 # {{{ sub CheckForAutoGenerated
155 sub CheckForAutoGenerated {
158 my $Precedence = $head->get("Precedence") || "" ;
159 if ($Precedence =~ /^(bulk|junk)/i) {
163 # First Class mailer uses this as a clue.
164 my $FCJunk = $head->get("X-FC-Machinegenerated") || "";
165 if ($FCJunk =~ /^true/i) {
176 =head2 IsRTAddress ADDRESS
178 Takes a single parameter, an email address.
179 Returns true if that address matches the $RTAddressRegexp.
180 Returns false, otherwise.
185 my $address = shift || '';
187 # Example: the following rule would tell RT not to Cc
188 # "tickets@noc.example.com"
189 if ( defined($RT::RTAddressRegexp) &&
190 $address =~ /$RT::RTAddressRegexp/ ) {
199 # {{{ CullRTAddresses
201 =head2 CullRTAddresses ARRAY
203 Takes a single argument, an array of email addresses.
204 Returns the same array with any IsRTAddress()es weeded out.
208 sub CullRTAddresses {
209 return (grep { IsRTAddress($_) } @_);
216 my %args = (To => $RT::OwnerEmail,
218 From => $RT::CorrespondAddress,
219 Subject => 'There has been an error',
220 Explanation => 'Unexplained error',
227 $RT::Logger->log(level => $args{'LogLevel'},
228 message => $args{'Explanation'}
230 my $entity = MIME::Entity->build( Type =>"multipart/mixed",
231 From => $args{'From'},
234 Subject => $args{'Subject'},
235 Precedence => 'bulk',
236 'X-RT-Loop-Prevention' => $RT::rtname,
239 $entity->attach( Data => $args{'Explanation'}."\n");
241 my $mimeobj = $args{'MIMEObj'};
243 $mimeobj->sync_headers();
244 $entity->add_part($mimeobj);
247 if ($args{'Attach'}) {
248 $entity->attach(Data => $args{'Attach'}, Type => 'message/rfc822');
252 if ($RT::MailCommand eq 'sendmailpipe') {
253 open (MAIL, "|$RT::SendmailPath $RT::SendmailArguments") || return(0);
254 print MAIL $entity->as_string;
258 $entity->send($RT::MailCommand, $RT::MailParams);
267 my ($Username, $Address, $Name, $ErrorsTo, $entity) = @_;
268 my $NewUser = RT::User->new($RT::SystemUser);
270 my ($Val, $Message) =
271 $NewUser->Create(Name => ($Username || $Address),
272 EmailAddress => $Address,
276 Comments => 'Autocreated on ticket submission'
281 # Deal with the race condition of two account creations at once
284 $NewUser->LoadByName($Username);
287 unless ($NewUser->Id) {
288 $NewUser->LoadByEmail($Address);
291 unless ($NewUser->Id) {
292 MailError( To => $ErrorsTo,
293 Subject => "User could not be created",
294 Explanation => "User creation failed in mailgateway: $Message",
301 #Load the new user object
302 my $CurrentUser = RT::CurrentUser->new();
303 $CurrentUser->LoadByEmail($Address);
305 unless ($CurrentUser->id) {
306 $RT::Logger->warning("Couldn't load user '$Address'.". "giving up");
307 MailError( To => $ErrorsTo,
308 Subject => "User could not be loaded",
309 Explanation => "User '$Address' could not be loaded in the mail gateway",
319 # {{{ ParseCcAddressesFromHead
321 =head2 ParseCcAddressesFromHead HASHREF
323 Takes a hashref object containing QueueObj, Head and CurrentUser objects.
324 Returns a list of all email addresses in the To and Cc
325 headers b<except> the current Queue\'s email addresses, the CurrentUser\'s
326 email address and anything that the configuration sub RT::IsRTAddress matches.
330 sub ParseCcAddressesFromHead {
331 my %args = ( Head => undef,
333 CurrentUser => undef,
338 my @ToObjs = Mail::Address->parse($args{'Head'}->get('To'));
339 my @CcObjs = Mail::Address->parse($args{'Head'}->get('Cc'));
341 foreach my $AddrObj (@ToObjs, @CcObjs) {
342 my $Address = $AddrObj->address;
343 $Address = $args{'CurrentUser'}->UserObj->CanonicalizeEmailAddress($Address);
344 next if ($args{'CurrentUser'}->EmailAddress =~ /^\Q$Address\E$/i);
345 next if ($args{'QueueObj'}->CorrespondAddress =~ /^\Q$Address\E$/i);
346 next if ($args{'QueueObj'}->CommentAddress =~ /^\Q$Address\E$/i);
347 next if (RT::EmailParser->IsRTAddress($Address));
349 push (@Addresses, $Address);
357 # {{{ ParseSenderAdddressFromHead
359 =head2 ParseSenderAddressFromHead
361 Takes a MIME::Header object. Returns a tuple: (user@host, friendly name)
362 of the From (evaluated in order of Reply-To:, From:, Sender)
366 sub ParseSenderAddressFromHead {
368 #Figure out who's sending this message.
369 my $From = $head->get('Reply-To') ||
370 $head->get('From') ||
371 $head->get('Sender');
372 return (ParseAddressFromHeader($From));
376 # {{{ ParseErrorsToAdddressFromHead
378 =head2 ParseErrorsToAddressFromHead
380 Takes a MIME::Header object. Return a single value : user@host
381 of the From (evaluated in order of Errors-To:,Reply-To:, From:, Sender)
385 sub ParseErrorsToAddressFromHead {
387 #Figure out who's sending this message.
389 foreach my $header ('Errors-To' , 'Reply-To', 'From', 'Sender' ) {
390 # If there's a header of that name
391 my $headerobj = $head->get($header);
393 my ($addr, $name ) = ParseAddressFromHeader($headerobj);
394 # If it's got actual useful content...
395 return ($addr) if ($addr);
401 # {{{ ParseAddressFromHeader
403 =head2 ParseAddressFromHeader ADDRESS
405 Takes an address from $head->get('Line') and returns a tuple: user@host, friendly name
410 sub ParseAddressFromHeader{
413 # Perl 5.8.0 breaks when doing regex matches on utf8
414 Encode::_utf8_off($Addr) if $] == 5.008;
415 my @Addresses = Mail::Address->parse($Addr);
417 my $AddrObj = $Addresses[0];
419 unless (ref($AddrObj)) {
423 my $Name = ($AddrObj->phrase || $AddrObj->comment || $AddrObj->address);
425 #Lets take the from and load a user object.
426 my $Address = $AddrObj->address;
428 return ($Address, $Name);
432 # {{{ sub ParseTicketId
439 my $test_name = $RT::EmailSubjectTagRegex || qr/\Q$RT::rtname\E/;
441 if ( $Subject =~ s/\[$test_name\s+\#(\d+)\s*\]//i ) {
443 $RT::Logger->debug("Found a ticket ID. It's $id");
454 =head2 Gateway ARGSREF
464 This performs all the "guts" of the mail rt-mailgate program, and is
465 designed to be called from the web interface with a message, user
468 Can also take an optional 'ticket' parameter; this ticket id overrides
469 any ticket id found in the subject.
475 (status code, message, optional ticket object)
477 status code is a numeric value.
479 for temporary failures, the status code should be -75
481 for permanent failures which are handled by RT, the status code
484 for succces, the status code should be 1
493 my %args = %$argsref;
495 # Set some reasonable defaults
496 $args{'action'} ||= 'correspond';
497 $args{'queue'} ||= '1';
499 # Validate the action
500 my ($status, @actions) = IsCorrectAction( $args{'action'} );
503 # Can't safely loc this. What object do we loc around?
504 $RT::Logger->crit("Mail gateway called with an invalid action paramenter '".$actions[0]."' for queue '".$args{'queue'}."'");
506 return ( -75, "Invalid 'action' parameter", undef );
509 my $parser = RT::EmailParser->new();
511 $parser->SmartParseMIMEEntityFromScalar( Message => $args{'message'});
513 if (!$parser->Entity()) {
515 To => $RT::OwnerEmail,
516 Subject => "RT Bounce: Unparseable message",
517 Explanation => "RT couldn't process the message below",
518 Attach => $args{'message'}
521 return(0,"Failed to parse this message. Something is likely badly wrong with the message");
524 my $Message = $parser->Entity();
525 my $head = $Message->head;
527 my ( $CurrentUser, $AuthStat, $error );
529 # Initalize AuthStat so comparisons work correctly
530 $AuthStat = -9999999;
532 my $ErrorsTo = ParseErrorsToAddressFromHead($head);
534 my $MessageId = $head->get('Message-ID')
535 || "<no-message-id-" . time . rand(2000) . "\@.$RT::Organization>";
537 #Pull apart the subject line
538 my $Subject = $head->get('Subject') || '';
541 $args{'ticket'} ||= ParseTicketId($Subject);
544 my $Right = 'CreateTicket';
545 if ( $args{'ticket'} ) {
546 $SystemTicket = RT::Ticket->new($RT::SystemUser);
547 $SystemTicket->Load( $args{'ticket'} );
548 # if there's an existing ticket, this must be a reply
549 $Right = 'ReplyToTicket';
552 #Set up a queue object
553 my $SystemQueueObj = RT::Queue->new($RT::SystemUser);
554 $SystemQueueObj->Load( $args{'queue'} );
556 # We can safely have no queue of we have a known-good ticket
557 unless ( $args{'ticket'} || $SystemQueueObj->id ) {
558 return ( -75, "RT couldn't find the queue: " . $args{'queue'}, undef );
561 # Authentication Level
562 # -1 - Get out. this user has been explicitly declined
563 # 0 - User may not do anything (Not used at the moment)
565 # 2 - User is allowed to specify status updates etc. a la enhanced-mailgate
567 push @RT::MailPlugins, "Auth::MailFrom" unless @RT::MailPlugins;
569 # Since this needs loading, no matter what
571 foreach (@RT::MailPlugins) {
574 if ( ref($_) eq "CODE" ) {
578 $_ = "RT::Interface::Email::".$_ unless $_ =~ /^RT::Interface::Email::/;
581 $RT::Logger->crit("Couldn't load module '$_': $@");
585 if ( !defined( $Code = *{ $_ . "::GetCurrentUser" }{CODE} ) ) {
586 $RT::Logger->crit("No GetCurrentUser code found in $_ module");
591 foreach my $action ( @actions ) {
593 ( $CurrentUser, $NewAuthStat ) = $Code->(
595 RawMessageRef => \$args{'message'},
596 CurrentUser => $CurrentUser,
597 AuthLevel => $AuthStat,
599 Ticket => $SystemTicket,
600 Queue => $SystemQueueObj
604 # If a module returns a "-1" then we discard the ticket, so.
605 $AuthStat = -1 if $NewAuthStat == -1;
607 # You get the highest level of authentication you were assigned.
608 $AuthStat = $NewAuthStat if $NewAuthStat > $AuthStat;
610 last if $AuthStat == -1;
613 last if $AuthStat == -1;
616 # {{{ If authentication fails and no new user was created, get out.
617 if ( !$CurrentUser or !$CurrentUser->Id or $AuthStat == -1 ) {
619 # If the plugins refused to create one, they lose.
620 unless ( $AuthStat == -1 ) {
622 # Notify the RT Admin of the failure.
623 # XXX Should this be configurable?
625 To => $RT::OwnerEmail,
626 Subject => "Could not load a valid user",
627 Explanation => <<EOT,
628 RT could not load a valid user, and RT's configuration does not allow
629 for the creation of a new user for this email ($ErrorsTo).
631 You might need to grant 'Everyone' the right '$Right' for the
632 queue @{[$args{'queue'}]}.
639 # Also notify the requestor that his request has been dropped.
642 Subject => "Could not load a valid user",
643 Explanation => <<EOT,
644 RT could not load a valid user, and RT's configuration does not allow
645 for the creation of a new user for your email.
652 return ( 0, "Could not load a valid user", undef );
657 # {{{ Lets check for mail loops of various sorts.
658 my $IsAutoGenerated = CheckForAutoGenerated($head);
660 my $IsSuspiciousSender = CheckForSuspiciousSender($head);
662 my $IsALoop = CheckForLoops($head);
664 my $SquelchReplies = 0;
666 #If the message is autogenerated, we need to know, so we can not
667 # send mail to the sender
668 if ( $IsSuspiciousSender || $IsAutoGenerated || $IsALoop ) {
670 $ErrorsTo = $RT::OwnerEmail;
675 # {{{ Drop it if it's disallowed
676 if ( $AuthStat == 0 ) {
679 Subject => "Permission Denied",
680 Explanation => "You do not have permission to communicate with RT",
686 # {{{ Warn someone if it's a loop
688 # Warn someone if it's a loop, before we drop it on the ground
690 $RT::Logger->crit("RT Recieved mail ($MessageId) from itself.");
692 #Should we mail it to RTOwner?
693 if ($RT::LoopsToRTOwner) {
695 To => $RT::OwnerEmail,
696 Subject => "RT Bounce: $Subject",
697 Explanation => "RT thinks this message may be a bounce",
702 #Do we actually want to store it?
703 return ( 0, "Message Bounced", undef ) unless ($RT::StoreLoops);
708 # {{{ Squelch replies if necessary
709 # Don't let the user stuff the RT-Squelch-Replies-To header.
710 if ( $head->get('RT-Squelch-Replies-To') ) {
712 'RT-Relocated-Squelch-Replies-To',
713 $head->get('RT-Squelch-Replies-To')
715 $head->delete('RT-Squelch-Replies-To');
718 if ($SquelchReplies) {
720 # Squelch replies to the sender, and also leave a clue to
721 # allow us to squelch ALL outbound messages. This way we
722 # can punt the logic of "what to do when we get a bounce"
723 # to the scrip. We might want to notify nobody. Or just
724 # the RT Owner. Or maybe all Privileged watchers.
725 my ( $Sender, $junk ) = ParseSenderAddressFromHead($head);
726 $head->add( 'RT-Squelch-Replies-To', $Sender );
727 $head->add( 'RT-DetectedAutoGenerated', 'true' );
732 my $Ticket = RT::Ticket->new($CurrentUser);
734 # {{{ If we don't have a ticket Id, we're creating a new ticket
735 if ( (!$SystemTicket || !$SystemTicket->Id) &&
736 grep /^(comment|correspond)$/, @actions ) {
738 # {{{ Create a new ticket
741 my @Requestors = ( $CurrentUser->id );
743 if ($RT::ParseNewMessageForTicketCcs) {
744 @Cc = ParseCcAddressesFromHead(
746 CurrentUser => $CurrentUser,
747 QueueObj => $SystemQueueObj
751 my ( $id, $Transaction, $ErrStr ) = $Ticket->Create(
752 Queue => $SystemQueueObj->Id,
754 Requestor => \@Requestors,
761 Subject => "Ticket creation failed",
762 Explanation => $ErrStr,
765 $RT::Logger->error("Create failed: $id / $Transaction / $ErrStr ");
766 return ( 0, "Ticket creation failed", $Ticket );
768 # strip comments&corresponds from the actions we don't need record twice
769 @actions = grep !/^(comment|correspond)$/, @actions;
770 $args{'ticket'} = $id;
775 $Ticket->Load( $args{'ticket'} );
776 unless ( $Ticket->Id ) {
777 my $message = "Could not find a ticket with id " . $args{'ticket'};
780 Subject => "Message not recorded",
781 Explanation => $message,
785 return ( 0, $message );
789 foreach my $action( @actions ) {
790 # If the action is comment, add a comment.
791 if ( $action =~ /^(comment|correspond)$/i ) {
792 my ( $status, $msg );
793 if ( $action =~ /^correspond$/i ) {
794 ( $status, $msg ) = $Ticket->Correspond( MIMEObj => $Message );
797 ( $status, $msg ) = $Ticket->Comment( MIMEObj => $Message );
801 #Warn the sender that we couldn't actually submit the comment.
804 Subject => "Message not recorded",
808 return ( 0, "Message not recorded", $Ticket );
811 elsif ($RT::UnsafeEmailCommands && $action =~ /^take$/i ) {
812 my ( $status, $msg ) = $Ticket->SetOwner( $CurrentUser->id );
815 #Warn the sender that we couldn't actually submit the comment.
818 Subject => "Ticket not taken",
822 return ( 0, "Ticket not taken", $Ticket );
825 elsif ( $RT::UnsafeEmailCommands && $action =~ /^resolve$/i ) {
826 my ( $status, $msg ) = $Ticket->SetStatus( 'resolved' );
828 #Warn the sender that we couldn't actually submit the comment.
831 Subject => "Ticket not resolved",
835 return ( 0, "Ticket not resolved", $Ticket );
841 #Return mail to the sender with an error
844 Subject => "RT Configuration error",
847 . "' not a recognized action."
848 . " Your RT administrator has misconfigured "
849 . "the mail aliases which invoke RT",
852 $RT::Logger->crit( $args{'action'} . " type unknown for $MessageId" );
855 "Configuration error: "
857 . " not a recognized action",
864 return ( 1, "Success", $Ticket );
870 my @actions = split /-/, $action;
871 foreach ( @actions ) {
872 return (0, $_) unless /^(?:comment|correspond|take|resolve)$/;
874 return (1, @actions);
878 eval "require RT::Interface::Email_Vendor";
879 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Vendor.pm});
880 eval "require RT::Interface::Email_Local";
881 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Local.pm});