Subversion Repositories camp_sysinfo_client_3

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 rodolico 1
#!/usr/bin/perl -w
2
##############################################################################
3
## sendEmail
4
## Written by: Brandon Zehm <caspian@dotconf.net>
5
## 
6
## License:
7
##  sendEmail (hereafter referred to as "program") is free software;
8
##  you can redistribute it and/or modify it under the terms of the GNU General
9
##  Public License as published by the Free Software Foundation; either version
10
##  2 of the License, or (at your option) any later version.
11
##  When redistributing modified versions of this source code it is recommended
12
##  that that this disclaimer and the above coder's names are included in the
13
##  modified code.
14
##  
15
## Disclaimer:
16
##  This program is provided with no warranty of any kind, either expressed or
17
##  implied.  It is the responsibility of the user (you) to fully research and
18
##  comprehend the usage of this program.  As with any tool, it can be misused,
19
##  either intentionally (you're a vandal) or unintentionally (you're a moron).
20
##  THE AUTHOR(S) IS(ARE) NOT RESPONSIBLE FOR ANYTHING YOU DO WITH THIS PROGRAM
21
##  or anything that happens because of your use (or misuse) of this program,
22
##  including but not limited to anything you, your lawyers, or anyone else
23
##  can dream up.  And now, a relevant quote directly from the GPL:
24
##  
25
## NO WARRANTY
26
##  
27
##  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
28
##  FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
29
##  OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
30
##  PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
31
##  OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
32
##  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
33
##  TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
34
##  PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
35
##  REPAIR OR CORRECTION.
36
##    
37
##############################################################################
38
use strict;
39
use IO::Socket;
40
 
41
 
42
########################
43
##  Global Variables  ##
44
########################
45
 
46
my %conf = (
47
    ## General
48
    "programName"          => $0,                                  ## The name of this program
49
    "version"              => '1.55',                              ## The version of this program
50
    "authorName"           => 'Brandon Zehm',                      ## Author's Name
51
    "authorEmail"          => 'caspian@dotconf.net',               ## Author's Email Address
52
    "timezone"             => '+0000',                             ## We always use +0000 for the time zone
53
    "hostname"             => 'changeme',                          ## Used in printmsg() for all output (is updated later in the script).
54
    "debug"                => 0,                                   ## Default debug level
55
    "error"                => '',                                  ## Error messages will often be stored here
56
 
57
    ## Logging
58
    "stdout"               => 1,
59
    "logging"              => 0,                                   ## If this is true the printmsg function prints to the log file
60
    "logFile"              => '',                                  ## If this is specified (form the command line via -l) this file will be used for logging.
61
 
62
    ## Network
63
    "server"               => 'localhost',                         ## Default SMTP server
64
    "port"                 => 25,                                  ## Default port
65
    "bindaddr"             => '',                                  ## Default local bind address
66
    "alarm"                => '',                                  ## Default timeout for connects and reads, this gets set from $opt{'timeout'}
67
    "tls_client"           => 0,                                   ## If TLS is supported by the client (us)
68
    "tls_server"           => 0,                                   ## If TLS is supported by the remote SMTP server
69
 
70
    ## Email
71
    "delimiter"            => "----MIME delimiter for sendEmail-"  ## MIME Delimiter
72
                              . rand(1000000),                     ## Add some randomness to the delimiter
73
    "Message-ID"           => rand(1000000) . "-sendEmail",        ## Message-ID for email header
74
 
75
);
76
 
77
 
78
## This hash stores the options passed on the command line via the -o option.
79
my %opt = (
80
    ## Addressing
81
    "reply-to"             => '',                                  ## Reply-To field
82
 
83
    ## Message
84
    "message-file"         => '',                                  ## File to read message body from
85
    "message-header"       => '',                                  ## Additional email header line(s)
86
    "message-format"       => 'normal',                            ## If "raw" is specified the message is sent unmodified
87
    "message-charset"      => 'iso-8859-1',                        ## Message character-set
88
 
89
    ## Network
90
    "timeout"              => 60,                                  ## Default timeout for connects and reads, this is copied to $conf{'alarm'} later.
91
    "fqdn"                 => 'changeme',                          ## FQDN of this machine, used during SMTP communication (is updated later in the script).
92
 
93
    ## eSMTP
94
    "username"             => '',                                  ## Username used in SMTP Auth
95
    "password"             => '',                                  ## Password used in SMTP Auth
96
    "tls"                  => 'auto',                              ## Enable or disable TLS support.  Options: auto, yes, no
97
 
98
);
99
 
100
## More variables used later in the program
101
my $SERVER;
102
my $CRLF        = "\015\012";
103
my $subject     = '';
104
my $header      = '';
105
my $message     = '';
106
my $from        = '';
107
my @to          = ();
108
my @cc          = ();
109
my @bcc         = ();
110
my @attachments = ();
111
my @attachments_names = ();
112
 
113
## For printing colors to the console
114
my ${colorRed}    = "\033[31;1m";
115
my ${colorGreen}  = "\033[32;1m";
116
my ${colorCyan}   = "\033[36;1m";
117
my ${colorWhite}  = "\033[37;1m";
118
my ${colorNormal} = "\033[m";
119
my ${colorBold}   = "\033[1m";
120
my ${colorNoBold} = "\033[0m";
121
 
122
## Don't use shell escape codes on Windows systems
123
if ($^O =~ /win/i) {
124
    ${colorRed}   = ""; ${colorGreen}  = ""; ${colorCyan} = ""; 
125
    ${colorWhite} = ""; ${colorNormal} = ""; ${colorBold} = ""; ${colorNoBold} = "";
126
}
127
 
128
## Load IO::Socket::SSL if it's available
129
eval    { require IO::Socket::SSL; };
130
if ($@) { $conf{'tls_client'} = 0; }
131
else    { $conf{'tls_client'} = 1; }
132
$conf{'tls_client'} = 0;
133
 
134
 
135
 
136
 
137
 
138
#############################
139
##                          ##
140
##      FUNCTIONS            ##
141
##                          ##
142
#############################
143
 
144
 
145
 
146
 
147
 
148
###############################################################################################
149
##  Function: initialize ()
150
##  
151
##  Does all the script startup jibberish.
152
##  
153
###############################################################################################
154
sub initialize {
155
 
156
    ## Set STDOUT to flush immediatly after each print  
157
    $| = 1;
158
 
159
    ## Intercept signals
160
    $SIG{'QUIT'}  = sub { quit("EXITING: Received SIG$_[0]", 1); };
161
    $SIG{'INT'}   = sub { quit("EXITING: Received SIG$_[0]", 1); };
162
    $SIG{'KILL'}  = sub { quit("EXITING: Received SIG$_[0]", 1); };
163
    $SIG{'TERM'}  = sub { quit("EXITING: Received SIG$_[0]", 1); };
164
 
165
    ## ALARM and HUP signals are not supported in Win32
166
    unless ($^O =~ /win/i) {
167
        $SIG{'HUP'}   = sub { quit("EXITING: Received SIG$_[0]", 1); };
168
        $SIG{'ALRM'}  = sub { quit("EXITING: Received SIG$_[0]", 1); };
169
    }
170
 
171
    ## Fixup $conf{'programName'}
172
    $conf{'programName'} =~ s/(.)*[\/,\\]//;
173
    $0 = $conf{'programName'} . " " . join(" ", @ARGV);
174
 
175
    ## Fixup $conf{'hostname'} and $opt{'fqdn'}
176
    if ($opt{'fqdn'} eq 'changeme') { $opt{'fqdn'} = get_hostname(1); }
177
    if ($conf{'hostname'} eq 'changeme') { $conf{'hostname'} = $opt{'fqdn'}; $conf{'hostname'} =~ s/\..*//; }
178
 
179
    return(1);
180
}
181
 
182
 
183
 
184
 
185
 
186
 
187
 
188
 
189
 
190
 
191
 
192
 
193
 
194
 
195
 
196
###############################################################################################
197
##  Function: processCommandLine ()
198
##  
199
##  Processes command line storing important data in global vars (usually %conf)
200
##  
201
###############################################################################################
202
sub processCommandLine {
203
 
204
 
205
    ############################
206
    ##  Process command line  ##
207
    ############################
208
 
209
    my @ARGS = @ARGV;  ## This is so later we can re-parse the command line args later if we need to
210
    my $numargv = @ARGS;
211
    help() unless ($numargv);
212
    my $counter = 0;
213
 
214
    for ($counter = 0; $counter < $numargv; $counter++) {
215
 
216
        if ($ARGS[$counter] =~ /^-h$/i) {                    ## Help ##
217
            help();
218
        }
219
 
220
        elsif ($ARGS[$counter] eq "") {                      ## Ignore null arguments
221
            ## Do nothing
222
        }
223
 
224
        elsif ($ARGS[$counter] =~ /^--help/) {               ## Topical Help ##
225
            $counter++;
226
            if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
227
                helpTopic($ARGS[$counter]);
228
            }
229
            else {
230
                help();
231
            }
232
        }
233
 
234
        elsif ($ARGS[$counter] =~ /^-o$/i) {                 ## Options specified with -o ##
235
            $counter++;
236
            ## Loop through each option passed after the -o
237
            while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
238
 
239
                if ($ARGS[$counter] !~ /(\S+)=(\S.*)/) {
240
                    printmsg("WARNING => Name/Value pair [$ARGS[$counter]] is not properly formatted", 0);
241
                    printmsg("WARNING => Arguments proceeding -o should be in the form of \"name=value\"", 0);
242
                }
243
                else {
244
                    if (exists($opt{$1})) {
245
                        if ($1 eq 'message-header') {
246
                            $opt{$1} .= $2 . $CRLF;
247
                        }
248
                        else {
249
                            $opt{$1} = $2;
250
                        }
251
                        printmsg("DEBUG => Assigned \$opt{} key/value: $1 => $2", 3);
252
                    }
253
                    else {
254
                        printmsg("WARNING => Name/Value pair [$ARGS[$counter]] will be ignored: unknown key [$1]", 0);
255
                        printmsg("HINT => Try the --help option to find valid command line arguments", 1);
256
                    }
257
                }
258
                $counter++;
259
            }   $counter--;
260
        }
261
 
262
        elsif ($ARGS[$counter] =~ /^-f$/) {                  ## From ##
263
            $counter++;
264
            if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { $from = $ARGS[$counter]; }
265
            else { printmsg("WARNING => The argument after -f was not an email address!", 0); $counter--; }
266
        }
267
 
268
        elsif ($ARGS[$counter] =~ /^-t$/) {                  ## To ##
269
            $counter++;
270
            while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
271
                if ($ARGS[$counter] =~ /[;,]/) {
272
                    push (@to, split(/[;,]/, $ARGS[$counter]));
273
                }
274
                else {
275
                    push (@to,$ARGS[$counter]);
276
                }
277
                $counter++;
278
            }   $counter--;
279
        }
280
 
