1 # {{{ BEGIN BPS TAGGED BLOCK
5 # This software is Copyright (c) 1996-2004 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.4 $ =~ /\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) {
172 my %args = (To => $RT::OwnerEmail,
174 From => $RT::CorrespondAddress,
175 Subject => 'There has been an error',
176 Explanation => 'Unexplained error',
183 $RT::Logger->log(level => $args{'LogLevel'},
184 message => $args{'Explanation'}
186 my $entity = MIME::Entity->build( Type =>"multipart/mixed",
187 From => $args{'From'},
190 Subject => $args{'Subject'},
191 Precedence => 'bulk',
192 'X-RT-Loop-Prevention' => $RT::rtname,
195 $entity->attach( Data => $args{'Explanation'}."\n");
197 my $mimeobj = $args{'MIMEObj'};
199 $mimeobj->sync_headers();
200 $entity->add_part($mimeobj);
203 if ($args{'Attach'}) {
204 $entity->attach(Data => $args{'Attach'}, Type => 'message/rfc822');
208 if ($RT::MailCommand eq 'sendmailpipe') {
209 open (MAIL, "|$RT::SendmailPath $RT::SendmailArguments") || return(0);
210 print MAIL $entity->as_string;
214 $entity->send($RT::MailCommand, $RT::MailParams);
223 my ($Username, $Address, $Name, $ErrorsTo, $entity) = @_;
224 my $NewUser = RT::User->new($RT::SystemUser);
226 my ($Val, $Message) =
227 $NewUser->Create(Name => ($Username || $Address),
228 EmailAddress => $Address,
232 Comments => 'Autocreated on ticket submission'
237 # Deal with the race condition of two account creations at once
240 $NewUser->LoadByName($Username);
243 unless ($NewUser->Id) {
244 $NewUser->LoadByEmail($Address);
247 unless ($NewUser->Id) {
248 MailError( To => $ErrorsTo,
249 Subject => "User could not be created",
250 Explanation => "User creation failed in mailgateway: $Message",
257 #Load the new user object
258 my $CurrentUser = RT::CurrentUser->new();
259 $CurrentUser->LoadByEmail($Address);
261 unless ($CurrentUser->id) {
262 $RT::Logger->warning("Couldn't load user '$Address'.". "giving up");
263 MailError( To => $ErrorsTo,
264 Subject => "User could not be loaded",
265 Explanation => "User '$Address' could not be loaded in the mail gateway",
274 # {{{ ParseCcAddressesFromHead
276 =head2 ParseCcAddressesFromHead HASHREF
278 Takes a hashref object containing QueueObj, Head and CurrentUser objects.
279 Returns a list of all email addresses in the To and Cc
280 headers b<except> the current Queue\'s email addresses, the CurrentUser\'s
281 email address and anything that the configuration sub RT::IsRTAddress matches.
285 sub ParseCcAddressesFromHead {
286 my %args = ( Head => undef,
288 CurrentUser => undef,
293 my @ToObjs = Mail::Address->parse($args{'Head'}->get('To'));
294 my @CcObjs = Mail::Address->parse($args{'Head'}->get('Cc'));
296 foreach my $AddrObj (@ToObjs, @CcObjs) {
297 my $Address = $AddrObj->address;
298 $Address = $args{'CurrentUser'}->UserObj->CanonicalizeEmailAddress($Address);
299 next if ($args{'CurrentUser'}->EmailAddress =~ /^$Address$/i);
300 next if ($args{'QueueObj'}->CorrespondAddress =~ /^$Address$/i);
301 next if ($args{'QueueObj'}->CommentAddress =~ /^$Address$/i);
302 next if (RT::EmailParser::IsRTAddress(undef, $Address));
304 push (@Addresses, $Address);
312 # {{{ ParseSenderAdddressFromHead
314 =head2 ParseSenderAddressFromHead
316 Takes a MIME::Header object. Returns a tuple: (user@host, friendly name)
317 of the From (evaluated in order of Reply-To:, From:, Sender)
321 sub ParseSenderAddressFromHead {
323 #Figure out who's sending this message.
324 my $From = $head->get('Reply-To') ||
325 $head->get('From') ||
326 $head->get('Sender');
327 return (ParseAddressFromHeader($From));
331 # {{{ ParseErrorsToAdddressFromHead
333 =head2 ParseErrorsToAddressFromHead
335 Takes a MIME::Header object. Return a single value : user@host
336 of the From (evaluated in order of Errors-To:,Reply-To:, From:, Sender)
340 sub ParseErrorsToAddressFromHead {
342 #Figure out who's sending this message.
344 foreach my $header ('Errors-To' , 'Reply-To', 'From', 'Sender' ) {
345 # If there's a header of that name
346 my $headerobj = $head->get($header);
348 my ($addr, $name ) = ParseAddressFromHeader($headerobj);
349 # If it's got actual useful content...
350 return ($addr) if ($addr);
356 # {{{ ParseAddressFromHeader
358 =head2 ParseAddressFromHeader ADDRESS
360 Takes an address from $head->get('Line') and returns a tuple: user@host, friendly name
365 sub ParseAddressFromHeader{
368 my @Addresses = Mail::Address->parse($Addr);
370 my $AddrObj = $Addresses[0];
372 unless (ref($AddrObj)) {
376 my $Name = ($AddrObj->phrase || $AddrObj->comment || $AddrObj->address);
378 #Lets take the from and load a user object.
379 my $Address = $AddrObj->address;
381 return ($Address, $Name);
387 =head2 Gateway ARGSREF
397 This performs all the "guts" of the mail rt-mailgate program, and is
398 designed to be called from the web interface with a message, user
401 Can also take an optional 'ticket' parameter; this ticket id overrides
402 any ticket id found in the subject.
408 (status code, message, optional ticket object)
410 status code is a numeric value.
412 for temporary failures, status code should be -75
414 for permanent failures which are handled by RT, status code should be 0
416 for succces, the status code should be 1
425 my %args = %$argsref;
427 # Set some reasonable defaults
428 $args{'action'} = 'correspond' unless ( $args{'action'} );
429 $args{'queue'} = '1' unless ( $args{'queue'} );
431 # Validate the action
432 unless ( $args{'action'} =~ /^(comment|correspond|action)$/ ) {
434 # Can't safely loc this. What object do we loc around?
435 $RT::Logger->crit("Mail gateway called with an invalid action paramenter '".$args{'action'}."' for queue '".$args{'queue'}."'");
437 return ( -75, "Invalid 'action' parameter", undef );
440 my $parser = RT::EmailParser->new();
442 $parser->SmartParseMIMEEntityFromScalar( Message => $args{'message'});
444 if (!$parser->Entity()) {
446 To => $RT::OwnerEmail,
447 Subject => "RT Bounce: Unparseable message",
448 Explanation => "RT couldn't process the message below",
449 Attach => $args{'message'}
452 return(0,"Failed to parse this message. Something is likely badly wrong with the message");
455 my $Message = $parser->Entity();
456 my $head = $Message->head;
458 my ( $CurrentUser, $AuthStat, $status, $error );
460 # Initalize AuthStat so comparisons work correctly
461 $AuthStat = -9999999;
463 my $ErrorsTo = ParseErrorsToAddressFromHead($head);
465 my $MessageId = $head->get('Message-Id')
466 || "<no-message-id-" . time . rand(2000) . "\@.$RT::Organization>";
468 #Pull apart the subject line
469 my $Subject = $head->get('Subject') || '';
472 $args{'ticket'} ||= $parser->ParseTicketId($Subject);
475 my $Right = 'CreateTicket';
476 if ( $args{'ticket'} ) {
477 $SystemTicket = RT::Ticket->new($RT::SystemUser);
478 $SystemTicket->Load( $args{'ticket'} );
479 # if there's an existing ticket, this must be a reply
480 $Right = 'ReplyToTicket';
483 #Set up a queue object
484 my $SystemQueueObj = RT::Queue->new($RT::SystemUser);
485 $SystemQueueObj->Load( $args{'queue'} );
487 # We can safely have no queue of we have a known-good ticket
488 unless ( $args{'ticket'} || $SystemQueueObj->id ) {
489 return ( -75, "RT couldn't find the queue: " . $args{'queue'}, undef );
492 # Authentication Level
493 # -1 - Get out. this user has been explicitly declined
494 # 0 - User may not do anything (Not used at the moment)
496 # 2 - User is allowed to specify status updates etc. a la enhanced-mailgate
498 push @RT::MailPlugins, "Auth::MailFrom" unless @RT::MailPlugins;
500 # Since this needs loading, no matter what
502 foreach (@RT::MailPlugins) {
505 if ( ref($_) eq "CODE" ) {
509 $_ = "RT::Interface::Email::".$_ unless $_ =~ /^RT::Interface::Email::/;
512 $RT::Logger->crit("Couldn't load module '$_': $@");
516 if ( !defined( $Code = *{ $_ . "::GetCurrentUser" }{CODE} ) ) {
517 $RT::Logger->crit("No GetCurrentUser code found in $_ module");
522 ( $CurrentUser, $NewAuthStat ) = $Code->(
524 RawMessageRef => \$args{'message'},
525 CurrentUser => $CurrentUser,
526 AuthLevel => $AuthStat,
527 Action => $args{'action'},
528 Ticket => $SystemTicket,
529 Queue => $SystemQueueObj
533 # If a module returns a "-1" then we discard the ticket, so.
534 $AuthStat = -1 if $NewAuthStat == -1;
536 # You get the highest level of authentication you were assigned.
537 $AuthStat = $NewAuthStat if $NewAuthStat > $AuthStat;
538 last if $AuthStat == -1;
541 # {{{ If authentication fails and no new user was created, get out.
542 if ( !$CurrentUser or !$CurrentUser->Id or $AuthStat == -1 ) {
544 # If the plugins refused to create one, they lose.
545 unless ( $AuthStat == -1 ) {
547 # Notify the RT Admin of the failure.
548 # XXX Should this be configurable?
550 To => $RT::OwnerEmail,
551 Subject => "Could not load a valid user",
552 Explanation => <<EOT,
553 RT could not load a valid user, and RT's configuration does not allow
554 for the creation of a new user for this email ($ErrorsTo).
556 You might need to grant 'Everyone' the right '$Right' for the
557 queue @{[$args{'queue'}]}.
564 # Also notify the requestor that his request has been dropped.
567 Subject => "Could not load a valid user",
568 Explanation => <<EOT,
569 RT could not load a valid user, and RT's configuration does not allow
570 for the creation of a new user for your email.
577 return ( 0, "Could not load a valid user", undef );
582 # {{{ Lets check for mail loops of various sorts.
583 my $IsAutoGenerated = CheckForAutoGenerated($head);
585 my $IsSuspiciousSender = CheckForSuspiciousSender($head);
587 my $IsALoop = CheckForLoops($head);
589 my $SquelchReplies = 0;
591 #If the message is autogenerated, we need to know, so we can not
592 # send mail to the sender
593 if ( $IsSuspiciousSender || $IsAutoGenerated || $IsALoop ) {
595 $ErrorsTo = $RT::OwnerEmail;
600 # {{{ Drop it if it's disallowed
601 if ( $AuthStat == 0 ) {
604 Subject => "Permission Denied",
605 Explanation => "You do not have permission to communicate with RT",
611 # {{{ Warn someone if it's a loop
613 # Warn someone if it's a loop, before we drop it on the ground
615 $RT::Logger->crit("RT Recieved mail ($MessageId) from itself.");
617 #Should we mail it to RTOwner?
618 if ($RT::LoopsToRTOwner) {
620 To => $RT::OwnerEmail,
621 Subject => "RT Bounce: $Subject",
622 Explanation => "RT thinks this message may be a bounce",
627 #Do we actually want to store it?
628 return ( 0, "Message Bounced", undef ) unless ($RT::StoreLoops);
633 # {{{ Squelch replies if necessary
634 # Don't let the user stuff the RT-Squelch-Replies-To header.
635 if ( $head->get('RT-Squelch-Replies-To') ) {
637 'RT-Relocated-Squelch-Replies-To',
638 $head->get('RT-Squelch-Replies-To')
640 $head->delete('RT-Squelch-Replies-To');
643 if ($SquelchReplies) {
644 ## TODO: This is a hack. It should be some other way to
645 ## indicate that the transaction should be "silent".
647 my ( $Sender, $junk ) = ParseSenderAddressFromHead($head);
648 $head->add( 'RT-Squelch-Replies-To', $Sender );
653 my $Ticket = RT::Ticket->new($CurrentUser);
655 # {{{ If we don't have a ticket Id, we're creating a new ticket
656 if ( !$args{'ticket'} ) {
658 # {{{ Create a new ticket
661 my @Requestors = ( $CurrentUser->id );
663 if ($RT::ParseNewMessageForTicketCcs) {
664 @Cc = ParseCcAddressesFromHead(
666 CurrentUser => $CurrentUser,
667 QueueObj => $SystemQueueObj
671 my ( $id, $Transaction, $ErrStr ) = $Ticket->Create(
672 Queue => $SystemQueueObj->Id,
674 Requestor => \@Requestors,
681 Subject => "Ticket creation failed",
682 Explanation => $ErrStr,
685 $RT::Logger->error("Create failed: $id / $Transaction / $ErrStr ");
686 return ( 0, "Ticket creation failed", $Ticket );
694 # If the action is comment, add a comment.
695 elsif ( $args{'action'} =~ /^(comment|correspond)$/i ) {
696 $Ticket->Load( $args{'ticket'} );
697 unless ( $Ticket->Id ) {
698 my $message = "Could not find a ticket with id " . $args{'ticket'};
701 Subject => "Message not recorded",
702 Explanation => $message,
706 return ( 0, $message );
709 my ( $status, $msg );
710 if ( $args{'action'} =~ /^correspond$/ ) {
711 ( $status, $msg ) = $Ticket->Correspond( MIMEObj => $Message );
714 ( $status, $msg ) = $Ticket->Comment( MIMEObj => $Message );
718 #Warn the sender that we couldn't actually submit the comment.
721 Subject => "Message not recorded",
725 return ( 0, "Message not recorded", $Ticket );
731 #Return mail to the sender with an error
734 Subject => "RT Configuration error",
737 . "' not a recognized action."
738 . " Your RT administrator has misconfigured "
739 . "the mail aliases which invoke RT",
742 $RT::Logger->crit( $args{'action'} . " type unknown for $MessageId" );
745 "Configuration error: "
747 . " not a recognized action",
753 return ( 1, "Success", $Ticket );
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});