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.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',
160 $RT::Logger->log(level => $args{'LogLevel'},
161 message => $args{'Explanation'}
163 my $entity = MIME::Entity->build( Type =>"multipart/mixed",
164 From => $args{'From'},
167 Subject => $args{'Subject'},
168 'X-RT-Loop-Prevention' => $RT::rtname,
171 $entity->attach( Data => $args{'Explanation'}."\n");
173 my $mimeobj = $args{'MIMEObj'};
175 $mimeobj->sync_headers();
176 $entity->add_part($mimeobj);
179 if ($RT::MailCommand eq 'sendmailpipe') {
180 open (MAIL, "|$RT::SendmailPath $RT::SendmailArguments") || return(0);
181 print MAIL $entity->as_string;
185 $entity->send($RT::MailCommand, $RT::MailParams);
194 my ($Username, $Address, $Name, $ErrorsTo, $entity) = @_;
195 my $NewUser = RT::User->new($RT::SystemUser);
197 # This data is tainted by some Very Broken mailers.
198 # (Sometimes they send raw ISO 8859-1 data here. fear that.
200 $Username = Encode::encode(utf8 => $Username, Encode::FB_PERLQQ()) if defined $Username;
201 $Name = Encode::encode(utf8 => $Name, Encode::FB_PERLQQ()) if defined $Name;
203 my ($Val, $Message) =
204 $NewUser->Create(Name => ($Username || $Address),
205 EmailAddress => $Address,
209 Comments => 'Autocreated on ticket submission'
214 # Deal with the race condition of two account creations at once
217 $NewUser->LoadByName($Username);
220 unless ($NewUser->Id) {
221 $NewUser->LoadByEmail($Address);
224 unless ($NewUser->Id) {
225 MailError( To => $ErrorsTo,
226 Subject => "User could not be created",
227 Explanation => "User creation failed in mailgateway: $Message",
234 #Load the new user object
235 my $CurrentUser = RT::CurrentUser->new();
236 $CurrentUser->LoadByEmail($Address);
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",
251 # {{{ ParseCcAddressesFromHead
253 =head2 ParseCcAddressesFromHead HASHREF
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.
262 sub ParseCcAddressesFromHead {
263 my %args = ( Head => undef,
265 CurrentUser => undef,
270 my @ToObjs = Mail::Address->parse($args{'Head'}->get('To'));
271 my @CcObjs = Mail::Address->parse($args{'Head'}->get('Cc'));
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));
281 push (@Addresses, $Address);
289 # {{{ ParseSenderAdddressFromHead
291 =head2 ParseSenderAddressFromHead
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)
298 sub ParseSenderAddressFromHead {
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));
308 # {{{ ParseErrorsToAdddressFromHead
310 =head2 ParseErrorsToAddressFromHead
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)
317 sub ParseErrorsToAddressFromHead {
319 #Figure out who's sending this message.
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);
325 my ($addr, $name ) = ParseAddressFromHeader($headerobj);
326 # If it's got actual useful content...
327 return ($addr) if ($addr);
333 # {{{ ParseAddressFromHeader
335 =head2 ParseAddressFromHeader ADDRESS
337 Takes an address from $head->get('Line') and returns a tuple: user@host, friendly name
342 sub ParseAddressFromHeader{
345 my @Addresses = Mail::Address->parse($Addr);
347 my $AddrObj = $Addresses[0];
349 unless (ref($AddrObj)) {
353 my $Name = ($AddrObj->phrase || $AddrObj->comment || $AddrObj->address);
355 #Lets take the from and load a user object.
356 my $Address = $AddrObj->address;
358 return ($Address, $Name);
366 This performs all the "guts" of the mail rt-mailgate program, and is
367 designed to be called from the web interface with a message, user
373 my %args = ( message => undef,
375 action => 'correspond',
379 # Validate the action
380 unless ( $args{'action'} =~ /^(comment|correspond|action)$/ ) {
382 # Can't safely loc this. What object do we loc around?
383 return ( 0, "Invalid 'action' parameter", undef );
386 my $parser = RT::EmailParser->new();
387 $parser->ParseMIMEEntityFromScalar( $args{'message'} );
389 my $Message = $parser->Entity();
390 my $head = $Message->head;
392 my ( $CurrentUser, $AuthStat, $status, $error );
394 my $ErrorsTo = ParseErrorsToAddressFromHead($head);
396 my $MessageId = $head->get('Message-Id')
397 || "<no-message-id-" . time . rand(2000) . "\@.$RT::Organization>";
399 #Pull apart the subject line
400 my $Subject = $head->get('Subject') || '';
404 $args{'ticket'} ||= $parser->ParseTicketId($Subject);
407 if ($args{'ticket'} ) {
408 $SystemTicket = RT::Ticket->new($RT::SystemUser);
409 $SystemTicket->Load($args{'ticket'});
412 #Set up a queue object
413 my $SystemQueueObj = RT::Queue->new($RT::SystemUser);
414 $SystemQueueObj->Load( $args{'queue'} );
417 # We can safely have no queue of we have a known-good ticket
418 unless ( $args{'ticket'} || $SystemQueueObj->id ) {
420 To => $RT::OwnerEmail,
421 Subject => "RT Bounce: $Subject",
422 Explanation => "RT couldn't find the queue: " . $args{'queue'},
423 MIMEObj => $Message );
424 return ( 0, "RT couldn't find the queue: " . $args{'queue'}, undef );
427 # Authentication Level
428 # -1 - Get out. this user has been explicitly declined
429 # 0 - User may not do anything (Not used at the moment)
431 # 2 - User is allowed to specify status updates etc. a la enhanced-mailgate
433 push @RT::MailPlugins, "Auth::MailFrom" unless @RT::MailPlugins;
434 # Since this needs loading, no matter what
436 for (@RT::MailPlugins) {
439 if ( ref($_) eq "CODE" ) {
443 $_ = "RT::Interface::Email::$_" unless /^RT::Interface::Email::/;
446 die ("Couldn't load module $_: $@");
450 if ( !defined( $Code = *{ $_ . "::GetCurrentUser" }{CODE} ) ) {
451 die ("No GetCurrentUser code found in $_ module");
456 ( $CurrentUser, $NewAuthStat ) = $Code->( Message => $Message,
457 CurrentUser => $CurrentUser,
458 AuthLevel => $AuthStat,
459 Action => $args{'action'},
460 Ticket => $SystemTicket,
461 Queue => $SystemQueueObj );
463 # You get the highest level of authentication you were assigned.
464 last if $AuthStat == -1;
465 $AuthStat = $NewAuthStat if $NewAuthStat > $AuthStat;
468 # {{{ If authentication fails and no new user was created, get out.
469 if ( !$CurrentUser or !$CurrentUser->Id or $AuthStat == -1 ) {
471 # If the plugins refused to create one, they lose.
473 Subject => "Could not load a valid user",
474 Explanation => <<EOT,
475 RT could not load a valid user, and RT's configuration does not allow
476 for the creation of a new user for your email.
478 Your RT administrator needs to grant 'Everyone' the right 'CreateTicket'
483 LogLevel => 'error' )
484 unless $AuthStat == -1;
485 return ( 0, "Could not load a valid user", undef );
490 # {{{ Lets check for mail loops of various sorts.
491 my $IsAutoGenerated = CheckForAutoGenerated($head);
493 my $IsSuspiciousSender = CheckForSuspiciousSender($head);
495 my $IsALoop = CheckForLoops($head);
497 my $SquelchReplies = 0;
499 #If the message is autogenerated, we need to know, so we can not
500 # send mail to the sender
501 if ( $IsSuspiciousSender || $IsAutoGenerated || $IsALoop ) {
503 $ErrorsTo = $RT::OwnerEmail;
508 # {{{ Drop it if it's disallowed
509 if ( $AuthStat == 0 ) {
512 Subject => "Permission Denied",
513 Explanation => "You do not have permission to communicate with RT",
514 MIMEObj => $Message );
518 # {{{ Warn someone if it's a loop
520 # Warn someone if it's a loop, before we drop it on the ground
522 $RT::Logger->crit("RT Recieved mail ($MessageId) from itself.");
524 #Should we mail it to RTOwner?
525 if ($RT::LoopsToRTOwner) {
526 MailError( To => $RT::OwnerEmail,
527 Subject => "RT Bounce: $Subject",
528 Explanation => "RT thinks this message may be a bounce",
529 MIMEObj => $Message );
531 #Do we actually want to store it?
532 return ( 0, "Message Bounced", undef ) unless ($RT::StoreLoops);
538 # {{{ Squelch replies if necessary
539 # Don't let the user stuff the RT-Squelch-Replies-To header.
540 if ( $head->get('RT-Squelch-Replies-To') ) {
541 $head->add( 'RT-Relocated-Squelch-Replies-To',
542 $head->get('RT-Squelch-Replies-To') );
543 $head->delete('RT-Squelch-Replies-To');
546 if ($SquelchReplies) {
547 ## TODO: This is a hack. It should be some other way to
548 ## indicate that the transaction should be "silent".
550 my ( $Sender, $junk ) = ParseSenderAddressFromHead($head);
551 $head->add( 'RT-Squelch-Replies-To', $Sender );
556 my $Ticket = RT::Ticket->new($CurrentUser);
558 # {{{ If we don't have a ticket Id, we're creating a new ticket
559 if ( !$args{'ticket'} ) {
561 # {{{ Create a new ticket
564 my @Requestors = ( $CurrentUser->id );
566 if ($RT::ParseNewMessageForTicketCcs) {
567 @Cc = ParseCcAddressesFromHead( Head => $head,
568 CurrentUser => $CurrentUser,
569 QueueObj => $SystemQueueObj );
572 my ( $id, $Transaction, $ErrStr ) = $Ticket->Create(
573 Queue => $SystemQueueObj->Id,
575 Requestor => \@Requestors,
577 MIMEObj => $Message );
579 MailError( To => $ErrorsTo,
580 Subject => "Ticket creation failed",
581 Explanation => $ErrStr,
582 MIMEObj => $Message );
583 $RT::Logger->error("Create failed: $id / $Transaction / $ErrStr ");
584 return ( 0, "Ticket creation failed", $Ticket );
592 # If the action is comment, add a comment.
593 elsif ( $args{'action'} =~ /^(comment|correspond)$/i ) {
594 $Ticket->Load($args{'ticket'});
595 unless ( $Ticket->Id ) {
596 my $message = "Could not find a ticket with id ".$args{'ticket'};
597 MailError( To => $ErrorsTo,
598 Subject => "Message not recorded",
599 Explanation => $message,
600 MIMEObj => $Message );
602 return ( 0, $message);
605 my ( $status, $msg );
606 if ( $args{'action'} =~ /^correspond$/ ) {
607 ( $status, $msg ) = $Ticket->Correspond( MIMEObj => $Message );
610 ( $status, $msg ) = $Ticket->Comment( MIMEObj => $Message );
614 #Warn the sender that we couldn't actually submit the comment.
615 MailError( To => $ErrorsTo,
616 Subject => "Message not recorded",
618 MIMEObj => $Message );
619 return ( 0, "Message not recorded", $Ticket );
625 #Return mail to the sender with an error
626 MailError( To => $ErrorsTo,
627 Subject => "RT Configuration error",
630 . "' not a recognized action."
631 . " Your RT administrator has misconfigured "
632 . "the mail aliases which invoke RT",
633 MIMEObj => $Message );
634 $RT::Logger->crit( $args{'action'} . " type unknown for $MessageId" );
635 return ( 0, "Configuration error: " . $args{'action'} . " not a recognized action", $Ticket );
640 return ( 1, "Success", $Ticket );
643 eval "require RT::Interface::Email_Vendor";
644 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Vendor.pm});
645 eval "require RT::Interface::Email_Local";
646 die $@ if ($@ && $@ !~ qr{^Can't locate RT/Interface/Email_Local.pm});