281
        elsif ($ARGS[$counter] =~ /^-cc$/) {                 ## Cc ##
282
            $counter++;
283
            while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
284
                if ($ARGS[$counter] =~ /[;,]/) {
285
                    push (@cc, split(/[;,]/, $ARGS[$counter]));
286
                }
287
                else {
288
                    push (@cc,$ARGS[$counter]);
289
                }
290
                $counter++;
291
            }   $counter--;
292
        }
293
 
294
        elsif ($ARGS[$counter] =~ /^-bcc$/) {                ## Bcc ##
295
            $counter++;
296
            while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
297
                if ($ARGS[$counter] =~ /[;,]/) {
298
                    push (@bcc, split(/[;,]/, $ARGS[$counter]));
299
                }
300
                else {
301
                    push (@bcc,$ARGS[$counter]);
302
                }
303
                $counter++;
304
            }   $counter--;
305
        }
306
 
307
        elsif ($ARGS[$counter] =~ /^-m$/) {                  ## Message ##
308
            $counter++;
309
            $message = "";
310
            while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
311
                if ($message) { $message .= " "; }
312
                $message .= $ARGS[$counter];
313
                $counter++;
314
            }   $counter--;
315
 
316
            ## Replace '\n' with $CRLF.
317
            ## This allows newlines with messages sent on the command line
318
            $message =~ s/\\n/$CRLF/g;
319
        }
320
 
321
        elsif ($ARGS[$counter] =~ /^-u$/) {                  ## Subject ##
322
            $counter++;
323
            $subject = "";
324
            while ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
325
                if ($subject) { $subject .= " "; }
326
                $subject .= $ARGS[$counter];
327
                $counter++;
328
            }   $counter--;
329
        }
330
 
331
        elsif ($ARGS[$counter] =~ /^-s$/) {                  ## Server ##
332
            $counter++;
333
            if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
334
                $conf{'server'} = $ARGS[$counter];
335
                if ($conf{'server'} =~ /:/) {                ## Port ##
336
                    ($conf{'server'},$conf{'port'}) = split(":",$conf{'server'});
337
                }
338
            }
339
            else { printmsg("WARNING - The argument after -s was not the server!", 0); $counter--; }
340
        }
341
 
342
        elsif ($ARGS[$counter] =~ /^-b$/) {                  ## Bind Address ##
343
            $counter++;
344
            if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
345
                $conf{'bindaddr'} = $ARGS[$counter];
346
            }
347
            else { printmsg("WARNING - The argument after -b was not the bindaddr!", 0); $counter--; }
348
        }
349
 
350
        elsif ($ARGS[$counter] =~ /^-a$/) {                  ## Attachments ##
351
            $counter++;
352
            while ($ARGS[$counter] && ($ARGS[$counter] !~ /^-/)) {
353
                push (@attachments,$ARGS[$counter]);
354
                $counter++;
355
            }   $counter--;
356
        }
357
 
358
        elsif ($ARGS[$counter] =~ /^-xu$/) {                  ## AuthSMTP Username ##
359
            $counter++;
360
            if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
361
               $opt{'username'} = $ARGS[$counter];
362
            }
363
            else {
364
                printmsg("WARNING => The argument after -xu was not valid username!", 0);
365
                $counter--;
366
            }
367
        }
368
 
369
        elsif ($ARGS[$counter] =~ /^-xp$/) {                  ## AuthSMTP Password ##
370
            $counter++;
371
            if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) {
372
               $opt{'password'} = $ARGS[$counter];
373
            }
374
            else {
375
                printmsg("WARNING => The argument after -xp was not valid password!", 0);
376
                $counter--;
377
            }
378
        }
379
 
380
        elsif ($ARGS[$counter] =~ /^-l$/) {                  ## Logging ##
381
            $counter++;
382
            $conf{'logging'} = 1;
383
            if ($ARGS[$counter] && $ARGS[$counter] !~ /^-/) { $conf{'logFile'} = $ARGS[$counter]; }
384
            else { printmsg("WARNING - The argument after -l was not the log file!", 0); $counter--; }
385
        }
386
 
387
        elsif ($ARGS[$counter] =~ s/^-v+//i) {               ## Verbosity ##
388
            my $tmp = (length($&) - 1);
389
            $conf{'debug'} += $tmp;
390
        }
391
 
392
        elsif ($ARGS[$counter] =~ /^-q$/) {                  ## Quiet ##
393
            $conf{'stdout'} = 0;
394
        }
395
 
396
        else {
397
            printmsg("Error: \"$ARGS[$counter]\" is not a recognized option!", 0);
398
            help();
399
        }
400
 
401
    }
402
 
403
 
404
 
405
 
406
 
407
 
408
 
409
 
410
    ###################################################
411
    ##  Verify required variables are set correctly  ##
412
    ###################################################
413
 
414
    ## Make sure we have something in $conf{hostname} and $opt{fqdn}
415
    if ($opt{'fqdn'} =~ /\./) {
416
        $conf{'hostname'} = $opt{'fqdn'};
417
        $conf{'hostname'} =~ s/\..*//;
418
    }
419
 
420
    if (!$conf{'server'}) { $conf{'server'} = 'localhost'; }
421
    if (!$conf{'port'})   { $conf{'port'} = 25; }
422
    if (!$from) {
423
        quit("ERROR => You must specify a 'from' field!  Try --help.", 1);
424
    }
425
    if ( ((scalar(@to)) + (scalar(@cc)) + (scalar(@bcc))) <= 0) {
426
        quit("ERROR => You must specify at least one recipient via -t, -cc, or -bcc", 1);
427
    }
428
 
429
    ## Make sure email addresses look OK.
430
    foreach my $addr (@to, @cc, @bcc, $from, $opt{'reply-to'}) {
431
        if ($addr) {
432
            if (!returnAddressParts($addr)) {
433
                printmsg("ERROR => Can't use improperly formatted email address: $addr", 0);
434
                printmsg("HINT => Try viewing the extended help on addressing with \"--help addressing\"", 1);
435
                quit("", 1);
436
            }
437
        }
438
    }
439
 
440
    ## Make sure all attachments exist.
441
    foreach my $file (@attachments) {
442
        if ( (! -f $file) or (! -r $file) ) {
443
            printmsg("ERROR => The attachment [$file] doesn't exist!", 0);
444
            printmsg("HINT => Try specifying the full path to the file or reading extended help with \"--help message\"", 1);
445
            quit("", 1);
446
        }
447
    }
448
 
449
    if ($conf{'logging'} and (!$conf{'logFile'})) {
450
        quit("ERROR => You used -l to enable logging but didn't specify a log file!", 1);
451
    }    
452
 
453
    if ( $opt{'username'} ) {
454
        if (!$opt{'password'}) {
455
            ## Prompt for a password since one wasn't specified with the -xp option.
456
            $SIG{'ALRM'} = sub { quit("ERROR => Timeout waiting for password inpupt", 1); };
457
            alarm(60) if ($^O !~ /win/i);  ## alarm() doesn't work in win32
458
            print "Password: ";
459
            $opt{'password'} = <STDIN>; chomp $opt{'password'};
460
            if (!$opt{'password'}) {
461
                quit("ERROR => A username for SMTP authentication was specified, but no password!", 1);
462
            }
463
        }
464
    }
465
 
466
    ## Validate the TLS setting
467
    $opt{'tls'} = lc($opt{'tls'});
468
    if ($opt{'tls'} !~ /^(auto|yes|no)$/) {
469
        quit("ERROR => Invalid TLS setting ($opt{'tls'}). Must be one of auto, yes, or no.", 1);
470
    }
471
 
472
    ## If TLS is set to "yes", make sure sendEmail loaded the libraries needed.
473
    if ($opt{'tls'} eq 'yes' and $conf{'tls_client'} == 0) {
474
        quit("ERROR => No TLS support!  SendEmail can't load required libraries. (try installing Net::SSLeay and IO::Socket::SSL)", 1);
475
    }
476
 
477
    ## Return 0 errors
478
    return(0);
479
}
480
 
481
 
482
 
483
 
484
 
485
 
486
 
487
 
488
 
489
 
490
 
491
 
492
 
493
 
494
 
495
 
496
## getline($socketRef)
497
sub getline {
498
    my ($socketRef) = @_;
499
    local ($/) = "\r\n";
500
    return $$socketRef->getline;
501
}
502
 
503
 
504
 
505
 
506
## Receive a (multiline?) SMTP response from ($socketRef)
507
sub getResponse {
508
    my ($socketRef) = @_;
509
    my ($tmp, $reply);
510
    local ($/) = "\r\n";
511
    return undef unless defined($tmp = getline($socketRef));
512
    return("getResponse() socket is not open") unless ($$socketRef->opened);
513
    ## Keep reading lines if it's a multi-line response
514
    while ($tmp =~ /^\d{3}-/o) {
515
        $reply .= $tmp;
516
        return undef unless defined($tmp = getline($socketRef));
517
    }
518
    $reply .= $tmp;
519
    $reply =~ s/\r?\n$//o;
520
    return $reply;
521
}
522
 
523
 
524
 
525
 
526
###############################################################################################
527
##  Function:    SMTPchat ( [string $command] )
528
##
529
##  Description: Sends $command to the SMTP server (on SERVER) and awaits a successful
530
##               reply form the server.  If the server returns an error, or does not reply
531
##               within $conf{'alarm'} seconds an error is generated.
532
##               NOTE: $command is optional, if no command is specified then nothing will
533
##               be sent to the server, but a valid response is still required from the server.
534
##
535
##  Input:       [$command]          A (optional) valid SMTP command (ex. "HELO")
536
##  
537
##  
538
##  Output:      Returns zero on success, or non-zero on error.  
539
##               Error messages will be stored in $conf{'error'}
540
##               A copy of the last SMTP response is stored in the global variable
541
##               $conf{'SMTPchat_response'}
542
##               
543
##  
544
##  Example:     SMTPchat ("HELO mail.isp.net");
545
###############################################################################################
546
sub SMTPchat {
547
    my ($command) = @_;
548
 
549
    printmsg("INFO => Sending: \t$command", 1) if ($command);
550
 
551
    ## Send our command
552
    print $SERVER "$command$CRLF" if ($command);
553
 
554
    ## Read a response from the server
555
    $SIG{'ALRM'} = sub { $conf{'error'} = "alarm"; $SERVER->close(); };
556
    alarm($conf{'alarm'}) if ($^O !~ /win/i);  ## alarm() doesn't work in win32;
557
    my $result = $conf{'SMTPchat_response'} = getResponse(\$SERVER); 
558
    alarm(0) if ($^O !~ /win/i);  ## alarm() doesn't work in win32;
559
 
560
    ## Generate an alert if we timed out
561
    if ($conf{'error'} eq "alarm") {
562
        $conf{'error'} = "ERROR => Timeout while reading from $conf{'server'}:$conf{'port'} There was no response after $conf{'alarm'} seconds.";
563
        return(1);
564
    }
565
 
566
    ## Make sure the server actually responded
567
    if (!$result) {
568
        $conf{'error'} = "ERROR => $conf{'server'}:$conf{'port'} returned a zero byte response to our query.";
569
        return(2);
570
    }
571
 
572
    ## Validate the response
573
    if (evalSMTPresponse($result)) {
574
        ## conf{'error'} will already be set here
575
        return(2);
576
    }
577
 
578
    ## Print the success messsage
579
    printmsg($conf{'error'}, 1);
580
 
581
    ## Return Success
582
    return(0);
583
}
584
 
