3 # Copyright (c) 1996-2003 Jesse Vincent <jesse@bestpractical.com>
5 # (Except where explictly superceded by other copyright notices)
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
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.
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.
24 package RT::Interface::Email;
34 use vars qw ($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
36 # set the version for version checking
37 $VERSION = do { my @r = (q$Revision: 1.1.1.2 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker
41 # your exported package globals go here,
42 # as well as any optionally exported functions
47 &CheckForSuspiciousSender
48 &CheckForAutoGenerated
50 &ParseCcAddressesFromHead
51 &ParseSenderAddressFromHead
52 &ParseErrorsToAddressFromHead
53 &ParseAddressFromHeader
60 RT::Interface::CLI - helper functions for creating a commandline RT interface
64 use lib "!!RT_LIB_PATH!!";
65 use lib "!!RT_ETC_PATH!!";
67 use RT::Interface::Email qw(Gateway CreateUser);
74 ok(require RT::Interface::Email);
84 # {{{ sub CheckForLoops
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") {
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 ...
103 # {{{ sub CheckForSuspiciousSender
105 sub CheckForSuspiciousSender {
108 #if it's from a postmaster or mailer daemon, it's likely a bounce.
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.
116 #TODO: search through the whole email and find the right Ticket ID.
118 my ($From, $junk) = ParseSenderAddressFromHead($head);
120 if (($From =~ /^mailer-daemon/i) or
121 ($From =~ /^postmaster/i)){
132 # {{{ sub CheckForAutoGenerated
133 sub CheckForAutoGenerated {
136 my $Precedence = $head->get("Precedence") || "" ;
137 if ($Precedence =~ /^(bulk|junk)/i) {
150 my %args = (To => $RT::OwnerEmail,
152 From => $RT::CorrespondAddress,
153 Subject => 'There has been an error',
154 Explanation => 'Unexplained error',
161 $RT::Logger->log(level => $args{'LogLevel'},
162 message => $args{'Explanation'}
164 my $entity = MIME::Entity->build( Type =>"multipart/mixed",
165 From => $args{'From'},
168 Subject => $args{'Subject'},
169 'X-RT-Loop-Prevention' => $RT::rtname,
172 $entity->attach( Data => $args{'Explanation'}."\n");
174 my $mimeobj = $args{'MIMEObj'};
176 $mimeobj->sync_headers();
177 $entity->add_part($mimeobj);
180 if ($args{'Attach'}) {
181 $entity->attach(Data => $args{'Attach'}, Type => 'message/rfc822');
186 if ($RT::MailCommand eq 'sendmailpipe') {
187 open (MAIL, "|$RT::SendmailPath $RT::SendmailArguments") || return(0);
188 print MAIL $entity->as_string;
192 $entity->send($RT::MailCommand, $RT::MailParams);
201 my ($Username, $Address, $Name, $ErrorsTo, $entity) = @_;
202 my $NewUser = RT::User->new($RT::SystemUser);
204 my ($Val, $Message) =
205 $NewUser->Create(Name => ($Username || $Address),
206 EmailAddress => $Address,
210 Comments => 'Autocreated on ticket submission'
215 # Deal with the race condition of two account creations at once
218 $NewUser->LoadByName($Username);
221 unless ($NewUser->Id) {
222 $NewUser->LoadByEmail($Address);
225 unless ($NewUser->Id) {
226 MailError( To => $ErrorsTo,
227 Subject => "User could not be created",
228 Explanation => "User creation failed in mailgateway: $Message",
235 #Load the new user object
236 my $CurrentUser = RT::CurrentUser->new();
237 $CurrentUser->LoadByEmail($Address);
239 unless ($CurrentUser->id) {
240 $RT::Logger->warning("Couldn't load user '$Address'.". "giving up");
241 MailError( To => $ErrorsTo,
242 Subject => "User could not be loaded",
243 Explanation => "User '$Address' could not be loaded in the mail gateway",
252 # {{{ ParseCcAddressesFromHead
254 =head2 ParseCcAddressesFromHead HASHREF
256 Takes a hashref object containing QueueObj, Head and CurrentUser objects.
257 Returns a list of all email addresses in the To and Cc
258 headers b<except> the current Queue\'s email addresses, the CurrentUser\'s
259 email address and anything that the configuration sub RT::IsRTAddress matches.
263 sub ParseCcAddressesFromHead {
264 my %args = ( Head => undef,
266 CurrentUser => undef,
271 my @ToObjs = Mail::Address->parse($args{'Head'}->get('To'));
272 my @CcObjs = Mail::Address->parse($args{'Head'}->get('Cc'));
274 foreach my $AddrObj (@ToObjs, @CcObjs) {
275 my $Address = $AddrObj->address;
276 $Address = $args{'CurrentUser'}->UserObj->CanonicalizeEmailAddress($Address);
277 next if ($args{'CurrentUser'}->EmailAddress =~ /^$Address$/i);
278 next if ($args{'QueueObj'}->CorrespondAddress =~ /^$Address$/i);
279 next if ($args{'QueueObj'}->CommentAddress =~ /^$Address$/i);
280 next if (RT::EmailParser::IsRTAddress(undef, $Address));
282 push (@Addresses, $Address);
290 # {{{ ParseSenderAdddressFromHead
292 =head2 ParseSenderAddressFromHead
294 Takes a MIME::Header object. Returns a tuple: (user@host, friendly name)
295 of the From (evaluated in order of Reply-To:, From:, Sender)
299 sub ParseSenderAddressFromHead {
301 #Figure out who's sending this message.
302 my $From = $head->get('Reply-To') ||
303 $head->get('From') ||
304 $head->get('Sender');
305 return (ParseAddressFromHeader($From));
309 # {{{ ParseErrorsToAdddressFromHead
311 =head2 ParseErrorsToAddressFromHead
313 Takes a MIME::Header object. Return a single value : user@host
314 of the From (evaluated in order of Errors-To:,Reply-To:, From:, Sender)
318 sub ParseErrorsToAddressFromHead {
320 #Figure out who's sending this message.
322 foreach my $header ('Errors-To' , 'Reply-To', 'From', 'Sender' ) {
323 # If there's a header of that name
324 my $headerobj = $head->get($header);
326 my ($addr, $name ) = ParseAddressFromHeader($headerobj);
327 # If it's got actual useful content...
328 return ($addr) if ($addr);
334 # {{{ ParseAddressFromHeader
336 =head2 ParseAddressFromHeader ADDRESS
338 Takes an address from $head->get('Line') and returns a tuple: user@host, friendly name
343 sub ParseAddressFromHeader{
346 my @Addresses = Mail::Address->parse($Addr);
348 my $AddrObj = $Addresses[0];
350 unless (ref($AddrObj)) {
354 my $Name = ($AddrObj->phrase || $AddrObj->comment || $AddrObj->address);
356 #Lets take the from and load a user object.
357 my $Address = $AddrObj->address;
359 return ($Address, $Name);
365 =head2 Gateway ARGSREF
375 This performs all the "guts" of the mail rt-mailgate program, and is
376 designed to be called from the web interface with a message, user
383 (status code, message, optional ticket object)
385 status code is a numeric value.
387 for temporary failures, status code should be -75
389 for permanent failures which are handled by RT, status code should be 0
391 for succces, the status code should be 1
400 my %args = %$argsref;
402 # Set some reasonable defaults
403 $args{'action'} = 'correspond' unless ( $args{'action'} );
404 $args{'queue'} = '1' unless ( $args{'queue'} );
406 # Validate the action
407 unless ( $args{'action'} =~ /^(comment|correspond|action)$/ ) {
409 # Can't safely loc this. What object do we loc around?
410 $RT::Logger->crit("Mail gateway called with an invalid action paramenter '".$args{'action'}."' for queue '".$args{'queue'}."'");
412 return ( -75, "Invalid 'action' parameter", undef );
415 my $parser = RT::EmailParser->new();
416 my ( $fh, $temp_file );
419 # on NFS and NTFS, it is possible that tempfile() conflicts
420 # with other processes, causing a race condition. we try to
421 # accommodate this by pausing and retrying.
422 last if ( $fh, $temp_file ) = eval { File::Temp::tempfile(undef, UNLINK => 0) };
426 binmode $fh; #thank you, windows
428 print $fh $args{'message'};
431 if ( -f $temp_file ) {
432 $parser->ParseMIMEEntityFromFile($temp_file);
433 File::Temp::unlink0( $fh, $temp_file );
434 if ($parser->Entity) {
435 delete $args{'message'};
441 #If for some reason we weren't able to parse the message using a temp file
442 # try it with a scalar
443 if ($args{'message'}) {
444 $parser->ParseMIMEEntityFromScalar($args{'message'});
448 if (!$parser->Entity()) {
450 To => $RT::OwnerEmail,
451 Subject => "RT Bounce: Unparseable message",
452 Explanation => "RT couldn't process the message below",
453 Attach => $args{'message'}
456 return(0,"Failed to parse this message. Something is likely badly wrong with the message");
459 my $Message = $parser->Entity();
460 my $head = $Message->head;
462 my ( $CurrentUser, $AuthStat, $status, $error );
464 # Initalize AuthStat so comparisons work correctly
465 $AuthStat = -9999999;
467 my $ErrorsTo = ParseErrorsToAddressFromHead($head);
469 my $MessageId = $head->get('Message-Id')
470 || "<no-message-id-" . time . rand(2000) . "\@.$RT::Organization>";
472 #Pull apart the subject line
473 my $Subject = $head->get('Subject') || '';
476 $args{'ticket'} ||= $parser->ParseTicketId($Subject);
479 if ( $args{'ticket'} ) {
480 $SystemTicket = RT::Ticket->new($RT::SystemUser);
481 $SystemTicket->Load( $args{'ticket'} );
484 #Set up a queue object
485 my $SystemQueueObj = RT::Queue->new($RT::SystemUser);
486 $SystemQueueObj->Load( $args{'queue'} );
488 # We can safely have no queue of we have a known-good ticket
489 unless ( $args{'ticket'} || $SystemQueueObj->id ) {
490 return ( -75, "RT couldn't find the queue: " . $args{'queue'}, undef );
493 # Authentication Level
494 # -1 - Get out. this user has been explicitly declined
495 # 0 - User may not do anything (Not used at the moment)
497 # 2 - User is allowed to specify status updates etc. a la enhanced-mailgate
499 push @RT::MailPlugins, "Auth::MailFrom" unless @RT::MailPlugins;
501 # Since this needs loading, no matter what
503 for (@RT::MailPlugins) {
506 if ( ref($_) eq "CODE" ) {
510 $_ = "RT::Interface::Email::$_" unless /^RT::Interface::Email::/;
513 die ("Couldn't load module $_: $@");
517 if ( !defined( $Code = *{ $_ . "::GetCurrentUser" }{CODE} ) ) {
518 die ("No GetCurrentUser code found in $_ module");
523 ( $CurrentUser, $NewAuthStat ) = $Code->(
525 CurrentUser => $CurrentUser,
526 AuthLevel => $AuthStat,
527 Action => $args{'action'},
528 Ticket => $SystemTicket,
529 Queue => $SystemQueueObj
532 # If a module returns a "-1" then we discard the ticket, so.
533 $AuthStat = -1 if $NewAuthStat == -1;
535 # You get the highest level of authentication you were assigned.
536 $AuthStat = $NewAuthStat if $NewAuthStat > $AuthStat;
537 last if $AuthStat == -1;
540 # {{{ If authentication fails and no new user was created, get out.
541 if ( !$CurrentUser or !$CurrentUser->Id or $AuthStat == -1 ) {
543 # If the plugins refused to create one, they lose.
544 unless ( $AuthStat == -1 ) {
546 # Notify the RT Admin of the failure.
547 # XXX Should this be configurable?
549 To => $RT::OwnerEmail,
550 Subject => "Could not load a valid user",
551 Explanation => <<EOT,
552 RT could not load a valid user, and RT's configuration does not allow
553 for the creation of a new user for this email ($ErrorsTo).
555 You might need to grant 'Everyone' the right 'CreateTicket' for the
556 queue @{[$args{'queue'}]}.
563 # Also notify the requestor that his request has been dropped.
566 Subject => "Could not load a valid user",
567 Explanation => <<EOT,
568 RT could not load a valid user, and RT's configuration does not allow
569 for the creation of a new user for your email.
576 return ( 0, "Could not load a valid user", undef );
581 # {{{ Lets check for mail loops of various sorts.
582 my $IsAutoGenerated = CheckForAutoGenerated($head);
584 my $IsSuspiciousSender = CheckForSuspiciousSender($head);
586 my $IsALoop = CheckForLoops($head);
588 my $SquelchReplies = 0;
590 #If the message is autogenerated, we need to know, so we can not
591 # send mail to the sender
592 if ( $IsSuspiciousSender || $IsAutoGenerated || $IsALoop ) {
594 $ErrorsTo = $RT::OwnerEmail;
599 # {{{ Drop it if it's disallowed
600 if ( $AuthStat == 0 ) {
603 Subject => "Permission Denied",
604 Explanation => "You do not have permission to communicate with RT",
610 # {{{ Warn someone if it's a loop
612 # Warn someone if it's a loop, before we drop it on the ground
614 $RT::Logger->crit("RT Recieved mail ($MessageId) from itself.");
616 #Should we mail it to RTOwner?
617 if ($RT::LoopsToRTOwner) {
619 To => $RT::OwnerEmail,
620 Subject => "RT Bounce: $Subject",
621 Explanation => "RT thinks this message may be a bounce",
625 #Do we actually want to store it?
626 return ( 0, "Message Bounced", undef ) unless ($RT::StoreLoops);
632 # {{{ Squelch replies if necessary
633 # Don't let the user stuff the RT-Squelch-Replies-To header.
634 if ( $head->get('RT-Squelch-Replies-To') ) {
636 'RT-Relocated-Squelch-Replies-To',
637 $head->get('RT-Squelch-Replies-To')
639 $head->delete('RT-Squelch-Replies-To');
642 if ($SquelchReplies) {
643 ## TODO: This is a hack. It should be some other way to
644 ## indicate that the transaction should be "silent".
646 my ( $Sender, $junk ) = ParseSenderAddressFromHead($head);
647 $head->add( 'RT-Squelch-Replies-To', $Sender );
652 my $Ticket = RT::Ticket->new($CurrentUser);
654 # {{{ If we don't have a ticket Id, we're creating a new ticket
655 if ( !$args{'ticket'} ) {
657 # {{{ Create a new ticket
660 my @Requestors = ( $CurrentUser->id );
662 if ($RT::ParseNewMessageForTicketCcs) {
663 @Cc = ParseCcAddressesFromHead(
665 CurrentUser => $CurrentUser,
666 QueueObj => $SystemQueueObj
670 my ( $id, $Transaction, $ErrStr ) = $Ticket->Create(
671 Queue => $SystemQueueObj->Id,
673 Requestor => \@Requestors,
680 Subject => "Ticket creation failed",
681 Explanation => $ErrStr,
684 $RT::Logger->error("Create failed: $id / $Transaction / $ErrStr ");
685 return ( 0, "Ticket creation failed", $Ticket );
693 # If the action is comment, add a comment.
694 elsif ( $args{'action'} =~ /^(comment|correspond)$/i ) {
695 $Ticket->Load( $args{'ticket'} );
696 unless ( $Ticket->Id ) {
697 my $message = "Could not find a ticket with id " . $args{'ticket'};
700 Subject => "Message not recorded",
701 Explanation => $message,
705 return ( 0, $message );
708 my ( $status, $msg );
709 if ( $args{'action'} =~ /^correspond$/ ) {
710 ( $status, $msg ) = $Ticket->Correspond( MIMEObj => $Message );
713 ( $status, $msg ) = $Ticket->Comment( MIMEObj => $Message );
717 #Warn the sender that we couldn't actually submit the comment.
720 Subject => "Message not recorded",
724 return ( 0, "Message not recorded", $Ticket );
730 #Return mail to the sender with an error
733 Subject => "RT Configuration error",
736 . "' not a recognized action."
737 . " Your RT administrator has misconfigured "
738 . "the mail aliases which invoke RT",
741 $RT::Logger->crit( $args{'action'} . " type unknown for $MessageId" );
744 "Configuration error: "
746 . " not a recognized action",
752 return ( 1, "Success", $Ticket );
755 eval "require RT::Interface::Email_Vendor";
756 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Vendor.pm});
757 eval "require RT::Interface::Email_Local";
758 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Local.pm});