-
Notifications
You must be signed in to change notification settings - Fork 281
Expand file tree
/
Copy pathEmail.pm
More file actions
1618 lines (1302 loc) · 50.9 KB
/
Email.pm
File metadata and controls
1618 lines (1302 loc) · 50.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# BEGIN BPS TAGGED BLOCK {{{
#
# COPYRIGHT:
#
# This software is Copyright (c) 1996-2025 Best Practical Solutions, LLC
# <sales@bestpractical.com>
#
# (Except where explicitly superseded by other copyright notices)
#
#
# LICENSE:
#
# This work is made available to you under the terms of Version 2 of
# the GNU General Public License. A copy of that license should have
# been provided with this software, but in any event can be snarfed
# from www.gnu.org.
#
# This work is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 or visit their web page on the internet at
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
#
#
# CONTRIBUTION SUBMISSION POLICY:
#
# (The following paragraph is not intended to limit the rights granted
# to you to modify and distribute this software under the terms of
# the GNU General Public License and is only of importance to you if
# you choose to contribute your changes and enhancements to the
# community by submitting them to Best Practical Solutions, LLC.)
#
# By intentionally submitting any modifications, corrections or
# derivatives to this work, or any other work intended for use with
# Request Tracker, to Best Practical Solutions, LLC, you confirm that
# you are the copyright holder for those contributions and you grant
# Best Practical Solutions, LLC a nonexclusive, worldwide, irrevocable,
# royalty-free, perpetual, license to use, copy, create derivative
# works based on those contributions, and sublicense and distribute
# those contributions and any derivatives thereof.
#
# END BPS TAGGED BLOCK }}}
package RT::Interface::Email;
use strict;
use warnings;
use 5.26.3;
use RT::Interface::Email::Crypt;
use Email::Address;
use MIME::Entity;
use RT::EmailParser;
use File::Temp;
use Mail::Mailer ();
use Text::ParseWords qw/shellwords/;
use RT::Util 'safe_run_child';
use File::Spec;
use MIME::Words ();
use Scope::Upper qw/unwind HERE/;
use 5.26.3;
=head1 NAME
RT::Interface::Email - helper functions for parsing and sending email
=head1 METHODS
=head2 RECEIVING MAIL
=head3 Gateway ARGSREF
Takes parameters:
=over
=item C<action>
A C<-> separated list of actions to run. Standard actions, as detailed
in L<bin/rt-mailgate>, are C<comment> and C<correspond>. The
L<RT::Interface::Email::Action::Take> and
L<RT::Interface::Email::Action::Resolve> plugins can be added to
L<RT_Config/@MailPlugins> to provide C<take> and C<resolve> actions,
respectively.
=item C<queue>
The queue that tickets should be created in, if no ticket id is found on
the message. Can be either a name or an id; defaults to 1.
=item C<message>
The content of the message, as obtained from the MTA.
=item C<ticket>
Optional; this ticket id overrides any ticket number derived from the
subject.
=back
Secrypts and verifies the message, decodes the transfer encoding,
determines the user that the mail was sent from, and performs the given
actions.
Returns a list of C<(status, message, ticket)>. The C<status> is -75
for a temporary failure (to be retried later by the MTA), 0 for a
permanent failure which did not result in a ticket, and 1 for a ticket
that was found and acted on.
=cut
my $SCOPE;
sub TMPFAIL { unwind (-75, $_[0], undef, => $SCOPE) }
sub FAILURE { unwind ( 0, $_[0], $_[1], => $SCOPE) }
sub SUCCESS { unwind ( 1, "Success", $_[0], => $SCOPE) }
sub Gateway {
my $argsref = shift;
my %args = (
action => 'correspond',
queue => '1',
ticket => undef,
message => undef,
%$argsref
);
RT->Config->RefreshConfigFromDatabase();
RT->System->MaybeRebuildLifecycleCache();
RT->SetCurrentInterface('Email');
# Set the scope to return from with TMPFAIL/FAILURE/SUCCESS
$SCOPE = HERE;
# Validate the actions
my @actions = grep $_, split /-/, $args{action};
for my $action (@actions) {
TMPFAIL( "Invalid 'action' parameter $action for queue $args{queue}" )
unless Plugins(Method => "Handle" . ucfirst($action));
}
my $parser = RT::EmailParser->new();
$parser->SmartParseMIMEEntityFromScalar(
Message => $args{'message'},
Decode => 0,
Exact => 1,
);
my $Message = $parser->Entity();
unless ($Message) {
MailError(
Subject => "RT Bounce: Unparseable message",
Explanation => "RT couldn't process the message below",
Attach => $args{'message'},
FAILURE => 1,
);
}
# Clean up sensitive headers. Crypt related headers are cleaned up in RT::Interface::Email::Crypt::VerifyDecrypt
my @headers = qw( RT-Attach RT-Send-Cc RT-Send-Bcc RT-Message-ID RT-DetectedAutoGenerated RT-Squelch-Replies-To );
$Message->head->delete($_) for @headers;
#Set up a queue object
my $SystemQueueObj = RT::Queue->new( RT->SystemUser );
$SystemQueueObj->Load( $args{'queue'} );
for my $Code ( Plugins(Method => "BeforeDecrypt") ) {
$Code->(
Message => $Message,
RawMessageRef => \$args{'message'},
Queue => $SystemQueueObj,
Actions => \@actions,
);
}
RT::Interface::Email::Crypt::VerifyDecrypt(
Message => $Message,
RawMessageRef => \$args{'message'},
Queue => $SystemQueueObj,
);
for my $Code ( Plugins(Method => "BeforeDecode") ) {
$Code->(
Message => $Message,
RawMessageRef => \$args{'message'},
Queue => $SystemQueueObj,
Actions => \@actions,
);
}
$parser->_DecodeBodies;
$parser->RescueOutlook;
$parser->_PostProcessNewEntity;
my $head = $Message->head;
my $From = Encode::decode( "UTF-8", $head->get("From") );
chomp $From if defined $From;
#Pull apart the subject line
my $Subject = Encode::decode( "UTF-8", $head->get('Subject') || '');
chomp $Subject;
# Lets check for mail loops of various sorts.
my $ErrorsTo = ParseErrorsToAddressFromHead( $head );
$ErrorsTo = RT->Config->Get('OwnerEmail')
if IsMachineGeneratedMail(
Message => $Message,
Subject => $Subject,
);
# Make all errors from here on out bounce back to $ErrorsTo
my $bare_MailError = \&MailError;
no warnings 'redefine';
local *MailError = sub {
$bare_MailError->(To => $ErrorsTo, MIMEObj => $Message, @_)
};
$args{'ticket'} ||= ExtractTicketId( $Message );
my $SystemTicket = RT::Ticket->new( RT->SystemUser );
$SystemTicket->Load( $args{'ticket'} ) if ( $args{'ticket'} ) ;
# We can safely have no queue of we have a known-good ticket
TMPFAIL("RT couldn't find the queue: " . $args{'queue'})
unless $SystemTicket->id || $SystemQueueObj->id;
my $CurrentUser = GetCurrentUser(
Message => $Message,
RawMessageRef => \$args{message},
Ticket => $SystemTicket,
Queue => $SystemQueueObj,
RawAction => $args{action},
);
# We only care about ACLs on the _first_ action, as later actions
# may have gotten rights by the time they happen.
CheckACL(
Action => $actions[0],
Message => $Message,
CurrentUser => $CurrentUser,
Ticket => $SystemTicket,
Queue => $SystemQueueObj,
);
$head->replace('X-RT-Interface' => 'Email');
my $Ticket = RT::Ticket->new($CurrentUser);
$Ticket->Load( $SystemTicket->Id );
for my $action (@actions) {
HandleAction(
Action => $action,
Subject => $Subject,
Message => $Message,
CurrentUser => $CurrentUser,
Ticket => $Ticket,
TicketId => $args{ticket},
Queue => $SystemQueueObj,
);
}
SUCCESS( $Ticket );
}
=head3 Plugins Method => C<name>, Code => 0
Returns the list of subroutine references for the given method C<name>
from the configured L<RT_Config/@MailPlugins>. If C<Code> is passed a
true value, includes anonymous subroutines found in C<@MailPlugins>.
=cut
sub Plugins {
my %args = (
Add => undef,
Code => 0,
Method => undef,
@_
);
state $INIT;
state @PLUGINS;
if ($args{Add} or !$INIT) {
my @mail_plugins = $INIT ? () : RT->Config->Get('MailPlugins');
push @mail_plugins, @{$args{Add}} if $args{Add};
foreach my $plugin (@mail_plugins) {
if ( ref($plugin) eq "CODE" ) {
push @PLUGINS, $plugin;
} elsif ( !ref $plugin ) {
my $Class = $plugin;
$Class = "RT::Interface::Email::" . $Class
unless $Class =~ /^RT::/;
RT::StaticUtil::RequireModule($Class) or
do { $RT::Logger->error("Couldn't load $Class: $@"); next };
unless ( $Class->DOES( "RT::Interface::Email::Role" ) ) {
$RT::Logger->crit( "$Class does not implement RT::Interface::Email::Role. Mail plugins from RT 4.2 and earlier are not forward-compatible with RT 4.4.");
next;
}
push @PLUGINS, $Class;
} else {
$RT::Logger->crit( "$plugin - is not class name or code reference");
}
}
$INIT = 1;
}
my @list = @PLUGINS;
@list = grep {not ref} @list unless $args{Code};
@list = grep {$_} map {ref $_ ? $_ : $_->can($args{Method})} @list if $args{Method};
return @list;
}
=head3 GetCurrentUser Message => C<message>, Ticket => C<ticket>, Queue => C<queue>
Dispatches to the C<@MailPlugins> to find one the provides
C<GetCurrentUser> that recognizes the current user. Mail plugins are
tried one at a time, and stops after the first to return a current user.
Anonymous subroutine references found in C<@MailPlugins> are treated as
C<GetCurrentUser> methods.
The default GetCurrentUser authenticator simply looks at the From:
address, and loads or creates a user accordingly; see
L<RT::Interface::Email::Auth::MailFrom>.
Returns the current user; on failure of any plugin to do so, stops
processing with a permanent failure and sends a generic "Permission
Denied" mail to the user.
=cut
sub GetCurrentUser {
my %args = (
Message => undef,
RawMessageRef => undef,
Ticket => undef,
Queue => undef,
RawAction => undef,
@_,
);
# Since this needs loading, no matter what
for my $Code ( Plugins(Code => 1, Method => "GetCurrentUser") ) {
my $CurrentUser = $Code->(
Message => $args{Message},
RawMessageRef => $args{RawMessageRef},
Ticket => $args{Ticket},
Queue => $args{Queue},
RawAction => $args{RawAction},
);
return $CurrentUser if $CurrentUser and $CurrentUser->id;
}
# None of the GetCurrentUser plugins found a user. This is
# rare; some non-Auth::MailFrom authentication plugin which
# doesn't always return a current user?
MailError(
Subject => "Permission Denied",
Explanation => "You do not have permission to communicate with RT",
FAILURE => 1,
);
}
=head3 CheckACL Action => C<action>, CurrentUser => C<user>, Ticket => C<ticket>, Queue => C<queue>
Checks that the CurrentUser can perform a particular action. While RT's
standard permission controls apply, this allows a better error message,
or more limited restrictions on the email gateway.
Each plugin in C<@MailPlugins> which provides C<CheckACL> is given a
chance to allow the action. If any returns a true value, it
short-circuits all later plugins. Note that plugins may short-circuit
and abort with failure of their own accord.
Aborts processing, sending a "Permission Denied" mail to the user with
the last plugin's failure message, on failure.
=cut
sub CheckACL {
my %args = (
Action => undef,
Message => undef,
CurrentUser => undef,
Ticket => undef,
Queue => undef,
@_,
);
for my $Code ( Plugins( Method => "CheckACL" ) ) {
return if $Code->(
Message => $args{Message},
CurrentUser => $args{CurrentUser},
Action => $args{Action},
Ticket => $args{Ticket},
Queue => $args{Queue},
);
}
# Nobody said yes, and nobody said FAILURE; fail closed
MailError(
Subject => "Permission Denied",
Explanation => "You have no permission to $args{Action}",
FAILURE => 1,
);
}
=head3 HandleAction Action => C<action>, Message => C<message>, Ticket => C<ticket>, Queue => C<queue>
Dispatches to the first plugin in C<@MailPlugins> which provides a
C<HandleFoo> where C<Foo> is C<ucfirst(action)>.
=cut
sub HandleAction {
my %args = (
Action => undef,
Subject => undef,
Message => undef,
Ticket => undef,
TicketId => undef,
Queue => undef,
@_
);
my $action = delete $args{Action};
my ($code) = Plugins(Method => "Handle" . ucfirst($action));
TMPFAIL( "Invalid 'action' parameter $action for queue ".$args{Queue}->Name )
unless $code;
$code->(%args);
}
=head3 ParseSenderAddressFromHead HEAD
Takes a L<MIME::Header> object. Returns a list of (email address,
friendly name, errors) where the address and name are the first address
found in C<Reply-To>, C<From>, or C<Sender>.
A list of error messages may be returned even when an address is found,
since it could be a parse error for another (checked earlier) sender
field. In this case, the errors aren't fatal, but may be useful to
investigate the parse failure.
=cut
sub ParseSenderAddressFromHead {
my $head = shift;
my @errors; # Accumulate any errors
foreach my $header ( 'Reply-To', 'From', 'Sender' ) {
my $addr_line = Encode::decode( "UTF-8", $head->get($header) ) || next;
my ($addr) = RT::EmailParser->ParseEmailAddress( $addr_line );
return ($addr->address, $addr->phrase, @errors) if $addr;
chomp $addr_line;
push @errors, "$header: $addr_line";
}
return (undef, undef, @errors);
}
=head3 ParseErrorsToAddressFromHead HEAD
Takes a L<MIME::Header> object. Returns the first email address found in
C<Return-path>, C<Errors-To>, C<Reply-To>, C<From>, or C<Sender>.
=cut
sub ParseErrorsToAddressFromHead {
my $head = shift;
foreach my $header ( 'Errors-To', 'Reply-To', 'From', 'Sender' ) {
my $value = Encode::decode( "UTF-8", $head->get($header) );
next unless $value;
my ( $email ) = RT::EmailParser->ParseEmailAddress($value);
return $email->address if $email;
}
}
=head3 IsMachineGeneratedMail Message => C<message>
Checks if the mail is machine-generated (via a bounce, mail headers,
=cut
sub IsMachineGeneratedMail {
my %args = (
Message => undef,
Subject => undef,
@_
);
my $head = $args{'Message'}->head;
my $IsAutoGenerated = CheckForAutoGenerated($head);
my $IsALoop = CheckForLoops($head);
my $owner_mail = RT->Config->Get('OwnerEmail');
# Don't let the user stuff the RT-Squelch-Replies-To header.
$head->delete('RT-Squelch-Replies-To');
# If the message is autogenerated, we need to know, so we can not
# send mail to the sender
return unless $IsAutoGenerated || $IsALoop;
# Warn someone if it's a loop, before we drop it on the ground
if ($IsALoop) {
my $MessageId = Encode::decode( "UTF-8", $head->get('Message-ID') );
$RT::Logger->crit("RT Received mail ($MessageId) from itself.");
#Should we mail it to RTOwner?
if ( RT->Config->Get('LoopsToRTOwner') ) {
MailError(
To => $owner_mail,
Subject => "RT Bounce: ".$args{'Subject'},
Explanation => "RT thinks this message may be a bounce",
);
}
#Do we actually want to store it?
FAILURE( "Message is a bounce" ) unless RT->Config->Get('StoreLoops');
}
# Squelch replies to the sender, and also leave a clue to
# allow us to squelch ALL outbound messages. This way we
# can punt the logic of "what to do when we get a bounce"
# to the scrip. We might want to notify nobody. Or just
# the RT Owner. Or maybe all Privileged watchers.
my ( $Sender ) = ParseSenderAddressFromHead($head);
$head->replace( 'RT-Squelch-Replies-To', Encode::encode("UTF-8", $Sender ) );
$head->replace( 'RT-DetectedAutoGenerated', 'true' );
return 1;
}
=head3 CheckForLoops HEAD
Takes a L<MIME::Head> object and returns true if the message was sent by
this RT instance, by checking the C<X-RT-Loop-Prevention> header.
=cut
sub CheckForLoops {
my $head = shift;
# If this instance of RT sent it our, we don't want to take it in
my $RTLoop = Encode::decode( "UTF-8", $head->get("X-RT-Loop-Prevention") || "" );
chomp ($RTLoop); # remove that newline
if ( $RTLoop eq RT->Config->Get('rtname') ) {
return 1;
}
# TODO: We might not trap the case where RT instance A sends a mail
# to RT instance B which sends a mail to ...
return undef;
}
=head3 CheckForAutoGenerated HEAD
Takes a HEAD object of L<MIME::Head> class and returns true if message is
auto-generated. Checks C<Precedence>, RFC3834 C<Auto-Submitted>, and
C<X-FC-Machinegenerated> fields of the head in tests.
=cut
sub CheckForAutoGenerated {
my $head = shift;
# Bounces, via return-path
my $ReturnPath = $head->get("Return-path") || "";
return 1 if $ReturnPath =~ /<>/;
# Bounces, via mailer-daemon or postmaster
my ( $From ) = ParseSenderAddressFromHead($head);
return 1 if defined $From and $From =~ /^mailer-daemon\@/i;
return 1 if defined $From and $From =~ /^postmaster\@/i;
return 1 if defined $From and $From eq "";
# Bulk or junk messages are auto-generated
return 1 if grep {/^(bulk|junk)/i} $head->get_all("Precedence");
# Per RFC3834, any Auto-Submitted header which is not "no" means
# it is auto-generated.
my $AutoSubmitted = $head->get("Auto-Submitted") || "";
chomp $AutoSubmitted;
$AutoSubmitted =~ s/^\s+|\s+$//g;
return 1 if length $AutoSubmitted and $AutoSubmitted ne "no";
# First Class mailer uses this as a clue.
my $FCJunk = $head->get("X-FC-Machinegenerated") || "";
return 1 if $FCJunk =~ /^true/i;
return 0;
}
=head3 ExtractTicketId
Passed a L<MIME::Entity> object, and returns a either ticket id or undef
to signal 'new ticket'.
This is a great entry point if you need to customize how ticket ids are
handled for your site. L<RT::Extension::RepliesToResolved> demonstrates
one possible use for this extension.
If the Subject of the L<MIME::Entity> is modified, the updated subject
will be used during ticket creation.
=cut
sub ExtractTicketId {
my $entity = shift;
my $subject = Encode::decode( "UTF-8", $entity->head->get('Subject') || '' );
chomp $subject;
return ParseTicketId( $subject, $entity );
}
=head3 ParseTicketId
Takes a string (the email subject) and searches for [subjecttag #id]
For customizations, the L<MIME::Entity> object is passed as the second
argument.
Returns the id if a match is found. Otherwise returns undef.
=cut
sub ParseTicketId {
my $Subject = shift;
my $Entity = shift;
my $rtname = RT->Config->Get('rtname');
my $test_name = RT->Config->Get('EmailSubjectTagRegex') || qr/\Q$rtname\E/i;
# We use @captures and pull out the last capture value to guard against
# someone using (...) instead of (?:...) in $EmailSubjectTagRegex.
my $id;
if ( my @captures = $Subject =~ m{\[(?:https?://)?$test_name\s+\#(\d+)\s*\]}i ) {
$id = $captures[-1];
} else {
foreach my $tag ( RT->System->SubjectTag ) {
next unless my @captures = $Subject =~ m{\[(?:https?://)?\Q$tag\E\s+\#(\d+)\s*\]}i;
$id = $captures[-1];
last;
}
}
return undef unless $id;
$RT::Logger->debug("Found a ticket ID. It's $id");
return $id;
}
=head3 MailError PARAM HASH
Sends an error message. Takes a param hash:
=over 4
=item From
Sender's address, defaults to L<RT_Config/$CorrespondAddress>;
=item To
Recipient, defaults to L<RT_Config/$OwnerEmail>;
=item Subject
Subject of the message, defaults to C<There has been an error>;
=item Explanation
Main content of the error, default value is C<Unexplained error>;
=item MIMEObj
Optional L<MIME::Entity> that is attached to the error mail.
Additionally, the C<In-Reply-To> header will point to this message.
=item Attach
Optional text that attached to the error as a C<message/rfc822> part.
=item LogLevel
Log level the subject and explanation is written to the log; defaults to
C<critical>.
=back
=cut
sub MailError {
my %args = (
To => RT->Config->Get('OwnerEmail'),
From => RT->Config->Get('CorrespondAddress'),
Subject => 'There has been an error',
Explanation => 'Unexplained error',
MIMEObj => undef,
Attach => undef,
LogLevel => 'crit',
FAILURE => 0,
@_
);
$RT::Logger->log(
level => $args{'LogLevel'},
message => "$args{Subject}: $args{'Explanation'}",
) if $args{'LogLevel'};
# the colons are necessary to make ->build include non-standard headers
my %entity_args = (
Type => "multipart/mixed",
From => Encode::encode( "UTF-8", $args{'From'} ),
To => Encode::encode( "UTF-8", $args{'To'} ),
Subject => EncodeToMIME( String => $args{'Subject'} ),
'X-RT-Loop-Prevention:' => Encode::encode( "UTF-8", RT->Config->Get('rtname') ),
);
# only set precedence if the sysadmin wants us to
if (defined(RT->Config->Get('DefaultErrorMailPrecedence'))) {
$entity_args{'Precedence:'} =
Encode::encode( "UTF-8", RT->Config->Get('DefaultErrorMailPrecedence') );
}
my $entity = MIME::Entity->build(%entity_args);
SetInReplyTo( Message => $entity, InReplyTo => $args{'MIMEObj'} );
$entity->attach(
Type => "text/plain",
Charset => "UTF-8",
Data => Encode::encode( "UTF-8", $args{'Explanation'} . "\n" ),
);
if ( $args{'MIMEObj'} ) {
$args{'MIMEObj'}->sync_headers;
$entity->add_part( $args{'MIMEObj'} );
}
if ( $args{'Attach'} ) {
$entity->attach( Data => Encode::encode( "UTF-8", $args{'Attach'} ), Type => 'message/rfc822' );
}
SendEmail( Entity => $entity, Bounce => 1 );
FAILURE( "$args{Subject}: $args{Explanation}" ) if $args{FAILURE};
}
sub _OutgoingMailFrom {
my $TicketObj = shift;
my $MailFrom = RT->Config->Get('SetOutgoingMailFrom');
my $OutgoingMailAddress = $MailFrom =~ /\@/ ? $MailFrom : undef;
my $Overrides = RT->Config->Get('OverrideOutgoingMailFrom') || {};
if ($TicketObj) {
my $Queue = $TicketObj->QueueObj;
my $QueueAddressOverride = $Overrides->{$Queue->id}
|| $Overrides->{$Queue->Name};
if ($QueueAddressOverride) {
$OutgoingMailAddress = $QueueAddressOverride;
} else {
$OutgoingMailAddress ||= $Queue->CorrespondAddress
|| RT->Config->Get('CorrespondAddress');
}
}
elsif ($Overrides->{'Default'}) {
$OutgoingMailAddress = $Overrides->{'Default'};
}
$OutgoingMailAddress =~ s!__TicketID__!$TicketObj ? $TicketObj->Id : ''!egi;
return $OutgoingMailAddress;
}
=head2 SENDING EMAIL
=head3 SendEmail Entity => undef, [ Bounce => 0, Ticket => undef, Transaction => undef ]
Sends an email (passed as a L<MIME::Entity> object C<ENTITY>) using
RT's outgoing mail configuration. If C<BOUNCE> is passed, and is a
true value, the message will be marked as an auto-generated error, if
possible. Sets Date field of the head to now if it's not set.
If the C<X-RT-Squelch> header is set to any true value, the mail will
not be sent. One use is to let extensions easily cancel outgoing mail.
Ticket and Transaction arguments are optional. If Transaction is
specified and Ticket is not then ticket of the transaction is
used, but only if the transaction belongs to a ticket.
Returns 1 on success, 0 on error or -1 if message has no recipients
and hasn't been sent.
=head3 Signing and Encrypting
This function as well signs and/or encrypts the message according to
headers of a transaction's attachment or properties of a ticket's queue.
To get full access to the configuration Ticket and/or Transaction
arguments must be provided, but you can force behaviour using Sign
and/or Encrypt arguments.
The following precedence of arguments are used to figure out if
the message should be encrypted and/or signed:
* if Sign or Encrypt argument is defined then its value is used
* else if Transaction's first attachment has X-RT-Sign or X-RT-Encrypt
header field then it's value is used
* else properties of a queue of the Ticket are used.
=cut
sub SendEmail {
my (%args) = (
Entity => undef,
Bounce => 0,
Ticket => undef,
Transaction => undef,
@_,
);
my $TicketObj = $args{'Ticket'};
my $TransactionObj = $args{'Transaction'};
unless ( $args{'Entity'} ) {
$RT::Logger->crit( "Could not send mail without 'Entity' object" );
return 0;
}
my $msgid = Encode::decode( "UTF-8", $args{'Entity'}->head->get('Message-ID') || '' );
chomp $msgid;
# If we don't have any recipients to send to, don't send a message;
unless ( $args{'Entity'}->head->get('To')
|| $args{'Entity'}->head->get('Cc')
|| $args{'Entity'}->head->get('Bcc') )
{
$RT::Logger->info( $msgid . " No recipients found. Not sending." );
return -1;
}
if ($args{'Entity'}->head->get('X-RT-Squelch')) {
$RT::Logger->info( $msgid . " Squelch header found. Not sending." );
return -1;
}
if (my $precedence = RT->Config->Get('DefaultMailPrecedence')
and !$args{'Entity'}->head->get("Precedence")
) {
if ($TicketObj) {
my $Overrides = RT->Config->Get('OverrideMailPrecedence') || {};
my $Queue = $TicketObj->QueueObj;
$precedence = $Overrides->{$Queue->id}
if exists $Overrides->{$Queue->id};
$precedence = $Overrides->{$Queue->Name}
if exists $Overrides->{$Queue->Name};
}
$args{'Entity'}->head->replace( 'Precedence', Encode::encode("UTF-8",$precedence) )
if $precedence;
}
if ( $TransactionObj && !$TicketObj
&& $TransactionObj->ObjectType eq 'RT::Ticket' )
{
$TicketObj = $TransactionObj->Object;
}
my $head = $args{'Entity'}->head;
unless ( $head->get('Date') ) {
require RT::Date;
my $date = RT::Date->new( RT->SystemUser );
$date->SetToNow;
$head->replace( 'Date', Encode::encode("UTF-8",$date->RFC2822( Timezone => 'server' ) ) );
}
unless ( $head->get('MIME-Version') ) {
# We should never have to set the MIME-Version header
$head->replace( 'MIME-Version', '1.0' );
}
unless ( $head->get('Content-Transfer-Encoding') ) {
# fsck.com #5959: Since RT sends 8bit mail, we should say so.
$head->replace( 'Content-Transfer-Encoding', '8bit' );
}
if ( RT->Config->Get('Crypt')->{'Enable'} ) {
%args = WillSignEncrypt(
%args,
Attachment => $TransactionObj ? $TransactionObj->Attachments->First : undef,
Ticket => $TicketObj,
);
if ($TicketObj) {
$args{'Queue'} = $TicketObj->QueueObj;
}
my $res = SignEncrypt( %args );
return $res unless $res > 0;
}
my $mail_command = RT->Config->Get('MailCommand');
# if it is a sub routine, we just return it;
return $mail_command->($args{'Entity'}) if UNIVERSAL::isa( $mail_command, 'CODE' );
if ( $mail_command eq 'sendmailpipe' ) {
my $path = RT->Config->Get('SendmailPath');
my @args;
# SetOutgoingMailFrom and bounces conflict, since they both want -f
if ( $args{'Bounce'} ) {
@args = shellwords( RT->Config->Get('SendmailBounceArguments') );
}
else {
@args = shellwords( RT->Config->Get('SendmailArguments') );
if ( RT->Config->Get('SetOutgoingMailFrom') ) {
my $OutgoingMailAddress = _OutgoingMailFrom($TicketObj);
push @args, "-f", $OutgoingMailAddress if $OutgoingMailAddress;
}
}
push @args, "-t" unless grep {$_ eq "-t"} @args;
# VERP
if ( $TransactionObj and
my $prefix = RT->Config->Get('VERPPrefix') and
my $domain = RT->Config->Get('VERPDomain') )
{
my $from = $TransactionObj->CreatorObj->EmailAddress;
$from =~ s/@/=/g;
$from =~ s/\s//g;
push @args, "-f", "$prefix$from\@$domain";
}
eval {
# don't ignore CHLD signal to get proper exit code
local $SIG{'CHLD'} = 'DEFAULT';
# if something wrong with $mail->print we will get PIPE signal, handle it
local $SIG{'PIPE'} = sub { die "program unexpectedly closed pipe" };
require IPC::Open2;
my ($mail, $stdout);
my $pid = IPC::Open2::open2( $stdout, $mail, $path, @args )
or die "couldn't execute program: $!";
$args{'Entity'}->print($mail);
close $mail or die "close pipe failed: $!";
waitpid($pid, 0);
if ($?) {
# sendmail exit statuses mostly errors with data not software
# TODO: status parsing: core dump, exit on signal or EX_*
my $msg = "$msgid: `$path @args` exited with code ". ($?>>8);
$msg = ", interrupted by signal ". ($?&127) if $?&127;
$RT::Logger->error( $msg );
die $msg;
}
};
if ( $@ ) {
$RT::Logger->crit( "$msgid: Could not send mail with command `$path @args`: " . $@ );
if ( $TicketObj ) {
_RecordSendEmailFailure( $TicketObj );
}
return 0;
}
} elsif ( $mail_command eq 'mbox' ) {
my $now = RT::Date->new(RT->SystemUser);
$now->SetToNow;
state $logfile;
unless ($logfile) {
my $when = $now->ISO( Timezone => "server" );
$when =~ s/\s+/-/g;
$logfile = "$RT::VarPath/$when.mbox";
$RT::Logger->info("Storing outgoing emails in $logfile");
}
my $fh;
unless (open($fh, ">>", $logfile)) {
$RT::Logger->crit( "Can't open mbox file $logfile: $!" );
return 0;
}
my $content = $args{Entity}->stringify;
$content =~ s/^(>*From )/>$1/mg;
my $user = $ENV{USER} || getpwuid($<);
print $fh "From $user\@localhost ".localtime()."\n";
print $fh $content, "\n";
close $fh;
} else {
local ($ENV{'MAILADDRESS'}, $ENV{'PERL_MAILERS'});