585
 
586
 
587
 
588
 
589
 
590
 
591
 
592
 
593
 
594
 
595
 
596
###############################################################################################
597
##  Function:    evalSMTPresponse (string $message )
598
##
599
##  Description: Searches $message for either an  SMTP success or error code, and returns
600
##               0 on success, and the actual error code on error.
601
##               
602
##
603
##  Input:       $message          Data received from a SMTP server (ex. "220 
604
##                                
605
##  
606
##  Output:      Returns zero on success, or non-zero on error.  
607
##               Error messages will be stored in $conf{'error'}
608
##               
609
##  
610
##  Example:     SMTPchat ("HELO mail.isp.net");
611
###############################################################################################
612
sub evalSMTPresponse {
613
    my ($message) = @_;
614
 
615
    ## Validate input
616
    if (!$message) { 
617
        $conf{'error'} = "ERROR => No message was passed to evalSMTPresponse().  What happened?";
618
        return(1)
619
    }
620
 
621
    printmsg("DEBUG => evalSMTPresponse() - Checking for SMTP success or error status in the message: $message ", 3);
622
 
623
    ## Look for a SMTP success code
624
    if ($message =~ /^([23]\d\d)/) {
625
        printmsg("DEBUG => evalSMTPresponse() - Found SMTP success code: $1", 2);
626
        $conf{'error'} = "SUCCESS => Received: \t$message";
627
        return(0);
628
    }
629
 
630
    ## Look for a SMTP error code
631
    if ($message =~ /^([45]\d\d)/) {
632
        printmsg("DEBUG => evalSMTPresponse() - Found SMTP error code: $1", 2);
633
        $conf{'error'} = "ERROR => Received: \t$message";
634
        return($1);
635
    }
636
 
637
    ## If no SMTP codes were found return an error of 1
638
    $conf{'error'} = "ERROR => Received a message with no success or error code. The message received was: $message";
639
    return(2);
640
 
641
}
642
 
643
 
644
 
645
 
646
 
647
 
648
 
649
 
650
 
651
 
652
#########################################################
653
# SUB: &return_month(0,1,etc)
654
#  returns the name of the month that corrosponds
655
#  with the number.  returns 0 on error.
656
#########################################################
657
sub return_month {
658
    my $x = $_[0];
659
    if ($x == 0)  { return 'Jan'; }
660
    if ($x == 1)  { return 'Feb'; }
661
    if ($x == 2)  { return 'Mar'; }
662
    if ($x == 3)  { return 'Apr'; }
663
    if ($x == 4)  { return 'May'; }
664
    if ($x == 5)  { return 'Jun'; }
665
    if ($x == 6)  { return 'Jul'; }
666
    if ($x == 7)  { return 'Aug'; }
667
    if ($x == 8)  { return 'Sep'; }
668
    if ($x == 9)  { return 'Oct'; }
669
    if ($x == 10) { return 'Nov'; }
670
    if ($x == 11) { return 'Dec'; }
671
    return (0);
672
}
673
 
674
 
675
 
676
 
677
 
678
 
679
 
680
 
681
 
682
 
683
 
684
 
685
 
686
 
687
 
688
 
689
#########################################################
690
# SUB: &return_day(0,1,etc)
691
#  returns the name of the day that corrosponds
692
#  with the number.  returns 0 on error.
693
#########################################################
694
sub return_day {
695
    my $x = $_[0];
696
    if ($x == 0)  { return 'Sun'; }
697
    if ($x == 1)  { return 'Mon'; }
698
    if ($x == 2)  { return 'Tue'; }
699
    if ($x == 3)  { return 'Wed'; }
700
    if ($x == 4)  { return 'Thu'; }
701
    if ($x == 5)  { return 'Fri'; }
702
    if ($x == 6)  { return 'Sat'; }
703
    return (0);
704
}
705
 
706
 
707
 
708
 
709
 
710
 
711
 
712
 
713
 
714
 
715
 
716
 
717
 
718
 
719
 
720
 
