-
Notifications
You must be signed in to change notification settings - Fork 399
/
sendEmail
executable file
·2183 lines (1636 loc) · 76.1 KB
/
sendEmail
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
#!/usr/bin/perl -w
##############################################################################
## sendEmail
## Written by: Brandon Zehm <[email protected]>
##
## License:
## sendEmail (hereafter referred to as "program") is free software;
## you can redistribute it and/or modify it under the terms of the GNU General
## Public License as published by the Free Software Foundation; either version
## 2 of the License, or (at your option) any later version.
## When redistributing modified versions of this source code it is recommended
## that that this disclaimer and the above coder's names are included in the
## modified code.
##
## Disclaimer:
## This program is provided with no warranty of any kind, either expressed or
## implied. It is the responsibility of the user (you) to fully research and
## comprehend the usage of this program. As with any tool, it can be misused,
## either intentionally (you're a vandal) or unintentionally (you're a moron).
## THE AUTHOR(S) IS(ARE) NOT RESPONSIBLE FOR ANYTHING YOU DO WITH THIS PROGRAM
## or anything that happens because of your use (or misuse) of this program,
## including but not limited to anything you, your lawyers, or anyone else
## can dream up. And now, a relevant quote directly from the GPL:
##
## NO WARRANTY
##
## 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
## FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
## OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
## PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
## OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
## MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
## TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
## PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
## REPAIR OR CORRECTION.
##
##############################################################################
use strict;
use IO::Socket;
########################
## Global Variables ##
########################
my %conf = (
## General
"programName" => $0, ## The name of this program
"version" => '1.55', ## The version of this program
"authorName" => 'Brandon Zehm', ## Author's Name
"authorEmail" => '[email protected]', ## Author's Email Address
"timezone" => '+0000', ## We always use +0000 for the time zone
"hostname" => 'changeme', ## Used in printmsg() for all output (is updated later in the script).
"debug" => 0, ## Default debug level
"error" => '', ## Error messages will often be stored here
## Logging
"stdout" => 1,
"logging" => 0, ## If this is true the printmsg function prints to the log file
"logFile" => '', ## If this is specified (form the command line via -l) this file will be used for logging.
## Network
"server" => 'localhost', ## Default SMTP server
"port" => 25, ## Default port
"bindaddr" => '', ## Default local bind address
"alarm" => '', ## Default timeout for connects and reads, this gets set from $opt{'timeout'}
"tls_client" => 0, ## If TLS is supported by the client (us)
"tls_server" => 0, ## If TLS is supported by the remote SMTP server
## Email
"delimiter" => "----MIME delimiter for sendEmail-" ## MIME Delimiter
. rand(1000000), ## Add some randomness to the delimiter
"Message-ID" => rand(1000000) . "-sendEmail", ## Message-ID for email header
);
## This hash stores the options passed on the command line via the -o option.
my %opt = (
## Addressing
"reply-to" => '', ## Reply-To field
## Message
"message-file" => '', ## File to read message body from
"message-header" => '', ## Additional email header line(s)
"message-format" => 'normal', ## If "raw" is specified the message is sent unmodified
"message-charset" => 'iso-8859-1', ## Message character-set
## Network
"timeout" => 60, ## Default timeout for connects and reads, this is copied to $conf{'alarm'} later.
"fqdn" => 'changeme', ## FQDN of this machine, used during SMTP communication (is updated later in the script).
## eSMTP
"username" => '', ## Username used in SMTP Auth
"password" => '', ## Password used in SMTP Auth
"tls" => 'auto', ## Enable or disable TLS support. Options: auto, yes, no
);
## More variables used later in the program
my $SERVER;
my $CRLF = "\015\012";
my $subject = '';
my $header = '';
my $message = '';
my $from = '';
my @to = ();
my @cc = ();
my @bcc = ();
my @attachments = ();
my @attachments_names = ();
## For printing colors to the console
my ${colorRed} = "\033[31;1m";
my ${colorGreen} = "\033[32;1m";
my ${colorCyan} = "\033[36;1m";
my ${colorWhite} = "\033[37;1m";
my ${colorNormal} = "\033[m";
my ${colorBold} = "\033[1m";
my ${colorNoBold} = "\033[0m";
## Don't use shell escape codes on Windows systems
if ($^O =~ /win/i) {
${colorRed} = ""; ${colorGreen} = ""; ${colorCyan} = "";
${colorWhite} = ""; ${colorNormal} = ""; ${colorBold} = ""; ${colorNoBold} = "";
}
## Load IO::Socket::SSL if it's available
eval { require IO::Socket::SSL; };
if ($@) { $conf{'tls_client'} = 0; }
else { $conf{'tls_client'} = 1; }
#############################
## ##
## FUNCTIONS ##
## ##
#############################
###############################################################################################
## Function: initialize ()
##
## Does all the script startup jibberish.
##
###############################################################################################
sub initialize {
## Set STDOUT to flush immediatly after each print
$| = 1;
## Intercept signals
$SIG{'QUIT'} = sub { quit("EXITING: Received SIG$_[0]", 1); };
$SIG{'INT'} = sub { quit("EXITING: Received SIG$_[0]", 1); };
$SIG{'KILL'} = sub { quit("EXITING: Received SIG$_[0]", 1); };
$SIG{'TERM'} = sub { quit("EXITING: Received SIG$_[0]", 1); };
## ALARM and HUP signals are not supported in Win32
unless ($^O =~ /win/i) {
$SIG{'HUP'} = sub { quit("EXITING: Received SIG$_[0]", 1); };
$SIG{'ALRM'} = sub { quit("EXITING: Received SIG$_[0]", 1); };
}
## Fixup $conf{'programName'}
$conf{'programName'} =~ s/(.)*[\/,\\]//;
$0 = $conf{'programName'} . " " . join(" ", @ARGV);
## Fixup $conf{'hostname'} and $opt{'fqdn'}
if ($opt{'fqdn'} eq 'changeme') { $opt{'fqdn'} = get_hostname(1); }
if ($conf{'hostname'} eq 'changeme') { $conf{'hostname'} = $opt{'fqdn'}; $conf{'hostname'} =~ s/\..*//; }
return(1);
}
###############################################################################################
## Function: processCommandLine ()
##
## Processes command line storing important data in global vars (usually %conf)
##
###############################################################################################
sub processCommandLine {
############################
## Process command line ##
############################
my @ARGS = @ARGV; ## This is so later we can re-parse the command line args later if we need to
my $numargv = @ARGS;
help() unless ($numargv);
my $counter = 0;
for ($counter = 0; $counter < $numargv; $counter++) {
if ($ARGS[$counter] =~ /^-h$/i) { ## Help ##
help();
}
elsif ($ARGS[$counter] eq "") { ## Ignore null arguments
## Do nothing
}
elsif ($ARGS[$counter] =~ /^--help/) { ## Topical Help ##
$counter++;
if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
helpTopic($ARGS[$counter]);
}
else {
help();
}
}
elsif ($ARGS[$counter] =~ /^-o$/i) { ## Options specified with -o ##
$counter++;
## Loop through each option passed after the -o
while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
if ($ARGS[$counter] !~ /(\S+)=(\S.*)/) {
printmsg("WARNING => Name/Value pair [$ARGS[$counter]] is not properly formatted", 0);
printmsg("WARNING => Arguments proceeding -o should be in the form of \"name=value\"", 0);
}
else {
if (exists($opt{$1})) {
if ($1 eq 'message-header') {
$opt{$1} .= $2 . $CRLF;
}
else {
$opt{$1} = $2;
}
printmsg("DEBUG => Assigned \$opt{} key/value: $1 => $2", 3);
}
else {
printmsg("WARNING => Name/Value pair [$ARGS[$counter]] will be ignored: unknown key [$1]", 0);
printmsg("HINT => Try the --help option to find valid command line arguments", 1);
}
}
$counter++;
} $counter--;
}
elsif ($ARGS[$counter] =~ /^-f$/) { ## From ##
$counter++;
if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { $from = $ARGS[$counter]; }
else { printmsg("WARNING => The argument after -f was not an email address!", 0); $counter--; }
}
elsif ($ARGS[$counter] =~ /^-t$/) { ## To ##
$counter++;
while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
if ($ARGS[$counter] =~ /[;,]/) {
push (@to, split(/[;,]/, $ARGS[$counter]));
}
else {
push (@to,$ARGS[$counter]);
}
$counter++;
} $counter--;
}
elsif ($ARGS[$counter] =~ /^-cc$/) { ## Cc ##
$counter++;
while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
if ($ARGS[$counter] =~ /[;,]/) {
push (@cc, split(/[;,]/, $ARGS[$counter]));
}
else {
push (@cc,$ARGS[$counter]);
}
$counter++;
} $counter--;
}
elsif ($ARGS[$counter] =~ /^-bcc$/) { ## Bcc ##
$counter++;
while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
if ($ARGS[$counter] =~ /[;,]/) {
push (@bcc, split(/[;,]/, $ARGS[$counter]));
}
else {
push (@bcc,$ARGS[$counter]);
}
$counter++;
} $counter--;
}
elsif ($ARGS[$counter] =~ /^-m$/) { ## Message ##
$counter++;
$message = "";
while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
if ($message) { $message .= " "; }
$message .= $ARGS[$counter];
$counter++;
} $counter--;
## Replace '\n' with $CRLF.
## This allows newlines with messages sent on the command line
$message =~ s/\\n/$CRLF/g;
}
elsif ($ARGS[$counter] =~ /^-u$/) { ## Subject ##
$counter++;
$subject = "";
while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
if ($subject) { $subject .= " "; }
$subject .= $ARGS[$counter];
$counter++;
} $counter--;
}
elsif ($ARGS[$counter] =~ /^-s$/) { ## Server ##
$counter++;
if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
$conf{'server'} = $ARGS[$counter];
if ($conf{'server'} =~ /:/) { ## Port ##
($conf{'server'},$conf{'port'}) = split(":",$conf{'server'});
}
}
else { printmsg("WARNING - The argument after -s was not the server!", 0); $counter--; }
}
elsif ($ARGS[$counter] =~ /^-b$/) { ## Bind Address ##
$counter++;
if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
$conf{'bindaddr'} = $ARGS[$counter];
}
else { printmsg("WARNING - The argument after -b was not the bindaddr!", 0); $counter--; }
}
elsif ($ARGS[$counter] =~ /^-a$/) { ## Attachments ##
$counter++;
while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
push (@attachments,$ARGS[$counter]);
$counter++;
} $counter--;
}
elsif ($ARGS[$counter] =~ /^-xu$/) { ## AuthSMTP Username ##
$counter++;
if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
$opt{'username'} = $ARGS[$counter];
}
else {
printmsg("WARNING => The argument after -xu was not valid username!", 0);
$counter--;
}
}
elsif ($ARGS[$counter] =~ /^-xp$/) { ## AuthSMTP Password ##
$counter++;
if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
$opt{'password'} = $ARGS[$counter];
}
else {
printmsg("WARNING => The argument after -xp was not valid password!", 0);
$counter--;
}
}
elsif ($ARGS[$counter] =~ /^-l$/) { ## Logging ##
$counter++;
$conf{'logging'} = 1;
if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { $conf{'logFile'} = $ARGS[$counter]; }
else { printmsg("WARNING - The argument after -l was not the log file!", 0); $counter--; }
}
elsif ($ARGS[$counter] =~ s/^-v+//i) { ## Verbosity ##
my $tmp = (length($&) - 1);
$conf{'debug'} += $tmp;
}
elsif ($ARGS[$counter] =~ /^-q$/) { ## Quiet ##
$conf{'stdout'} = 0;
}
else {
printmsg("Error: \"$ARGS[$counter]\" is not a recognized option!", 0);
help();
}
}
###################################################
## Verify required variables are set correctly ##
###################################################
## Make sure we have something in $conf{hostname} and $opt{fqdn}
if ($opt{'fqdn'} =~ /\./) {
$conf{'hostname'} = $opt{'fqdn'};
$conf{'hostname'} =~ s/\..*//;
}
if (!$conf{'server'}) { $conf{'server'} = 'localhost'; }
if (!$conf{'port'}) { $conf{'port'} = 25; }
if (!$from) {
quit("ERROR => You must specify a 'from' field! Try --help.", 1);
}
if ( ((scalar(@to)) + (scalar(@cc)) + (scalar(@bcc))) <= 0) {
quit("ERROR => You must specify at least one recipient via -t, -cc, or -bcc", 1);
}
## Make sure email addresses look OK.
foreach my $addr (@to, @cc, @bcc, $from, $opt{'reply-to'}) {
if ($addr) {
if (!returnAddressParts($addr)) {
printmsg("ERROR => Can't use improperly formatted email address: $addr", 0);
printmsg("HINT => Try viewing the extended help on addressing with \"--help addressing\"", 1);
quit("", 1);
}
}
}
## Make sure all attachments exist.
foreach my $file (@attachments) {
if ( (! -f $file) or (! -r $file) ) {
printmsg("ERROR => The attachment [$file] doesn't exist!", 0);
printmsg("HINT => Try specifying the full path to the file or reading extended help with \"--help message\"", 1);
quit("", 1);
}
}
if ($conf{'logging'} and (!$conf{'logFile'})) {
quit("ERROR => You used -l to enable logging but didn't specify a log file!", 1);
}
if ( $opt{'username'} ) {
if (!$opt{'password'}) {
## Prompt for a password since one wasn't specified with the -xp option.
$SIG{'ALRM'} = sub { quit("ERROR => Timeout waiting for password inpupt", 1); };
alarm(60) if ($^O !~ /win/i); ## alarm() doesn't work in win32
print "Password: ";
$opt{'password'} = <STDIN>; chomp $opt{'password'};
if (!$opt{'password'}) {
quit("ERROR => A username for SMTP authentication was specified, but no password!", 1);
}
}
}
## Validate the TLS setting
$opt{'tls'} = lc($opt{'tls'});
if ($opt{'tls'} !~ /^(auto|yes|no)$/) {
quit("ERROR => Invalid TLS setting ($opt{'tls'}). Must be one of auto, yes, or no.", 1);
}
## If TLS is set to "yes", make sure sendEmail loaded the libraries needed.
if ($opt{'tls'} eq 'yes' and $conf{'tls_client'} == 0) {
quit("ERROR => No TLS support! SendEmail can't load required libraries. (try installing Net::SSLeay and IO::Socket::SSL)", 1);
}
## Return 0 errors
return(0);
}
## getline($socketRef)
sub getline {
my ($socketRef) = @_;
local ($/) = "\r\n";
return $$socketRef->getline;
}
## Receive a (multiline?) SMTP response from ($socketRef)
sub getResponse {
my ($socketRef) = @_;
my ($tmp, $reply);
local ($/) = "\r\n";
return undef unless defined($tmp = getline($socketRef));
return("getResponse() socket is not open") unless ($$socketRef->opened);
## Keep reading lines if it's a multi-line response
while ($tmp =~ /^\d{3}-/o) {
$reply .= $tmp;
return undef unless defined($tmp = getline($socketRef));
}
$reply .= $tmp;
$reply =~ s/\r?\n$//o;
return $reply;
}
###############################################################################################
## Function: SMTPchat ( [string $command] )
##
## Description: Sends $command to the SMTP server (on SERVER) and awaits a successful
## reply form the server. If the server returns an error, or does not reply
## within $conf{'alarm'} seconds an error is generated.
## NOTE: $command is optional, if no command is specified then nothing will
## be sent to the server, but a valid response is still required from the server.
##
## Input: [$command] A (optional) valid SMTP command (ex. "HELO")
##
##
## Output: Returns zero on success, or non-zero on error.
## Error messages will be stored in $conf{'error'}
## A copy of the last SMTP response is stored in the global variable
## $conf{'SMTPchat_response'}
##
##
## Example: SMTPchat ("HELO mail.isp.net");
###############################################################################################
sub SMTPchat {
my ($command) = @_;
printmsg("INFO => Sending: \t$command", 1) if ($command);
## Send our command
print $SERVER "$command$CRLF" if ($command);
## Read a response from the server
$SIG{'ALRM'} = sub { $conf{'error'} = "alarm"; $SERVER->close(); };
alarm($conf{'alarm'}) if ($^O !~ /win/i); ## alarm() doesn't work in win32;
my $result = $conf{'SMTPchat_response'} = getResponse(\$SERVER);
alarm(0) if ($^O !~ /win/i); ## alarm() doesn't work in win32;
## Generate an alert if we timed out
if ($conf{'error'} eq "alarm") {
$conf{'error'} = "ERROR => Timeout while reading from $conf{'server'}:$conf{'port'} There was no response after $conf{'alarm'} seconds.";
return(1);
}
## Make sure the server actually responded
if (!$result) {
$conf{'error'} = "ERROR => $conf{'server'}:$conf{'port'} returned a zero byte response to our query.";
return(2);
}
## Validate the response
if (evalSMTPresponse($result)) {
## conf{'error'} will already be set here
return(2);
}
## Print the success messsage
printmsg($conf{'error'}, 1);
## Return Success
return(0);
}
###############################################################################################
## Function: evalSMTPresponse (string $message )
##
## Description: Searches $message for either an SMTP success or error code, and returns
## 0 on success, and the actual error code on error.
##
##
## Input: $message Data received from a SMTP server (ex. "220
##
##
## Output: Returns zero on success, or non-zero on error.
## Error messages will be stored in $conf{'error'}
##
##
## Example: SMTPchat ("HELO mail.isp.net");
###############################################################################################
sub evalSMTPresponse {
my ($message) = @_;
## Validate input
if (!$message) {
$conf{'error'} = "ERROR => No message was passed to evalSMTPresponse(). What happened?";
return(1)
}
printmsg("DEBUG => evalSMTPresponse() - Checking for SMTP success or error status in the message: $message ", 3);
## Look for a SMTP success code
if ($message =~ /^([23]\d\d)/) {
printmsg("DEBUG => evalSMTPresponse() - Found SMTP success code: $1", 2);
$conf{'error'} = "SUCCESS => Received: \t$message";
return(0);
}
## Look for a SMTP error code
if ($message =~ /^([45]\d\d)/) {
printmsg("DEBUG => evalSMTPresponse() - Found SMTP error code: $1", 2);
$conf{'error'} = "ERROR => Received: \t$message";
return($1);
}
## If no SMTP codes were found return an error of 1
$conf{'error'} = "ERROR => Received a message with no success or error code. The message received was: $message";
return(2);
}
#########################################################
# SUB: &return_month(0,1,etc)
# returns the name of the month that corrosponds
# with the number. returns 0 on error.
#########################################################
sub return_month {
my $x = $_[0];
if ($x == 0) { return 'Jan'; }
if ($x == 1) { return 'Feb'; }
if ($x == 2) { return 'Mar'; }
if ($x == 3) { return 'Apr'; }
if ($x == 4) { return 'May'; }
if ($x == 5) { return 'Jun'; }
if ($x == 6) { return 'Jul'; }
if ($x == 7) { return 'Aug'; }
if ($x == 8) { return 'Sep'; }
if ($x == 9) { return 'Oct'; }
if ($x == 10) { return 'Nov'; }
if ($x == 11) { return 'Dec'; }
return (0);
}
#########################################################
# SUB: &return_day(0,1,etc)
# returns the name of the day that corrosponds
# with the number. returns 0 on error.
#########################################################
sub return_day {
my $x = $_[0];
if ($x == 0) { return 'Sun'; }
if ($x == 1) { return 'Mon'; }
if ($x == 2) { return 'Tue'; }
if ($x == 3) { return 'Wed'; }
if ($x == 4) { return 'Thu'; }
if ($x == 5) { return 'Fri'; }
if ($x == 6) { return 'Sat'; }
return (0);
}
###############################################################################################
## Function: returnAddressParts(string $address)
##
## Description: Returns a two element array containing the "Name" and "Address" parts of
## an email address.
##
## Example: "Brandon Zehm <[email protected]>"
## would return: ("Brandon Zehm", "[email protected]");
##
## "[email protected]"
## would return: ("[email protected]", "[email protected]")
###############################################################################################
sub returnAddressParts {
my $input = $_[0];
my $name = "";
my $address = "";
## Make sure to fail if it looks totally invalid
if ($input !~ /(\S+\@\S+)/) {
$conf{'error'} = "ERROR => The address [$input] doesn't look like a valid email address, ignoring it";
return(undef());
}
## Check 1, should find addresses like: "Brandon Zehm <[email protected]>"
elsif ($input =~ /^\s*(\S(.*\S)?)\s*<(\S+\@\S+)>/o) {
($name, $address) = ($1, $3);
}
## Otherwise if that failed, just get the address: <[email protected]>
elsif ($input =~ /<(\S+\@\S+)>/o) {
$name = $address = $1;
}
## Or maybe it was formatted this way: [email protected]
elsif ($input =~ /(\S+\@\S+)/o) {
$name = $address = $1;
}
## Something stupid happened, just return an error.
unless ($name and $address) {
printmsg("ERROR => Couldn't parse the address: $input", 0);
printmsg("HINT => If you think this should work, consider reporting this as a bug to $conf{'authorEmail'}", 1);
return(undef());
}
## Make sure there aren't invalid characters in the address, and return it.
my $ctrl = '\000-\037';
my $nonASCII = '\x80-\xff';
if ($address =~ /[<> ,;:"'\[\]\\$ctrl$nonASCII]/) {
printmsg("WARNING => The address [$address] seems to contain invalid characters: continuing anyway", 0);
}
return($name, $address);
}
###############################################################################################
## Function: base64_encode(string $data)
##
## Description: Returns $data as a base64 encoded string
## If the encoded data is returned in 76 character long lines with the final
## CR\LF removed.
###############################################################################################
sub base64_encode {
my $data = $_[0];
my $tmp = '';
my $base64 = '';
my $CRLF = "\r\n";
###################################
## Convert binary data to base64 ##
###################################
while ($data =~ s/(.{45})//s) { ## Get 45 bytes from the binary string
$tmp = substr(pack('u', $&), 1); ## Convert the binary to uuencoded text
chop($tmp);
$tmp =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
$base64 .= $tmp;
}
###################################
## Encode and send the leftovers ##
###################################
my $padding = "";
if ( ($data) and (length($data) >= 1) ) {
$padding = (3 - length($data) % 3) % 3; ## Set flag if binary data isn't divisible by 3
$tmp = substr(pack('u', $data), 1); ## Convert the binary to uuencoded text
chop($tmp);
$tmp =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
$base64 .= $tmp;
}
############################
## Fix padding at the end ##
############################
$data = '';
$base64 =~ s/.{$padding}$/'=' x $padding/e if $padding; ## Fix the end padding if flag (from above) is set
while ($base64 =~ s/(.{1,76})//s) { ## Put $CRLF after each 76 characters
$data .= "$1$CRLF";
}
chomp $data;
return($data);
}
#########################################################
# SUB: send_attachment("/path/filename")
# Sends the mime headers and base64 encoded file
# to the email server.
#########################################################
sub send_attachment {
my ($filename) = @_; ## Get filename passed
my (@fields, $y, $filename_name, $encoding, ## Local variables
@attachlines, $content_type);
my $bin = 1;
@fields = split(/\/|\\/, $filename); ## Get the actual filename without the path
$filename_name = pop(@fields);
push @attachments_names, $filename_name; ## FIXME: This is only used later for putting in the log file
##########################
## Autodetect Mime Type ##
##########################
@fields = split(/\./, $filename_name);
$encoding = $fields[$#fields];
if ($encoding =~ /txt|text|log|conf|^c$|cpp|^h$|inc|m3u/i) { $content_type = 'text/plain'; }
elsif ($encoding =~ /html|htm|shtml|shtm|asp|php|cfm/i) { $content_type = 'text/html'; }
elsif ($encoding =~ /sh$/i) { $content_type = 'application/x-sh'; }
elsif ($encoding =~ /tcl/i) { $content_type = 'application/x-tcl'; }
elsif ($encoding =~ /pl$/i) { $content_type = 'application/x-perl'; }
elsif ($encoding =~ /js$/i) { $content_type = 'application/x-javascript'; }
elsif ($encoding =~ /man/i) { $content_type = 'application/x-troff-man'; }
elsif ($encoding =~ /gif/i) { $content_type = 'image/gif'; }
elsif ($encoding =~ /jpg|jpeg|jpe|jfif|pjpeg|pjp/i) { $content_type = 'image/jpeg'; }
elsif ($encoding =~ /tif|tiff/i) { $content_type = 'image/tiff'; }
elsif ($encoding =~ /xpm/i) { $content_type = 'image/x-xpixmap'; }
elsif ($encoding =~ /bmp/i) { $content_type = 'image/x-MS-bmp'; }
elsif ($encoding =~ /pcd/i) { $content_type = 'image/x-photo-cd'; }
elsif ($encoding =~ /png/i) { $content_type = 'image/png'; }
elsif ($encoding =~ /aif|aiff/i) { $content_type = 'audio/x-aiff'; }
elsif ($encoding =~ /wav/i) { $content_type = 'audio/x-wav'; }
elsif ($encoding =~ /mp2|mp3|mpa/i) { $content_type = 'audio/x-mpeg'; }
elsif ($encoding =~ /ra$|ram/i) { $content_type = 'audio/x-pn-realaudio'; }
elsif ($encoding =~ /mpeg|mpg/i) { $content_type = 'video/mpeg'; }
elsif ($encoding =~ /mov|qt$/i) { $content_type = 'video/quicktime'; }
elsif ($encoding =~ /avi/i) { $content_type = 'video/x-msvideo'; }
elsif ($encoding =~ /zip/i) { $content_type = 'application/x-zip-compressed'; }
elsif ($encoding =~ /tar/i) { $content_type = 'application/x-tar'; }
elsif ($encoding =~ /jar/i) { $content_type = 'application/java-archive'; }
elsif ($encoding =~ /exe|bin/i) { $content_type = 'application/octet-stream'; }
elsif ($encoding =~ /ppt|pot|ppa|pps|pwz/i) { $content_type = 'application/vnd.ms-powerpoint'; }
elsif ($encoding =~ /mdb|mda|mde/i) { $content_type = 'application/vnd.ms-access'; }
elsif ($encoding =~ /xls|xlt|xlm|xld|xla|xlc|xlw|xll/i) { $content_type = 'application/vnd.ms-excel'; }
elsif ($encoding =~ /doc|dot/i) { $content_type = 'application/msword'; }
elsif ($encoding =~ /rtf/i) { $content_type = 'application/rtf'; }
elsif ($encoding =~ /pdf/i) { $content_type = 'application/pdf'; }
elsif ($encoding =~ /tex/i) { $content_type = 'application/x-tex'; }
elsif ($encoding =~ /latex/i) { $content_type = 'application/x-latex'; }
elsif ($encoding =~ /vcf/i) { $content_type = 'application/x-vcard'; }
else { $content_type = 'application/octet-stream'; }
############################
## Process the attachment ##
############################
#####################################
## Generate and print MIME headers ##
#####################################
$y = "$CRLF--$conf{'delimiter'}$CRLF";
$y .= "Content-Type: $content_type;$CRLF";
$y .= " name=\"$filename_name\"$CRLF";
$y .= "Content-Transfer-Encoding: base64$CRLF";
$y .= "Content-Disposition: attachment; filename=\"$filename_name\"$CRLF";
$y .= "$CRLF";
print $SERVER $y;
###########################################################
## Convert the file to base64 and print it to the server ##
###########################################################
open (FILETOATTACH, $filename) || do {
printmsg("ERROR => Opening the file [$filename] for attachment failed with the error: $!", 0);
return(1);
};
binmode(FILETOATTACH); ## Hack to make Win32 work
my $res = "";
my $tmp = "";
my $base64 = "";
while (<FILETOATTACH>) { ## Read a line from the (binary) file
$res .= $_;
###################################
## Convert binary data to base64 ##
###################################
while ($res =~ s/(.{45})//s) { ## Get 45 bytes from the binary string
$tmp = substr(pack('u', $&), 1); ## Convert the binary to uuencoded text
chop($tmp);
$tmp =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
$base64 .= $tmp;
}
################################
## Print chunks to the server ##
################################
while ($base64 =~ s/(.{76})//s) {
print $SERVER "$1$CRLF";
}
}
###################################
## Encode and send the leftovers ##
###################################
my $padding = "";
if ( ($res) and (length($res) >= 1) ) {
$padding = (3 - length($res) % 3) % 3; ## Set flag if binary data isn't divisible by 3
$res = substr(pack('u', $res), 1); ## Convert the binary to uuencoded text
chop($res);
$res =~ tr|` -_|AA-Za-z0-9+/|; ## Translate from uuencode to base64
}
############################
## Fix padding at the end ##
############################
$res = $base64 . $res; ## Get left overs from above
$res =~ s/.{$padding}$/'=' x $padding/e if $padding; ## Fix the end padding if flag (from above) is set
if ($res) {
while ($res =~ s/(.{1,76})//s) { ## Send it to the email server.
print $SERVER "$1$CRLF";
}
}
close (FILETOATTACH) || do {
printmsg("ERROR - Closing the filehandle for file [$filename] failed with the error: $!", 0);
return(2);
};
## Return 0 errors
return(0);
}
###############################################################################################
## Function: $string = get_hostname (boot $fqdn)
##
## Description: Tries really hard to returns the short (or FQDN) hostname of the current