721
###############################################################################################
722
##  Function:    returnAddressParts(string $address)
723
##
724
##  Description: Returns a two element array containing the "Name" and "Address" parts of 
725
##               an email address.
726
##  
727
## Example:      "Brandon Zehm <caspian@dotconf.net>"
728
##               would return: ("Brandon Zehm", "caspian@dotconf.net");
729
## 
730
##               "caspian@dotconf.net"
731
##               would return: ("caspian@dotconf.net", "caspian@dotconf.net")
732
###############################################################################################
733
sub returnAddressParts {
734
    my $input = $_[0];
735
    my $name = "";
736
    my $address = "";
737
 
738
    ## Make sure to fail if it looks totally invalid
739
    if ($input !~ /(\S+\@\S+)/) {
740
        $conf{'error'} = "ERROR => The address [$input] doesn't look like a valid email address, ignoring it";
741
        return(undef());
742
    }
743
 
744
    ## Check 1, should find addresses like: "Brandon Zehm <caspian@dotconf.net>"
745
    elsif ($input =~ /^\s*(\S(.*\S)?)\s*<(\S+\@\S+)>/o) {
746
        ($name, $address) = ($1, $3);
747
    }
748
 
749
    ## Otherwise if that failed, just get the address: <caspian@dotconf.net>
750
    elsif ($input =~ /<(\S+\@\S+)>/o) {
751
        $name = $address = $1;
752
    }
753
 
754
    ## Or maybe it was formatted this way: caspian@dotconf.net
755
    elsif ($input =~ /(\S+\@\S+)/o) {
756
        $name = $address = $1;
757
    }
758
 
759
    ## Something stupid happened, just return an error.
760
    unless ($name and $address) {
761
        printmsg("ERROR => Couldn't parse the address: $input", 0);
762
        printmsg("HINT => If you think this should work, consider reporting this as a bug to $conf{'authorEmail'}", 1);
763
        return(undef());
764
    }
765
 
766
    ## Make sure there aren't invalid characters in the address, and return it.
767
    my $ctrl        = '\000-\037';
768
    my $nonASCII    = '\x80-\xff';
769
    if ($address =~ /[<> ,;:"'\[\]\\$ctrl$nonASCII]/) {
770
        printmsg("WARNING => The address [$address] seems to contain invalid characters: continuing anyway", 0);
771
    }
772
    return($name, $address);
773
}
774
 
775
 
776
 
777
 
778
 
779
 
780
 
781
 
782
 
783
 
784
 
785
 
786
 
787
 
788
 
789
 
790
###############################################################################################
791
##  Function:    base64_encode(string $data)
792
##
793
##  Description: Returns $data as a base64 encoded string
794
##               If the encoded data is returned in 76 character long lines with the final 
795
##               CR\LF removed.
796
###############################################################################################
797
sub base64_encode {
798
    my $data = $_[0];
799
    my $tmp = '';
800
    my $base64 = '';
801
    my $CRLF = "\r\n";
802
 
803
    ###################################
804
    ## Convert binary data to base64 ##
805
    ###################################
806
    while ($data =~ s/(.{45})//s) {        ## Get 45 bytes from the binary string
807
        $tmp = substr(pack('u', $&), 1);   ## Convert the binary to uuencoded text
808
        chop($tmp);
809
        $tmp =~ tr|` -_|AA-Za-z0-9+/|;     ## Translate from uuencode to base64
810
        $base64 .= $tmp;
811
    }
812
 
813
    ###################################
814
    ## Encode and send the leftovers ##
815
    ###################################
816
    my $padding = "";
817
    if ( ($data) and (length($data) >= 1) ) {
818
        $padding = (3 - length($data) % 3) % 3;    ## Set flag if binary data isn't divisible by 3
819
        $tmp = substr(pack('u', $data), 1);       ## Convert the binary to uuencoded text
820
        chop($tmp);
821
        $tmp =~ tr|` -_|AA-Za-z0-9+/|;            ## Translate from uuencode to base64
822
        $base64 .= $tmp;
823
    }
824
 
825
    ############################
826
    ## Fix padding at the end ##
827
    ############################
828
    $data = '';
829
    $base64 =~ s/.{$padding}$/'=' x $padding/e if $padding; ## Fix the end padding if flag (from above) is set
830
    while ($base64 =~ s/(.{1,76})//s) {                     ## Put $CRLF after each 76 characters
831
        $data .= "$1$CRLF";
832
    }
833
    chomp $data;
834
 
835
    return($data);
836
}
837
 
838
 
839
 
840
 
841
 
842
 
843
 
844
 
845
 
846
#########################################################
847
# SUB: send_attachment("/path/filename")
848
# Sends the mime headers and base64 encoded file
849
# to the email server.
850
#########################################################
851
sub send_attachment {
852
    my ($filename) = @_;                             ## Get filename passed
853
    my (@fields, $y, $filename_name, $encoding,      ## Local variables
854
        @attachlines, $content_type);
855
    my $bin = 1;
856
 
857
    @fields = split(/\/|\\/, $filename);             ## Get the actual filename without the path  
858
    $filename_name = pop(@fields);       
859
    push @attachments_names, $filename_name;         ## FIXME: This is only used later for putting in the log file
860
 
861
    ##########################
862
    ## Autodetect Mime Type ##
863
    ##########################
864
 
865
    @fields = split(/\./, $filename_name);
866
    $encoding = $fields[$#fields];
867
 
868
    if ($encoding =~ /txt|text|log|conf|^c$|cpp|^h$|inc|m3u/i) {   $content_type = 'text/plain';                      }
869
    elsif ($encoding =~ /html|htm|shtml|shtm|asp|php|cfm/i) {      $content_type = 'text/html';                       }
870
    elsif ($encoding =~ /sh$/i) {                                  $content_type = 'application/x-sh';                }
871
    elsif ($encoding =~ /tcl/i) {                                  $content_type = 'application/x-tcl';               }
872
    elsif ($encoding =~ /pl$/i) {                                  $content_type = 'application/x-perl';              }
873
    elsif ($encoding =~ /js$/i) {                                  $content_type = 'application/x-javascript';        }
874
    elsif ($encoding =~ /man/i) {                                  $content_type = 'application/x-troff-man';         }
875
    elsif ($encoding =~ /gif/i) {                                  $content_type = 'image/gif';                       }
876
    elsif ($encoding =~ /jpg|jpeg|jpe|jfif|pjpeg|pjp/i) {          $content_type = 'image/jpeg';                      }
877
    elsif ($encoding =~ /tif|tiff/i) {                             $content_type = 'image/tiff';                      }
878
    elsif ($encoding =~ /xpm/i) {                                  $content_type = 'image/x-xpixmap';                 }
879
    elsif ($encoding =~ /bmp/i) {                                  $content_type = 'image/x-MS-bmp';                  }
880
    elsif ($encoding =~ /pcd/i) {                                  $content_type = 'image/x-photo-cd';                }
881
    elsif ($encoding =~ /png/i) {                                  $content_type = 'image/png';                       }
882
    elsif ($encoding =~ /aif|aiff/i) {                             $content_type = 'audio/x-aiff';                    }
883
    elsif ($encoding =~ /wav/i) {                                  $content_type = 'audio/x-wav';                     }
884
    elsif ($encoding =~ /mp2|mp3|mpa/i) {                          $content_type = 'audio/x-mpeg';                    }
885
    elsif ($encoding =~ /ra$|ram/i) {                              $content_type = 'audio/x-pn-realaudio';            }
886
    elsif ($encoding =~ /mpeg|mpg/i) {                             $content_type = 'video/mpeg';                      }
887
    elsif ($encoding =~ /mov|qt$/i) {                              $content_type = 'video/quicktime';                 }
888
    elsif ($encoding =~ /avi/i) {                                  $content_type = 'video/x-msvideo';                 }
889
    elsif ($encoding =~ /zip/i) {                                  $content_type = 'application/x-zip-compressed';    }
890
    elsif ($encoding =~ /tar/i) {                                  $content_type = 'application/x-tar';               }
891
    elsif ($encoding =~ /jar/i) {                                  $content_type = 'application/java-archive';        }
892
    elsif ($encoding =~ /exe|bin/i) {                              $content_type = 'application/octet-stream';        }
893
    elsif ($encoding =~ /ppt|pot|ppa|pps|pwz/i) {                  $content_type = 'application/vnd.ms-powerpoint';   }
894
    elsif ($encoding =~ /mdb|mda|mde/i) {                          $content_type = 'application/vnd.ms-access';       }
895
    elsif ($encoding =~ /xls|xlt|xlm|xld|xla|xlc|xlw|xll/i) {      $content_type = 'application/vnd.ms-excel';        }
896
    elsif ($encoding =~ /doc|dot/i) {                              $content_type = 'application/msword';              }
897
    elsif ($encoding =~ /rtf/i) {                                  $content_type = 'application/rtf';                 }
898
    elsif ($encoding =~ /pdf/i) {                                  $content_type = 'application/pdf';                 }
899
    elsif ($encoding =~ /tex/i) {                                  $content_type = 'application/x-tex';               }
900
    elsif ($encoding =~ /latex/i) {                                $content_type = 'application/x-latex';             }
901
    elsif ($encoding =~ /vcf/i) {                                  $content_type = 'application/x-vcard';             }
902
    else { $content_type = 'application/octet-stream';  }
903
 
904
 
905
  ############################
906
  ## Process the attachment ##
907
  ############################
908
 
909
    #####################################
910
    ## Generate and print MIME headers ##
911
    #####################################
912
 
913
    $y  = "$CRLF--$conf{'delimiter'}$CRLF";
914
    $y .= "Content-Type: $content_type;$CRLF";
915
    $y .= "        name=\"$filename_name\"$CRLF";
916
    $y .= "Content-Transfer-Encoding: base64$CRLF";
917
    $y .= "Content-Disposition: attachment; filename=\"$filename_name\"$CRLF";
918
    $y .= "$CRLF";
919
    print $SERVER $y;
920
 
921
 
922
    ###########################################################
923
    ## Convert the file to base64 and print it to the server ##
924
    ###########################################################
925
 
926
    open (FILETOATTACH, $filename) || do { 
927
        printmsg("ERROR => Opening the file [$filename] for attachment failed with the error: $!", 0);
928
        return(1);
929
    };
930
    binmode(FILETOATTACH);                 ## Hack to make Win32 work
931
 
932
    my $res = "";
933
    my $tmp = "";
934
    my $base64 = "";
935
    while (<FILETOATTACH>) {               ## Read a line from the (binary) file
936
        $res .= $_;
937
 
938
        ###################################
939
        ## Convert binary data to base64 ##
940
        ###################################
941
        while ($res =~ s/(.{45})//s) {         ## Get 45 bytes from the binary string
942
            $tmp = substr(pack('u', $&), 1);   ## Convert the binary to uuencoded text
943
            chop($tmp);
944
            $tmp =~ tr|` -_|AA-Za-z0-9+/|;     ## Translate from uuencode to base64
945
            $base64 .= $tmp;
946
        }
947
 
948
        ################################
949
        ## Print chunks to the server ##
950
        ################################
951
        while ($base64 =~ s/(.{76})//s) {
952
            print $SERVER "$1$CRLF";
953
        }
954
 
955
    }
956
 
957
    ###################################
958
    ## Encode and send the leftovers ##
959
    ###################################
960
    my $padding = "";
961
    if ( ($res) and (length($res) >= 1) ) {
962
        $padding = (3 - length($res) % 3) % 3;  ## Set flag if binary data isn't divisible by 3
963
        $res = substr(pack('u', $res), 1);      ## Convert the binary to uuencoded text
964
        chop($res);
965
        $res =~ tr|` -_|AA-Za-z0-9+/|;          ## Translate from uuencode to base64
966
    }
967
 
968
    ############################
969
    ## Fix padding at the end ##
970
    ############################
971
    $res = $base64 . $res;                               ## Get left overs from above
972
    $res =~ s/.{$padding}$/'=' x $padding/e if $padding; ## Fix the end padding if flag (from above) is set
973
    if ($res) {
974
        while ($res =~ s/(.{1,76})//s) {                 ## Send it to the email server.
975
            print $SERVER "$1$CRLF";
976
        }
977
    }
978
 
979
    close (FILETOATTACH) || do {
980
        printmsg("ERROR - Closing the filehandle for file [$filename] failed with the error: $!", 0);
981
        return(2);
982
    };
983
 
984
    ## Return 0 errors
985
    return(0);
986
 
987
}
988
 
989
 
990
 
991
 
992
 
993
 
994
 
995
 
996
 
997
###############################################################################################
998
##  Function:    $string = get_hostname (boot $fqdn)
999
##  
1000
##  Description: Tries really hard to returns the short (or FQDN) hostname of the current
1001
##               system.  Uses techniques and code from the  Sys-Hostname module.
1002
##  
1003
##  Input:       $fqdn     A true value (1) will cause this function to return a FQDN hostname
1004
##                         rather than a short hostname.
1005
##  
1006
##  Output:      Returns a string
1007
###############################################################################################
1008
sub get_hostname {
1009
    ## Assign incoming parameters to variables
1010
    my ( $fqdn ) = @_;
1011
    my $hostname = "";
1012
 
1013
    ## STEP 1: Get short hostname
1014
 
1015
    ## Load Sys::Hostname if it's available
1016
    eval { require Sys::Hostname; };
1017
    unless ($@) {
1018
        $hostname = Sys::Hostname::hostname(); 
1019
    }
1020
 
1021
    ## If that didn't get us a hostname, try a few other things
1022
    else {
1023
        ## Windows systems
1024
        if ($^O !~ /win/i) {
1025
            if ($ENV{'COMPUTERNAME'}) { $hostname = $ENV{'COMPUTERNAME'}; }
1026
            if (!$hostname) { $hostname = gethostbyname('localhost'); }
1027
            if (!$hostname) { chomp($hostname = `hostname 2> NUL`) };
1028
        }
1029
 
1030
        ## Unix systems
1031
        else {
1032
            local $ENV{PATH} = '/usr/bin:/bin:/usr/sbin:/sbin';  ## Paranoia
1033
 
1034
            ## Try the environment first (Help!  What other variables could/should I be checking here?)
1035
            if ($ENV{'HOSTNAME'}) { $hostname = $ENV{'HOSTNAME'}; }
1036
 
1037
            ## Try the hostname command
1038
            eval { local $SIG{__DIE__}; local $SIG{CHLD}; $hostname = `hostname 2>/dev/null`; chomp($hostname); } ||
1039
 
1040
            ## Try POSIX::uname(), which strictly can't be expected to be correct
1041
            eval { local $SIG{__DIE__}; require POSIX; $hostname = (POSIX::uname())[1]; } ||
1042
 
1043
            ## Try the uname command
1044
            eval { local $SIG{__DIE__}; $hostname = `uname -n 2>/dev/null`; chomp($hostname); };
1045
 
1046
        }
1047
 
1048
        ## If we can't find anything else, return ""
1049
        if (!$hostname) {
1050
            print "WARNING => No hostname could be determined, please specify one with -o fqdn=FQDN option!\n";
1051
            return("unknown");
1052
        }
1053
    }
1054
 
1055
    ## Return the short hostname
1056
    unless ($fqdn) {
1057
        $hostname =~ s/\..*//;
1058
        return(lc($hostname));
1059
    }
1060
 
1061
    ## STEP 2: Determine the FQDN
1062
 
1063
    ## First, if we already have one return it.
1064
    if ($hostname =~ /\w\.\w/) { return(lc($hostname)); }
1065
 
1066
    ## Next try using 
1067
    eval { $fqdn = (gethostbyname($hostname))[0]; };
1068
    if ($fqdn) { return(lc($fqdn)); }
1069
    return(lc($hostname));
1070
}
1071
 
1072
 
1073
 
1074
 
1075
 
1076
 
1077
 
1078
 
1079
###############################################################################################
1080
##  Function:    printmsg (string $message, int $level)
1081
##
1082
##  Description: Handles all messages - printing them to the screen only if the messages
1083
##               $level is >= the global debug level.  If $conf{'logFile'} is defined it
1084
##               will also log the message to that file.
1085
##
1086
##  Input:       $message          A message to be printed, logged, etc.
1087
##               $level            The debug level of the message. If
1088
##                                 not defined 0 will be assumed.  0 is
1089
##                                 considered a normal message, 1 and 
1090
##                                 higher is considered a debug message.
1091
##  
1092
##  Output:      Prints to STDOUT
1093
##
1094
##  Assumptions: $conf{'hostname'} should be the name of the computer we're running on.
1095
##               $conf{'stdout'} should be set to 1 if you want to print to stdout
1096
##               $conf{'logFile'} should be a full path to a log file if you want that
1097
##               $conf{'syslog'} should be 1 if you want to syslog, the syslog() function
1098
##               written by Brandon Zehm should be present.
1099
##               $conf{'debug'} should be an integer between 0 and 10.
1100
##
1101
##  Example:     printmsg("WARNING: We believe in generic error messages... NOT!", 0);
1102
###############################################################################################
1103
sub printmsg {
1104
    ## Assign incoming parameters to variables
1105
    my ( $message, $level ) = @_;
1106
 
1107
    ## Make sure input is sane
1108
    $level = 0 if (!defined($level));
1109
    $message =~ s/\s+$//sgo;
1110
    $message =~ s/\r?\n/, /sgo;
1111
 
1112
    ## Continue only if the debug level of the program is >= message debug level.
1113
    if ($conf{'debug'} >= $level) {
1114
 
1115
        ## Get the date in the format: Dec  3 11:14:04
1116
        my ($sec, $min, $hour, $mday, $mon) = localtime();
1117
        $mon = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')[$mon];
1118
        my $date = sprintf("%s %02d %02d:%02d:%02d", $mon, $mday, $hour, $min, $sec);
1119
 
1120
        ## Print to STDOUT always if debugging is enabled, or if conf{stdout} is true.
1121
        if ( ($conf{'debug'} >= 1) or ($conf{'stdout'} == 1) ) {
1122
            print "$date $conf{'hostname'} $conf{'programName'}\[$$\]: $message\n";
1123
        }
1124
 
1125
        ## Print to the log file if $conf{'logging'} is true
1126
        if ($conf{'logFile'}) {
1127
            if (openLogFile($conf{'logFile'})) { $conf{'logFile'} = ""; printmsg("ERROR => Opening the file [$conf{'logFile'}] for appending returned the error: $!", 1); }
1128
            print LOGFILE "$date $conf{'hostname'} $conf{'programName'}\[$$\]: $message\n";
1129
        }
1130
 
1131
    }
1132
 
1133
    ## Return 0 errors
1134
    return(0);
1135
}
1136
 
1137
 
1138
 
1139
 
1140
 
1141
 
1142
 
1143
 
1144
 
1145
 
1146
 
1147
 
1148
###############################################################################################
1149
## FUNCTION:    
1150
##   openLogFile ( $filename )
1151
## 
1152
## 
1153
## DESCRIPTION: 
1154
##   Opens the file $filename and attaches it to the filehandle "LOGFILE".  Returns 0 on success
1155
##   and non-zero on failure.  Error codes are listed below, and the error message gets set in
1156
##   global variable $!.
1157
##   
1158
##   
1159
## Example: 
1160
##   openFile ("/var/log/sendEmail.log");
1161
##
1162
###############################################################################################
1163
sub openLogFile {
1164
    ## Get the incoming filename
1165
    my $filename = $_[0];
1166
 
1167
    ## Make sure our file exists, and if the file doesn't exist then create it
1168
    if ( ! -f $filename ) {
1169
        print STDERR "NOTICE: The log file [$filename] does not exist.  Creating it now with mode [0600].\n" if ($conf{'stdout'});
1170
        open (LOGFILE, ">>$filename");
1171
        close LOGFILE;
1172
        chmod (0600, $filename);
1173
    }
1174
 
1175
    ## Now open the file and attach it to a filehandle
1176
    open (LOGFILE,">>$filename") or return (1);
1177
 
1178
    ## Put the file into non-buffering mode
1179
    select LOGFILE;
1180
    $| = 1;
1181
    select STDOUT;
1182
 
1183
    ## Return success
1184
    return(0);
1185
}
1186
 
1187
 
1188
 
1189
 
1190
 
1191
 
1192
 
1193
 
1194
###############################################################################################
1195
##  Function:    read_file (string $filename)
1196
##  
1197
##  Description: Reads the contents of a file and returns a two part array:
1198
##               ($status, $file-contents)
1199
##               $status is 0 on success, non-zero on error.
1200
##               
1201
##  Example:     ($status, $file) = read_file)("/etc/passwd");
1202
###############################################################################################
1203
sub read_file {
1204
    my ( $filename ) = @_;
1205
 
1206
    ## If the value specified is a file, load the file's contents
1207
    if ( (-e $filename and -r $filename) ) {
1208
        my $FILE;
1209
        if(!open($FILE, ' ' . $filename)) {
1210
            return((1, ""));
1211
        }
1212
        my $file = '';
1213
        while (<$FILE>) {
1214
            $file .= $_;
1215
        }
1216
        ## Strip an ending \r\n
1217
        $file =~ s/\r?\n$//os;
1218
    }
1219
    return((1, ""));
1220
}
1221
 
1222
 
1223
 
1224
 
1225
 
1226
 
1227
 
1228
 
1229
 
1230
###############################################################################################
1231
##  Function:    quit (string $message, int $errorLevel)
1232
##  
1233
##  Description: Exits the program, optionally printing $message.  It 
1234
##               returns an exit error level of $errorLevel to the 
1235
##               system  (0 means no errors, and is assumed if empty.)
1236
##
1237
##  Example:     quit("Exiting program normally", 0);
1238
###############################################################################################
1239
sub quit {
1240
    my ( $message, $errorLevel ) = @_;
1241
    $errorLevel = 0 if (!defined($errorLevel));
1242
 
1243
    ## Print exit message
1244
    if ($message) { 
1245
        printmsg($message, 0);
1246
    }
1247
 
1248
    ## Exit
1249
    exit($errorLevel);
1250
}
1251
 
1252
 
1253
 
1254
 
1255
 
1256
 
1257
 
1258
 
1259
 
1260
 
1261
 
1262
 
1263
###############################################################################################
1264
## Function:    help ()
1265
##
1266
## Description: For all those newbies ;) 
1267
##              Prints a help message and exits the program.
1268
## 
1269
###############################################################################################
1270
sub help {
1271
exit(1) if (!$conf{'stdout'});
1272
print <<EOM;
1273
 
1274
${colorBold}$conf{'programName'}-$conf{'version'} by $conf{'authorName'} <$conf{'authorEmail'}>${colorNoBold}
1275
 
1276
Synopsis:  $conf{'programName'} -f ADDRESS [options]
1277
 
1278
  ${colorRed}Required:${colorNormal}
1279
    -f ADDRESS                from (sender) email address
1280
    * At least one recipient required via -t, -cc, or -bcc
1281
    * Message body required via -m, STDIN, or -o message-file=FILE
1282
 
1283
  ${colorGreen}Common:${colorNormal}
1284
    -t ADDRESS [ADDR ...]     to email address(es)
1285
    -u SUBJECT                message subject
1286
    -m MESSAGE                message body
1287
    -s SERVER[:PORT]          smtp mail relay, default is $conf{'server'}:$conf{'port'}
1288
 
1289
  ${colorGreen}Optional:${colorNormal}
1290
    -a   FILE [FILE ...]      file attachment(s)
1291
    -cc  ADDRESS [ADDR ...]   cc  email address(es)
1292
    -bcc ADDRESS [ADDR ...]   bcc email address(es)
1293
    -xu  USERNAME             username for SMTP authentication
1294
    -xp  PASSWORD             password for SMTP authentication
1295
 
1296
  ${colorGreen}Paranormal:${colorNormal}
1297
    -b BINDADDR[:PORT]        local host bind address
1298
    -l LOGFILE                log to the specified file
1299
    -v                        verbosity, use multiple times for greater effect
1300
    -q                        be quiet (i.e. no STDOUT output)
1301
    -o NAME=VALUE             advanced options, for details try: --help misc
1302
        -o message-file=FILE         -o message-format=raw
1303
        -o message-header=HEADER     -o message-charset=CHARSET
1304
        -o reply-to=ADDRESS          -o timeout=SECONDS
1305
        -o username=USERNAME         -o password=PASSWORD
1306
        -o tls=<auto|yes|no>         -o fqdn=FQDN
1307
 
1308
  ${colorGreen}Help:${colorNormal}
1309
    --help                    the helpful overview you're reading now
1310
    --help addressing         explain addressing and related options
1311
    --help message            explain message body input and related options
1312
    --help networking         explain -s, -b, etc
1313
    --help output             explain logging and other output options
1314
    --help misc               explain -o options, TLS, SMTP auth, and more
1315
 
1316
EOM
1317
exit(1);
1318
}
1319
 
1320
 
1321
 
1322
 
1323
 
1324
 
1325
 
1326
 
1327
 
1328
###############################################################################################
1329
## Function:    helpTopic ($topic)
1330
##
1331
## Description: For all those newbies ;) 
1332
##              Prints a help message and exits the program.
1333
## 
1334
###############################################################################################
1335
sub helpTopic {
1336
    exit(1) if (!$conf{'stdout'});
1337
    my ($topic) = @_;
1338
 
1339
    CASE: {
1340
 
1341
 
1342
 
1343
 
1344
## ADDRESSING
1345
        ($topic eq 'addressing') && do {
1346
            print <<EOM;
1347
 
1348
${colorBold}ADDRESSING DOCUMENTATION${colorNormal}
1349
 
1350
${colorGreen}Addressing Options${colorNormal}
1351
Options related to addressing:
1352
    -f   ADDRESS
1353
    -t   ADDRESS [ADDRESS ...]
1354
    -cc  ADDRESS [ADDRESS ...]
1355
    -bcc ADDRESS [ADDRESS ...]
1356
    -o   reply-to=ADDRESS
1357
 
1358
-f ADDRESS
1359
    This required option specifies who the email is from, I.E. the sender's
1360
    email address.
1361
 
1362
-t ADDRESS [ADDRESS ...]
1363
    This option specifies the primary recipient(s).  At least one recipient
1364
    address must be specified via the -t, -cc. or -bcc options.
1365
 
1366
-cc ADDRESS [ADDRESS ...]
1367
    This option specifies the "carbon copy" recipient(s).  At least one 
1368
    recipient address must be specified via the -t, -cc. or -bcc options.
1369
 
1370
-bcc ADDRESS [ADDRESS ...]
1371
    This option specifies the "blind carbon copy" recipient(s).  At least
1372
    one recipient address must be specified via the -t, -cc. or -bcc options.
1373
 
1374
-o reply-to=ADDRESS
1375
    This option specifies that an optional "Reply-To" address should be
1376
    written in the email's headers.
1377
 
1378
 
1379
${colorGreen}Email Address Syntax${colorNormal}
1380
Email addresses may be specified in one of two ways:
1381
    Full Name:     "John Doe <john.doe\@gmail.com>"
1382
    Just Address:  "john.doe\@gmail.com"
1383
 
1384
The "Full Name" method is useful if you want a name, rather than a plain
1385
email address, to be displayed in the recipient's From, To, or Cc fields
1386
when they view the message.
1387
 
1388
 
1389
${colorGreen}Multiple Recipients${colorNormal}
1390
The -t, -cc, and -bcc options each accept multiple addresses.  They may be
1391
specified by separating them by either a white space, comma, or semi-colon
1392
separated list.  You may also specify the -t, -cc, and -bcc options multiple
1393
times, each occurance will append the new recipients to the respective list.
1394
 
1395
Examples:
1396
(I used "-t" in these examples, but it can be "-cc" or "-bcc" as well)
1397
 
1398
  * Space separated list:
1399
    -t jane.doe\@yahoo.com "John Doe <john.doe\@gmail.com>"
1400
 
1401
  * Semi-colon separated list:
1402
    -t "jane.doe\@yahoo.com; John Doe <john.doe\@gmail.com>"
1403
 
1404
  * Comma separated list:
1405
    -t "jane.doe\@yahoo.com, John Doe <john.doe\@gmail.com>"
1406
 
1407
  * Multiple -t, -cc, or -bcc options:
1408
    -t "jane.doe\@yahoo.com" -t "John Doe <john.doe\@gmail.com>"
1409
 
1410
 
1411
EOM
1412
            last CASE;
1413
        };
1414
 
1415
 
1416
 
1417
 
1418
 
1419
 
1420
## MESSAGE
1421
        ($topic eq 'message') && do {
1422
            print <<EOM;
1423
 
1424
${colorBold}MESSAGE DOCUMENTATION${colorNormal}
1425
 
1426
${colorGreen}Message Options${colorNormal}
1427
Options related to the email message body:
1428
    -u  SUBJECT
1429
    -m  MESSAGE
1430
    -o  message-file=FILE
1431
    -o  message-header=EMAIL HEADER
1432
    -o  message-charset=CHARSET
1433
    -o  message-format=raw
1434
 
1435
-u SUBJECT
1436
    This option allows you to specify the subject for your email message.
1437
    It is not required (anymore) that the subject be quoted, although it 
1438
    is recommended.  The subject will be read until an argument starting
1439
    with a hyphen (-) is found.  
1440
    Examples:
1441
      -u "Contact information while on vacation"
1442
      -u New Microsoft vulnerability discovered
1443
 
1444
-m MESSAGE
1445
    This option is one of three methods that allow you to specify the message
1446
    body for your email.  The message may be specified on the command line
1447
    with this -m option, read from a file with the -o message-file=FILE
1448
    option, or read from STDIN if neither of these options are present.
1449
 
1450
    It is not required (anymore) that the message be quoted, although it is
1451
    recommended.  The message will be read until an argument starting with a
1452
    hyphen (-) is found.
1453
    Examples:
1454
      -m "See you in South Beach, Hawaii.  -Todd"
1455
      -m Please ensure that you upgrade your systems right away
1456
 
1457
    Multi-line message bodies may be specified with the -m option by putting
1458
    a "\\n" into the message.  Example:
1459
      -m "This is line 1.\\nAnd this is line 2."
1460
 
1461
    HTML messages are supported, simply begin your message with "<html>" and
1462
    sendEmail will properly label the mime header so MUAs properly render
1463
    the message.  It is currently not possible without "-o message-format=raw"
1464
    to send a message with both text and html parts with sendEmail.
1465
 
1466
-o message-file=FILE
1467
    This option is one of three methods that allow you to specify the message
1468
    body for your email.  To use this option simply specify a text file
1469
    containing the body of your email message. Examples:
1470
      -o message-file=/root/message.txt
1471
      -o message-file="C:\\Program Files\\output.txt"
1472
 
1473
-o message-header=EMAIL HEADER
1474
    This option allows you to specify additional email headers to be included.
1475
    To add more than one message header simply use this option on the command
1476
    line more than once.  If you specify a message header that sendEmail would
1477
    normally generate the one you specified will be used in it's place.  
1478
    Do not use this unless you know what you are doing!
1479
    Example: 
1480
      To scare a Microsoft Outlook user you may want to try this:
1481
      -o message-header="X-Message-Flag: Message contains illegal content"
1482
    Example: 
1483
      To request a read-receipt try this:
1484
      -o message-header="Disposition-Notification-To: <user\@domain.com>"
1485
    Example: 
1486
      To set the message priority try this:
1487
      -o message-header="X-Priority: 1"
1488
      Priority reference: 1=highest, 2=high, 3=normal, 4=low, 5=lowest
1489
 
1490
-o message-charset=CHARSET
1491
    This option allows you to specify the character-set for the message body.
1492
    The default is iso-8859-1.
1493
 
1494
-o message-format=raw
1495
    This option instructs sendEmail to assume the message (specified with -m,
1496
    read from STDIN, or read from the file specified in -o message-file=FILE)
1497
    is already a *complete* email message.  SendEmail will not generate any
1498
    headers and will transmit the message as-is to the remote SMTP server.
1499
    Due to the nature of this option the following command line options will
1500
    be ignored when this one is used:
1501
      -u SUBJECT
1502
      -o message-header=EMAIL HEADER
1503
      -o message-charset=CHARSET
1504
      -a ATTACHMENT
1505
 
1506
 
1507
${colorGreen}The Message Body${colorNormal}
1508
The email message body may be specified in one of three ways:
1509
 1) Via the -m MESSAGE command line option.
1510
    Example:
1511
      -m "This is the message body"
1512
 
1513
 2) By putting the message body in a file and using the -o message-file=FILE
1514
    command line option.
1515
    Example:
1516
      -o message-file=/root/message.txt
1517
 
1518
 3) By piping the message body to sendEmail when nither of the above command
1519
    line options were specified.
1520
    Example:
1521
      grep "ERROR" /var/log/messages | sendEmail -t you\@domain.com ...
1522
 
1523
If the message body begins with "<html>" then the message will be treated as
1524
an HTML message and the MIME headers will be written so that a HTML capable
1525
email client will display the message in it's HTML form.
1526
Any of the above methods may be used with the -o message-format=raw option 
1527
to deliver an already complete email message.
1528
 
1529
 
1530
EOM
1531
            last CASE;
1532
        };
1533
 
1534
 
1535
 
1536
 
1537
 
1538
 
1539
## MISC
1540
        ($topic eq 'misc') && do {
1541
            print <<EOM;
1542
 
1543
${colorBold}MISC DOCUMENTATION${colorNormal}
1544
 
1545
${colorGreen}Misc Options${colorNormal}
1546
Options that don't fit anywhere else:
1547
    -a   ATTACHMENT [ATTACHMENT ...]
1548
    -xu  USERNAME
1549
    -xp  PASSWORD
1550
    -o   username=USERNAME
1551
    -o   password=PASSWORD
1552
    -o   tls=<auto|yes|no>
1553
    -o   timeout=SECONDS
1554
    -o   fqdn=FQDN
1555
 
1556
-a   ATTACHMENT [ATTACHMENT ...]
1557
    This option allows you to attach any number of files to your email message.
1558
    To specify more than one attachment, simply separate each filename with a
1559
    space.  Example: -a file1.txt file2.txt file3.txt
1560
 
1561
-xu  USERNAME
1562
    Alias for -o username=USERNAME
1563
 
1564
-xp  PASSWORD
1565
    Alias for -o password=PASSWORD
1566
 
1567
-o   username=USERNAME (synonym for -xu)
1568
    These options allow specification of a username to be used with SMTP
1569
    servers that require authentication.  If a username is specified but a
1570
    password is not, you will be prompted to enter one at runtime.
1571
 
1572
-o   password=PASSWORD (synonym for -xp)
1573
    These options allow specification of a password to be used with SMTP
1574
    servers that require authentication.  If a username is specified but a
1575
    password is not, you will be prompted to enter one at runtime. 
1576
 
1577
-o   tls=<auto|yes|no>
1578
    This option allows you to specify if TLS (SSL for SMTP) should be enabled
1579
    or disabled.  The default, auto, will use TLS automatically if your perl
1580
    installation has the IO::Socket::SSL and Net::SSLeay modules available,
1581
    and if the remote SMTP server supports TLS.  To require TLS for message
1582
    delivery set this to yes.  To disable TLS support set this to no.  A debug
1583
    level of one or higher will reveal details about the status of TLS.
1584
 
1585
-o   timeout=SECONDS    
1586
    This option sets the timeout value in seconds used for all network reads,
1587
    writes, and a few other things.
1588
 
1589
-o   fqdn=FQDN    
1590
    This option sets the Fully Qualified Domain Name used during the initial
1591
    SMTP greeting.  Normally this is automatically detected, but in case you
1592
    need to manually set it for some reason or get a warning about detection
1593
    failing, you can use this to override the default.
1594
 
1595
 
1596
EOM
1597
            last CASE;
1598
        };
1599
 
1600
 
1601
 
1602
 
1603
 
1604
 
1605
## NETWORKING
1606
        ($topic eq 'networking') && do {
1607
            print <<EOM;
1608
 
1609
${colorBold}NETWORKING DOCUMENTATION${colorNormal}
1610
 
1611
${colorGreen}Networking Options${colorNormal}
1612
Options related to networking:
1613
    -s   SERVER[:PORT]
1614
    -b   BINDADDR[:PORT]
1615
    -o   tls=<auto|yes|no>
1616
    -o   timeout=SECONDS
1617
 
1618
-s SERVER[:PORT]
1619
    This option allows you to specify the SMTP server sendEmail should
1620
    connect to to deliver your email message to.  If this option is not
1621
    specified sendEmail will try to connect to localhost:25 to deliver
1622
    the message.  THIS IS MOST LIKELY NOT WHAT YOU WANT, AND WILL LIKELY
1623
    FAIL unless you have a email server (commonly known as an MTA) running
1624
    on your computer!
1625
    Typically you will need to specify your company or ISP's email server.
1626
    For example, if you use CableOne you will need to specify:
1627
       -s mail.cableone.net
1628
    If you have your own email server running on port 300 you would
1629
    probably use an option like this:
1630
       -s myserver.mydomain.com:300
1631
 
1632
-b BINDADDR[:PORT]
1633
    This option allows you to specify the local IP address (and optional
1634
    tcp port number) for sendEmail to bind to when connecting to the remote
1635
    SMTP server.  This useful for people who need to send an email from a
1636
    specific network interface or source address and are running sendEmail on
1637
    a firewall or other host with several network interfaces.
1638
 
1639
-o   tls=<auto|yes|no>
1640
    This option allows you to specify if TLS (SSL for SMTP) should be enabled
1641
    or disabled.  The default, auto, will use TLS automatically if your perl
1642
    installation has the IO::Socket::SSL and Net::SSLeay modules available,
1643
    and if the remote SMTP server supports TLS.  To require TLS for message
1644
    delivery set this to yes.  To disable TLS support set this to no.  A debug
1645
    level of one or higher will reveal details about the status of TLS.
1646
 
1647
-o timeout=SECONDS    
1648
    This option sets the timeout value in seconds used for all network reads,
1649
    writes, and a few other things.
1650
 
1651
 
1652
EOM
1653
            last CASE;
1654
        };
1655
 
1656
 
1657
 
1658
 
1659
 
1660
 
1661
## OUTPUT
1662
        ($topic eq 'output') && do {
1663
            print <<EOM;
1664
 
1665
${colorBold}OUTPUT DOCUMENTATION${colorNormal}
1666
 
1667
${colorGreen}Output Options${colorNormal}
1668
Options related to output:
1669
    -l LOGFILE
1670
    -v
1671
    -q
1672
 
1673
-l LOGFILE
1674
    This option allows you to specify a log file to append to.  Every message
1675
    that is displayed to STDOUT is also written to the log file.  This may be
1676
    used in conjunction with -q and -v.
1677
 
1678
-q
1679
    This option tells sendEmail to disable printing to STDOUT.  In other
1680
    words nothing will be printed to the console.  This does not affect the
1681
    behavior of the -l or -v options.
1682
 
1683
-v
1684
    This option allows you to increase the debug level of sendEmail.  You may
1685
    either use this option more than once, or specify more than one v at a
1686
    time to obtain a debug level higher than one.  Examples:
1687
        Specifies a debug level of 1:  -v
1688
        Specifies a debug level of 2:  -vv
1689
        Specifies a debug level of 2:  -v -v
1690
    A debug level of one is recommended when doing any sort of debugging.  
1691
    At that level you will see the entire SMTP transaction (except the
1692
    body of the email message), and hints will be displayed for most
1693
    warnings and errors.  The highest debug level is three.
1694
 
1695
 
1696
EOM
1697
            last CASE;
1698
        };
1699
 
1700
        ## Unknown option selected!
1701
        quit("ERROR => The help topic specified is not valid!", 1);
1702
    };
1703
 
1704
exit(1);
1705
}
1706
 
1707
 
1708
 
1709
 
1710
 
1711
 
1712
 
1713
 
1714
 
1715
 
1716
 
1717
 
1718
 
1719
 
1720
 
1721
 
1722
 
1723
 
1724
 
1725
 
1726
 
1727
 
1728
#############################
1729
##                          ##
1730
##      MAIN PROGRAM         ##
1731
##                          ##
1732
#############################
1733
 
1734
 
1735
## Initialize
1736
initialize();
1737
 
1738
## Process Command Line
1739
processCommandLine();
1740
$conf{'alarm'} = $opt{'timeout'};
1741
 
1742
## Abort program after $conf{'alarm'} seconds to avoid infinite hangs
1743
alarm($conf{'alarm'}) if ($^O !~ /win/i);  ## alarm() doesn't work in win32
1744
 
1745
 
1746
 
1747
 
1748
###################################################
1749
##  Read $message from STDIN if -m was not used  ##
1750
###################################################
1751
 
1752
if (!($message)) {
1753
    ## Read message body from a file specified with -o message-file=
1754
    if ($opt{'message-file'}) {
1755
        if (! -e $opt{'message-file'}) {
1756
            printmsg("ERROR => Message body file specified [$opt{'message-file'}] does not exist!", 0);
1757
            printmsg("HINT => 1) check spelling of your file; 2) fully qualify the path; 3) doubble quote it", 1);
1758
            quit("", 1);
1759
        }
1760
        if (! -r $opt{'message-file'}) {
1761
            printmsg("ERROR => Message body file specified can not be read due to restricted permissions!", 0);
1762
            printmsg("HINT => Check permissions on file specified to ensure it can be read", 1);
1763
            quit("", 1);
1764
        }
1765
        if (!open(MFILE, "< " . $opt{'message-file'})) {
1766
            printmsg("ERROR => Error opening message body file [$opt{'message-file'}]: $!", 0);
1767
            quit("", 1);
1768
        }
1769
        while (<MFILE>) {
1770
            $message .= $_;
1771
        }
1772
        close(MFILE);
1773
    }
1774
 
1775
    ## Read message body from STDIN
1776
    else {
1777
        alarm($conf{'alarm'}) if ($^O !~ /win/i);  ## alarm() doesn't work in win32
1778
        if ($conf{'stdout'}) {
1779
            print "Reading message body from STDIN because the '-m' option was not used.\n";
1780
            print "If you are manually typing in a message:\n";
1781
            print "  - First line must be received within $conf{'alarm'} seconds.\n" if ($^O !~ /win/i);
1782
            print "  - End manual input with a CTRL-D on its own line.\n\n" if ($^O !~ /win/i);
1783
            print "  - End manual input with a CTRL-Z on its own line.\n\n" if ($^O =~ /win/i);
1784
        }
1785
        while (<STDIN>) {                 ## Read STDIN into $message
1786
            $message .= $_;
1787
            alarm(0) if ($^O !~ /win/i);  ## Disable the alarm since at least one line was received
1788
        }
1789
        printmsg("Message input complete.", 0);
1790
    }
1791
}
1792
 
1793
## Replace bare LF's with CRLF's (\012 should always have \015 with it)
1794
$message =~ s/(\015)?(\012|$)/\015\012/g;
1795
 
1796
## Replace bare CR's with CRLF's (\015 should always have \012 with it)
1797
$message =~ s/(\015)(\012|$)?/\015\012/g;
1798
 
1799
## Check message for bare periods and encode them
1800
$message =~ s/(^|$CRLF)(\.{1})($CRLF|$)/$1.$2$3/g;
1801
 
1802
## Get the current date for the email header
1803
my ($sec,$min,$hour,$mday,$mon,$year,$day) = gmtime();
1804
$year += 1900; $mon = return_month($mon); $day = return_day($day);
1805
my $date = sprintf("%s, %s %s %d %.2d:%.2d:%.2d %s",$day, $mday, $mon, $year, $hour, $min, $sec, $conf{'timezone'});
1806
 
1807
 
1808
 
1809
 
1810
##################################
1811
##  Connect to the SMTP server  ##
1812
##################################
1813
printmsg("DEBUG => Connecting to $conf{'server'}:$conf{'port'}", 1);
1814
$SIG{'ALRM'} = sub { 
1815
    printmsg("ERROR => Timeout while connecting to $conf{'server'}:$conf{'port'}  There was no response after $conf{'alarm'} seconds.", 0); 
1816
    printmsg("HINT => Try specifying a different mail relay with the -s option.", 1);
1817
    quit("", 1);
1818
};
1819
alarm($conf{'alarm'}) if ($^O !~ /win/i);  ## alarm() doesn't work in win32;
1820
$SERVER = IO::Socket::INET->new( PeerAddr  => $conf{'server'},
1821
                                 PeerPort  => $conf{'port'},
1822
                                 LocalAddr => $conf{'bindaddr'},
1823
                                 Proto     => 'tcp',
1824
                                 Autoflush => 1,
1825
                                 timeout   => $conf{'alarm'},
1826
);
1827
alarm(0) if ($^O !~ /win/i);  ## alarm() doesn't work in win32;
1828
 
1829
## Make sure we got connected
1830
if ( (!$SERVER) or (!$SERVER->opened()) ) {
1831
    printmsg("ERROR => Connection attempt to $conf{'server'}:$conf{'port'} failed: $@", 0);
1832
    printmsg("HINT => Try specifying a different mail relay with the -s option.", 1);
1833
    quit("", 1);
1834
}
1835
 
1836
## Save our IP address for later
1837
$conf{'ip'} = $SERVER->sockhost();
1838
printmsg("DEBUG => My IP address is: $conf{'ip'}", 1);
1839
 
1840
 
1841
 
1842
 
1843
 
1844
 
1845
 
1846
#########################
1847
##  Do the SMTP Dance  ##
1848
#########################
1849
 
1850
## Read initial greeting to make sure we're talking to a live SMTP server
1851
if (SMTPchat()) { quit($conf{'error'}, 1); }
1852
 
1853
## We're about to use $opt{'fqdn'}, make sure it isn't empty
1854
if (!$opt{'fqdn'}) {
1855
    ## Ok, that means we couldn't get a hostname, how about using the IP address for the HELO instead
1856
    $opt{'fqdn'} = "[" . $conf{'ip'} . "]";
1857
}
1858
 
1859
## EHLO
1860
if (SMTPchat('EHLO ' . $opt{'fqdn'}))   {
1861
    printmsg($conf{'error'}, 0);
1862
    printmsg("NOTICE => EHLO command failed, attempting HELO instead");
1863
    if (SMTPchat('HELO ' . $opt{'fqdn'})) { quit($conf{'error'}, 1); }
1864
    if ( $opt{'username'} and $opt{'password'} ) {
1865
        printmsg("WARNING => The mail server does not support SMTP authentication!", 0);
1866
    }
1867
}
1868
else {
1869
 
1870
    ## Determin if the server supports TLS
1871
    if ($conf{'SMTPchat_response'} =~ /STARTTLS/) {
1872
        $conf{'tls_server'} = 1;
1873
        printmsg("DEBUG => The remote SMTP server supports TLS :)", 2);
1874
    }
1875
    else {
1876
        $conf{'tls_server'} = 0;
1877
        printmsg("DEBUG => The remote SMTP server does NOT support TLS :(", 2);
1878
    }
1879
 
1880
    ## Start TLS if possible
1881
    if ($conf{'tls_server'} == 1 and $conf{'tls_client'} == 1 and $opt{'tls'} =~ /^(yes|auto)$/) {
1882
        printmsg("DEBUG => Starting TLS", 2);
1883
        if (SMTPchat('STARTTLS')) { quit($conf{'error'}, 1); }
1884
        if (! IO::Socket::SSL->start_SSL($SERVER, SSL_version => 'SSLv3 TLSv1')) {
1885
            quit("ERROR => TLS setup failed: " . IO::Socket::SSL::errstr(), 1);
1886
        }
1887
        printmsg("DEBUG => TLS: Using cipher: ". $SERVER->get_cipher(), 3);
1888
        printmsg("DEBUG => TLS session initialized :)", 1);
1889
 
1890
        ## Restart our SMTP session
1891
        if (SMTPchat('EHLO ' . $opt{'fqdn'})) { quit($conf{'error'}, 1); }
1892
    }
1893
    elsif ($opt{'tls'} eq 'yes' and $conf{'tls_server'} == 0) {
1894
        quit("ERROR => TLS not possible! Remote SMTP server, $conf{'server'},  does not support it.", 1);
1895
    }
1896
 
1897
 
1898
    ## Do SMTP Auth if required
1899
    if ( $opt{'username'} and $opt{'password'} ) {
1900
        if ($conf{'SMTPchat_response'} !~ /AUTH\s/) {
1901
            printmsg("NOTICE => Authentication not supported by the remote SMTP server!", 0);
1902
        }
1903
        else {
1904
            # ## SASL CRAM-MD5 authentication method
1905
            # if ($conf{'SMTPchat_response'} =~ /\bCRAM-MD5\b/i) {
1906
            #     printmsg("DEBUG => SMTP-AUTH: Using CRAM-MD5 authentication method", 1);
1907
            #     if (SMTPchat('AUTH CRAM-MD5')) { quit($conf{'error'}, 1); }
1908
            #     
1909
            #     ## FIXME!!
1910
            #     
1911
            #     printmsg("DEBUG => User authentication was successful", 1);
1912
            # }
1913
 
1914
            ## SASL PLAIN authentication method
1915
            if ($conf{'SMTPchat_response'} =~ /\bPLAIN\b/i) {
1916
                printmsg("DEBUG => SMTP-AUTH: Using PLAIN authentication method", 1);
1917
                if (SMTPchat('AUTH PLAIN ' . base64_encode("$opt{'username'}\0$opt{'username'}\0$opt{'password'}"))) { quit($conf{'error'}, 1); }
1918
                printmsg("DEBUG => User authentication was successful", 1);
1919
            }
1920
 
1921
            ## SASL LOGIN authentication method
1922
            elsif ($conf{'SMTPchat_response'} =~ /\bLOGIN\b/i) {
1923
                printmsg("DEBUG => SMTP-AUTH: Using LOGIN authentication method", 1);
1924
                if (SMTPchat('AUTH LOGIN')) { quit($conf{'error'}, 1); }
1925
                if (SMTPchat(base64_encode($opt{'username'}))) { quit($conf{'error'}, 1); }
1926
                if (SMTPchat(base64_encode($opt{'password'}))) { quit($conf{'error'}, 1); }
1927
                printmsg("DEBUG => User authentication was successful", 1);
1928
            }
1929
 
1930
            else {
1931
                printmsg("WARNING => SMTP-AUTH: No mutually supported authentication methods available", 0);
1932
            }
1933
        }
1934
    }
1935
}
1936
 
1937
## MAIL FROM
1938
if (SMTPchat('MAIL FROM:<' .(returnAddressParts($from))[1]. '>')) { quit($conf{'error'}, 1); }
1939
 
1940
## RCPT TO
1941
my $oneRcptAccepted = 0;
1942
foreach my $rcpt (@to, @cc, @bcc) {
1943
    my ($name, $address) = returnAddressParts($rcpt);
1944
    if (SMTPchat('RCPT TO:<' . $address . '>')) {
1945
        printmsg("WARNING => The recipient <$address> was rejected by the mail server, error follows:", 0);
1946
        $conf{'error'} =~ s/^ERROR/WARNING/o;
1947
        printmsg($conf{'error'}, 0);
1948
    }
1949
    elsif ($oneRcptAccepted == 0) {
1950
        $oneRcptAccepted = 1;
1951
    }
1952
}
1953
## If no recipients were accepted we need to exit with an error.
1954
if ($oneRcptAccepted == 0) {
1955
    quit("ERROR => Exiting. No recipients were accepted for delivery by the mail server.", 1);
1956
}
1957
 
1958
## DATA
1959
if (SMTPchat('DATA')) { quit($conf{'error'}, 1); }
1960
 
1961
 
1962
###############################
1963
##  Build and send the body  ##
1964
###############################
1965
printmsg("INFO => Sending message body",1);
1966
 
1967
## If the message-format is raw just send the message as-is.
1968
if ($opt{'message-format'} =~ /^raw$/i) {
1969
    print $SERVER $message;
1970
}
1971
 
1972
## If the message-format isn't raw, then build and send the message,
1973
else {
1974
 
1975
    ## Message-ID: <MessageID>
1976
    if ($opt{'message-header'} !~ /^Message-ID:/iom) {
1977
        $header .= 'Message-ID: <' . $conf{'Message-ID'} . '@' . $conf{'hostname'} . '>' . $CRLF;
1978
    }
1979
 
1980
    ## From: "Name" <address@domain.com> (the pointless test below is just to keep scoping correct)
1981
    if ($from and $opt{'message-header'} !~ /^From:/iom) {
1982
        my ($name, $address) = returnAddressParts($from);
1983
        $header .= 'From: "' . $name . '" <' . $address . '>' . $CRLF;
1984
    }
1985
 
1986
    ## Reply-To: 
1987
    if ($opt{'reply-to'} and $opt{'message-header'} !~ /^Reply-To:/iom) {
1988
        my ($name, $address) = returnAddressParts($opt{'reply-to'});
1989
        $header .= 'Reply-To: "' . $name . '" <' . $address . '>' . $CRLF;
1990
    }
1991
 
1992
    ## To: "Name" <address@domain.com>
1993
    if ($opt{'message-header'} =~ /^To:/iom) {
1994
        ## The user put the To: header in via -o message-header - dont do anything
1995
    }
1996
    elsif (scalar(@to) > 0) {
1997
        $header .= "To:";
1998
        for (my $a = 0; $a < scalar(@to); $a++) {
1999
            my $msg = "";
2000
 
2001
            my ($name, $address) = returnAddressParts($to[$a]);
2002
            $msg = " \"$name\" <$address>";
2003
 
2004
            ## If we're not on the last address add a comma to the end of the line.
2005
            if (($a + 1) != scalar(@to)) {
2006
                $msg .= ",";
2007
            }
2008
 
2009
            $header .= $msg . $CRLF;
2010
        }
2011
    }
2012
    ## We always want a To: line so if the only recipients were bcc'd they don't see who it was sent to
2013
    else {
2014
        $header .= "To: \"Undisclosed Recipients\" <>$CRLF";
2015
    }
2016
 
2017
    if (scalar(@cc) > 0 and $opt{'message-header'} !~ /^Cc:/iom) {
2018
        $header .= "Cc:";
2019
        for (my $a = 0; $a < scalar(@cc); $a++) {
2020
            my $msg = "";
2021
 
2022
            my ($name, $address) = returnAddressParts($cc[$a]);
2023
            $msg = " \"$name\" <$address>";
2024
 
2025
            ## If we're not on the last address add a comma to the end of the line.
2026
            if (($a + 1) != scalar(@cc)) {
2027
                $msg .= ",";
2028
            }
2029
 
2030
            $header .= $msg . $CRLF;
2031
        }
2032
    }
2033
 
2034
    if ($opt{'message-header'} !~ /^Subject:/iom) {
2035
        $header .= 'Subject: ' . $subject . $CRLF;                   ## Subject
2036
    }
2037
    if ($opt{'message-header'} !~ /^Date:/iom) {
2038
        $header .= 'Date: ' . $date . $CRLF;                         ## Date
2039
    }
2040
    if ($opt{'message-header'} !~ /^X-Mailer:/iom) {
2041
        $header .= 'X-Mailer: sendEmail-'.$conf{'version'}.$CRLF;    ## X-Mailer
2042
    }
2043
    ## I wonder if I should put this in by default?
2044
    # if ($opt{'message-header'} !~ /^X-Originating-IP:/iom) {
2045
    #     $header .= 'X-Originating-IP: ['.$conf{'ip'}.']'.$CRLF;      ## X-Originating-IP
2046
    # }
2047
 
2048
    ## Encode all messages with MIME.
2049
    if ($opt{'message-header'} !~ /^MIME-Version:/iom) {
2050
        $header .=  "MIME-Version: 1.0$CRLF";
2051
    }
2052
    if ($opt{'message-header'} !~ /^Content-Type:/iom) {
2053
        my $content_type = 'multipart/mixed';
2054
        if (scalar(@attachments) == 0) { $content_type = 'multipart/related'; }
2055
        $header .= "Content-Type: $content_type; boundary=\"$conf{'delimiter'}\"$CRLF";
2056
    }
2057
 
2058
    ## Send additional message header line(s) if specified
2059
    if ($opt{'message-header'}) {
2060
        $header .= $opt{'message-header'};
2061
    }
2062
 
2063
    ## Send the message header to the server
2064
    print $SERVER $header . $CRLF;
2065
 
2066
    ## Start sending the message body to the server
2067
    print $SERVER "This is a multi-part message in MIME format. To properly display this message you need a MIME-Version 1.0 compliant Email program.$CRLF";
2068
    print $SERVER "$CRLF";
2069
 
2070
 
2071
    ## Send message body
2072
    print $SERVER "--$conf{'delimiter'}$CRLF";
2073
    ## If the message contains HTML change the Content-Type
2074
    if ($message =~ /^\s*<html>/i) {
2075
        printmsg("Message is in HTML format", 1);
2076
        print $SERVER "Content-Type: text/html;$CRLF";
2077
    }
2078
    ## Otherwise it's a normal text email
2079
    else {
2080
        print $SERVER "Content-Type: text/plain;$CRLF";
2081
    }
2082
    print $SERVER "        charset=\"" . $opt{'message-charset'} . "\"$CRLF";
2083
    print $SERVER "Content-Transfer-Encoding: 7bit$CRLF";
2084
    print $SERVER $CRLF . $message;
2085
 
2086
 
2087
 
2088
    ## Send Attachemnts
2089
    if (scalar(@attachments) > 0) {
2090
        ## Disable the alarm so people on modems can send big attachments
2091
        alarm(0) if ($^O !~ /win/i);  ## alarm() doesn't work in win32
2092
 
2093
        ## Send the attachments
2094
        foreach my $filename (@attachments) {
2095
            ## This is check 2, we already checked this above, but just in case...
2096
            if ( ! -f $filename ) {
2097
                printmsg("ERROR => The file [$filename] doesn't exist!  Email will be sent, but without that attachment.", 0);
2098
            }
2099
            elsif ( ! -r $filename ) {
2100
                printmsg("ERROR => Couldn't open the file [$filename] for reading: $!   Email will be sent, but without that attachment.", 0);
2101
            }
2102
            else {
2103
                printmsg("DEBUG => Sending the attachment [$filename]", 1);
2104
                send_attachment($filename);
2105
            }
2106
        }
2107
    }
2108
 
2109
 
2110
    ## End the mime encoded message
2111
    print $SERVER "$CRLF--$conf{'delimiter'}--$CRLF";  
2112
}
2113
 
2114
 
2115
## Tell the server we are done sending the email
2116
print $SERVER "$CRLF.$CRLF";
2117
if (SMTPchat()) { quit($conf{'error'}, 1); }
2118
 
2119
 
2120
 
2121
####################
2122
#  We are done!!!  #
2123
####################
2124
 
2125
## Disconnect from the server (don't SMTPchat(), it breaks when using TLS)
2126
print $SERVER "QUIT$CRLF";
2127
close $SERVER;
2128
 
2129
 
2130
 
2131
 
2132
 
2133
 
2134
#######################################
2135
##  Generate exit message/log entry  ##
2136
#######################################
2137
 
2138
if ($conf{'debug'} or $conf{'logging'}) {
2139
    printmsg("Generating a detailed exit message", 3);
2140
 
2141
    ## Put the message together
2142
    my $output = "Email was sent successfully!  From: <" . (returnAddressParts($from))[1] . "> ";
2143
 
2144
    if (scalar(@to) > 0) {
2145
        $output .= "To: ";
2146
        for ($a = 0; $a < scalar(@to); $a++) {
2147
            $output .= "<" . (returnAddressParts($to[$a]))[1] . "> ";
2148
        }
2149
    }
2150
    if (scalar(@cc) > 0) {
2151
        $output .= "Cc: ";
2152
        for ($a = 0; $a < scalar(@cc); $a++) {
2153
            $output .= "<" . (returnAddressParts($cc[$a]))[1] . "> ";
2154
        }
2155
    }
2156
    if (scalar(@bcc) > 0) {
2157
        $output .= "Bcc: ";
2158
        for ($a = 0; $a < scalar(@bcc); $a++) {
2159
            $output .= "<" . (returnAddressParts($bcc[$a]))[1] . "> ";
2160
        }
2161
    }
2162
    $output .= "Subject: [$subject] " if ($subject);
2163
    if (scalar(@attachments_names) > 0) { 
2164
        $output .= "Attachment(s): ";
2165
        foreach(@attachments_names) {
2166
            $output .= "[$_] ";
2167
        }
2168
    }
2169
    $output .= "Server: [$conf{'server'}:$conf{'port'}]";
2170
 
2171
 
2172
######################
2173
#  Exit the program  #
2174
######################
2175
 
2176
    ## Print / Log the detailed message
2177
    quit($output, 0);
2178
}
2179
else {
2180
    ## Or the standard message
2181
    quit("Email was sent successfully!", 0);
2182
}
2183