This file is indexed.

/usr/share/perl5/Net/Server/Mail.pm is in libnet-server-mail-perl 0.23-1ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
package Net::Server::Mail;

use 5.006;
use strict;
use warnings;
use Sys::Hostname;
use IO::Select;
use IO::Handle;
use Carp;

use constant HOSTNAME => hostname();

$Net::Server::Mail::VERSION = '0.23';

=pod

=head1 NAME

Net::Server::Mail - Class to easily create a mail server

=head1 SYNOPSIS

    use Net::Server::Mail::SMTP;

    my @local_domains = qw(example.com example.org);
    my $server = IO::Socket::INET->new( Listen => 1, LocalPort => 25 );
    
    my $conn;
    while($conn = $server->accept)
    {
        my $smtp = Net::Server::Mail::SMTP->new( socket => $conn );
        $smtp->set_callback(RCPT => \&validate_recipient);
        $smtp->set_callback(DATA => \&queue_message);
        $smtp->process();
        $conn->close();
    }

    sub validate_recipient
    {
        my($session, $recipient) = @_;
        
        my $domain;
        if($recipient =~ /@(.*)>\s*$/)
        {
            $domain = $1;
        }

        if(not defined $domain)
        {
            return(0, 513, 'Syntax error.');
        }
        elsif(not(grep $domain eq $_, @local_domains))
        {
            return(0, 554, "$recipient: Recipient address rejected: Relay access denied");
        }

        return(1);
    }

    sub queue_message
    {
        my($session, $data) = @_;

        my $sender = $session->get_sender();
        my @recipients = $session->get_recipients();

        return(0, 554, 'Error: no valid recipients')
            unless(@recipients);
        
        my $msgid = add_queue($sender, \@recipients, $data);
          or return(0);

        return(1, 250, "message queued $msgid");
    }

=head1 DESCRIPTION

This module is a versatile and extensible implementation of the SMTP
protocol and its different evolutions like ESMTP and LMTP. The event
driven object-oriented API makes easy to incorporate the SMTP protocol
to your programs.

Other SMTPd implementations don't support useful ESMTP extensions and
the LMTP protocol. Their interface design precludes adding them
later. So I've decided to rewrite a complete implementation with
extensibility in mind.

It provides mechanism to easy addition future or not yet implemented
ESMTP extensions. Developers can hook code at each SMTP session state
and change the module's behaviors by registering event call-backs. The
class is designed to be easily inherited from.

This class is the base class for mail service protocols such as
B<Net::Server::Mail::SMTP>, B<Net::Server::Mail::ESMTP> and
B<Net::Server::Mail::LMTP>. Refer to the documentation provided with
each of these modules.

=head1 METHODS

=head2 new

    $instance = Net::Server::Mail->new( [option => 'value', ...] )

options:

=over 4

=item handle_in

Sets the input handle, from which the server reads data. Defaults to
STDIN.

=item handle_out

Sets the output handle, to which the server writes data. Defaults to
STDOUT.

=item socket

Sets a socket to be used for server reads and writes instead of
handles.

=item error_sleep_time

Number of seconds to wait for before printing an error message. This
avoids some DoS attacks that attempt to flood the server with bogus
commands. A value of 0 turns this feature off. Defaults to 0.

=item idle_timeout

Number of seconds a connection must remain idle before it is closed.
A value of 0 turns this feature off. Defaults to 0.

=back

=cut

sub new {
    my ( $proto, @args ) = @_;
    my $class = ref $proto || $proto;
    my $self = {};
    bless( $self, $class );
    return $self->init(@args);
}

sub init {
    my $self = shift;
    confess("odd number of arguments") if ( @_ % 2 );
    my $options = $self->{options} = {
        handle_in        => undef,
        handle_out       => undef,
        socket           => undef,
        error_sleep_time => 0,
        idle_timeout     => 0,
    };
    for ( my $i = 0 ; $i < @_ ; $i += 2 ) {
        $options->{ lc( $_[$i] ) } = $_[ $i + 1 ];
    }

    if ( defined $options->{handle_in} && defined $options->{handle_out} ) {
        if ( UNIVERSAL::isa( $options->{handle_in}, 'IO::Handle' ) ) {
            $self->{in} = $options->{handle_in};
        }
        else {
            $self->{in} =
              IO::Handle->new->fdopen( fileno( $options->{handle_in} ), "r" );
        }
        if ( UNIVERSAL::isa( $options->{handle_out}, 'IO::Handle' ) ) {
            $self->{out} = $options->{handle_out};
        }
        else {
            $self->{out} =
              IO::Handle->new->fdopen( fileno( $options->{handle_out} ), "w" );
        }
    }
    elsif ( defined $options->{'socket'} ) {
        $self->{in}  = $options->{'socket'};
        $self->{out} = $options->{'socket'};
    }
    else {
        $self->{in}  = IO::Handle->new->fdopen( fileno(STDIN),  "r" );
        $self->{out} = IO::Handle->new->fdopen( fileno(STDOUT), "w" );
    }

    $self->{out}->autoflush(1);
    $self->{process_operation} = \&process_operation;

    return $self;
}

=pod

=head2 dojob

Some commands need to do a job after the handler call. The handler
may want to override this to prevent the job from being executed.

By calling this method with a (defined) false value as an argument,
the expected job isn't executed. Defaults to true.

=cut

sub init_dojob { shift->{_dojob} = 1; }

sub dojob {
    my ( $self, $bool ) = @_;
    $self->{_dojob} = $bool if ( defined $bool );
    return $self->{_dojob};
}

sub make_event {
    my $self = shift;
    confess('odd number of arguments') if ( @_ % 2 );
    my %args = @_;

    my $name = $args{'name'} || confess('missing argument: \'name\'');
    my $args =
      defined $args{'arguments'}
      && ref $args{'arguments'} eq 'ARRAY' ? $args{'arguments'} : [];

    $self->init_dojob();
    my ( $success, $code, $msg ) = $self->callback( $name, @{$args} );

    # we have to take a proper decision if successness is undefined
    if ( not defined $success ) {
        if ( exists $args{'default_reply'} ) {
            if ( ref $args{'default_reply'} eq 'ARRAY' ) {
                ( $success, $code, $msg ) = $args{'default_reply'};
                $success = 0 unless defined $success;
            }
            else {
                $success = $args{'default_reply'};
            }
        }
        else {
            $success = 1;    # default
        }
    }

    # command may have some job to do regarding to the result. handler
    # can avoid it by calling dojob() method with a false value.
    if ( $self->dojob() ) {
        if ($success) {
            if ( defined $args{'on_success'}
                and ref $args{'on_success'} eq 'CODE' )
            {
                &{ $args{'on_success'} };
            }
        }
        else {
            if ( defined $args{'on_failure'}
                and ref $args{'on_failure'} eq 'CODE' )
            {
                &{ $args{'on_failure'} };
            }
        }
    }

    # ensure that a reply is sent, all SMTP command need at most 1 reply.
    # some events such as 'stop_session' don't require sending reply.
    unless ( defined $code && !$args{'no_reply'} ) {
        if ( defined $success && $success ) {
            ( $code, $msg ) =
              $self->get_default_reply( $args{'success_reply'}, 250 );
        }
        else {
            ( $code, $msg ) =
              $self->get_default_reply( $args{'failure_reply'}, 550 );
        }
    }

    die "return code `$code' isn't numeric" if ( defined $code && $code =~ /\D/ );

    $self->handle_reply( $name, $success, $code, $msg )
      if defined $code and length $code;

    return $success;
}

sub get_default_reply {
    my ( $self, $config, $default ) = @_;

    my ( $code, $msg );
    if ( defined $config ) {
        if ( ref $config eq 'ARRAY' ) {
            ( $code, $msg ) = @$config;
        }
        elsif ( not ref $config ) {
            $code = $config;
        }
        else {
            confess("unexpected format for reply");
        }
    }
    else {
        $code = $default;
    }

    return ( $code, $msg );
}

sub handle_reply {
    my ( $self, $verb, $success, $code, $msg ) = @_;

    # don't reply anything if code is empty
    $self->reply( $code, $msg ) if ( length $code );
}

sub callback {
    my ( $self, $name, @args ) = @_;

    if ( defined $self->{callback}->{$name} ) {
        my @rv;
        eval {
            my ( $code, $context ) = @{ $self->{callback}->{$name} };
            $self->set_context($context);
            @rv = &{$code}( $self, @args );
        };
        if ($@) {
            confess $@;
        }
        return @rv;
    }

    return 1;
}

sub set_context {
    my ( $self, $context ) = @_;
    $self->{_context} = $context;
}

sub get_context {
    my ($self) = @_;
    return $self->{_context};
}

=pod

=head2 set_callback

  ($success, $code, $msg) = $obj->set_callback(VERB, \&function, $context)>

Sets the callback code to be called on a particular event. The function should
return 1 to 3 values: (success, [return_code, ["message"]]).

    $mailserver->set_callback
    (
        'RCPT', sub
        {
            my($address) = @_;
            if(is_relayed($address))
            {
                # default success code/message will be used
                return 1;
            }
            else
            {
                return(0, 513, 'Relaying denied.');
            }
        }
    );

=cut

sub set_callback {
    my ( $self, $name, $code, $context ) = @_;
    confess('bad callback() invocation')
      unless defined $code && ref $code eq 'CODE';
    $self->{callback}->{$name} = [ $code, $context ];
}

sub def_verb {
    my ( $self, $verb, $coderef ) = @_;
    $self->{verb}->{ uc $verb } = $coderef;
}

sub undef_verb {
    my ( $self, $verb ) = @_;
    delete $self->{verb}->{$verb}
      if defined $self->{verb};
}

sub list_verb {
    my ($self) = @_;
    return keys %{ $self->{verb} };
}

sub next_input_to {
    my ( $self, $method_ref ) = @_;
    $self->{next_input} = $method_ref
      if ( defined $method_ref );
    return $self->{next_input};
}

sub tell_next_input_method {

    my ( $self, $input ) = @_;

    # calling the method and reinitialize. Note: we have to reinit
    # before calling the code, because code can resetup this variable.
    my $code = $self->{next_input};
    undef $self->{next_input};
    my $rv = &{$code}( $self, $input );
    return $rv;
}

=pod

=head2 process

    $mailserver->process;

Start a new session.

=cut

sub process {
    my ($self) = @_;

    my $in  = $self->{in};
    my $sel = IO::Select->new;
    $sel->add($in);

    $self->banner;

    # switch to non-blocking socket to handle PIPELINING
    # ESMTP extension. See RFC 2920 for more details.
    if ( $^O eq 'MSWin32' ) {

        # win32 platforms don't support nonblocking IO
        ioctl( $in, 2147772030, 1 );
    }
    else {
        defined( $in->blocking(0) ) or die "Couldn't set nonblocking: $^E";
    }

    my $buffer = "";
    while (1) {

        # wait for data and read it
        my $rv = undef;

        if ( $sel->can_read( $self->{options}->{idle_timeout} || undef ) ) {
            if ( $^O eq 'MSWin32' ) {

                # see how much data is available to read
                my $size = pack( "L", 0 );
                ioctl( $in, 1074030207, $size );
                $size = unpack( "L", $size );

                # read the data to $buffer
                $rv = sysread( $in, $buffer, $size, length($buffer) );
            }
            else {
                $rv = sysread( $in, $buffer, 512 * 1024, length($buffer) );
            }
        }
        else {
            # timeout
            return $self->timeout;
        }

        if ( ( not defined $rv ) or ( $rv == 0 ) ) {

            # read error or connection closed
            return $self->stop_session((not defined $rv) ? ($!) : ());
        }

        # process all terminated lines
        # Note: Should accept only CRLF according to RFC. We accept
        # plain LFs anyway because its more liberal and works as well.
        my $newline_idx = rindex( $buffer, "\n" );
        if ( $newline_idx >= 0 ) {

            # one or more lines, terminated with \r?\n
            my $chunk = substr( $buffer, 0, $newline_idx + 1 );

            # remaining buffer
            $buffer = substr( $buffer, $newline_idx + 1 );

            my $rv;
            if ( defined $self->next_input_to() ) {
                $rv = $self->tell_next_input_method($chunk);
            }
            else {
                $rv = $self->{process_operation}( $self, $chunk );
            }

            # if $rv is defined, we have to close the connection
            if ( defined $rv ) {
                return $rv;
            }
        }

        # limit the size of lines to protect from excessive memory consumption
        # (RFC specifies 1000 bytes including \r\n)
        if ( length($buffer) > 1000 ) {
            $self->make_event(
                name          => 'linetobig',
                success_reply => [ 552, 'line too long' ]
            );
            return 1;
        }
    }

    return 1;
}

sub process_once {
    my ( $self, $operation ) = @_;
    if ( $self->next_input_to() ) {
        return $self->tell_next_input_method($operation);
    }
    else {
        return $self->{process_operation}( $self, $operation );
    }
}

sub process_operation {
    my ( $self, $operation ) = @_;
    my ( $verb, $params )    = $self->tokenize_command($operation);
    if ( defined $params && $params =~ /[\r\n]/ ) {

        # doesn't support grouping of operations
        $self->reply( 453,
                "Command received prior to completion of"
              . " previous command sequence" );
        return;
    }
    $self->process_command( $verb, $params );
}

sub process_command {
    my ( $self, $verb, $params ) = @_;

    if ( exists $self->{verb}->{$verb} ) {
        my $action = $self->{verb}->{$verb};
        my $rv;
        if ( ref $action eq 'CODE' ) {
            $rv = &{ $self->{verb}->{$verb} }( $self, $params );
        }
        else {
            $rv = $self->$action($params);
        }
        return $rv;
    }
    else {
        $self->reply( 500, 'Syntax error: unrecognized command' );
        return;
    }
}

sub tokenize_command {
    my ( $self, $line ) = @_;
    $line =~ s/\r?\n$//s;
    $line =~ s/^\s+|\s+$//g;
    my ( $verb, $params ) = split ' ', $line, 2;
    return ( uc($verb), $params );
}

sub reply {
    my ( $self, $code, $msg ) = @_;
    my $out = $self->{out};

    # tempo on error
    sleep $self->{options}->{error_sleep_time}
      if ( $code >= 400 && $self->{options}->{error_sleep_time} );

    # default message
    $msg = $code >= 400 ? 'Failure' : 'Ok'
      unless defined $msg;

    # handle multiple lines
    my @lines;

    if ( ref $msg ) {
        confess "bad argument" unless ref $msg eq 'ARRAY';
        @lines = @$msg;
    }
    else {
        @lines = split( /\r?\n/, $msg );
    }
    for ( my $i = 0 ; $i < @lines ; $i++ ) {

        # RFC says that all lines but the last must
        # split the code and the message with a dash (-)
        my $sep = $i == $#lines ? ' ' : '-';
        print $out "$code$sep$lines[$i]\r\n";
    }
}

sub get_hostname {
    my ($self) = @_;
    return HOSTNAME;
}

sub get_protoname {
    my ($self) = @_;
    return 'NOPROTO';
}

sub get_appname {
    my ($self) = @_;
    return 'Net::Server::Mail (Perl)';
}

###########################################################

=pod

=head2 banner

Send the introduction banner. You have to call it manually when are
using process_once() method. Don't use it with process() method.

=head1 EVENTS

=head2 banner

Append at the opening of a new connection.

Handler takes no argument.

=cut

sub banner {
    my ($self) = @_;

    unless ( defined $self->{banner_string} ) {
        my $hostname  = $self->get_hostname  || '';
        my $protoname = $self->get_protoname || '';
        my $appname   = $self->get_appname   || '';

        my $str;
        $str = $hostname . ' ' if length $hostname;
        $str .= $protoname . ' ' if length $protoname;
        $str .= $appname . ' '   if length $appname;
        $str .= 'Service ready';
        $self->{banner_string} = $str;
    }

    $self->make_event(
        name          => 'banner',
        success_reply => [ 220, $self->{banner_string} ],
        failure_reply => [ '', '' ],
    );
}

=pod

=head2 timeout

This event append where timeout is exceeded.

Handler takes no argument.

=cut

sub timeout {
    my ($self) = @_;

    $self->make_event(
        name          => 'timeout',
        success_reply => [
            421,
            $self->get_hostname
              . ' Timeout exceeded, closing transmission channel'
        ],
    );

    return 1;
}

=pod

=head2 timeout

This event append where connection is closed or an error occurs during reading from socket.

Takes the error description as an argument if an error occurred and the argument is undefined if the session was closed by peer.

    $mailserver->set_callback
    (
        'stop_session', sub
        {
            my($session, $err) = @_;
            if( defined $err )
            {
                print "Error occurred during processing: $err\n";
            }
            else
            {
                print "Session closed py peer\n";
            }
            return 1;
        }
    );

=cut

sub stop_session {
    my ($self, $err) = @_;

    $self->make_event(
        name          => 'stop_session',
        arguments     => [$err],
        no_reply      => 1,
    );

    return 1;
}

=pod

=head1 SEE ALSO

Please, see L<Net::Server::Mail::SMTP>, L<Net::Server::Mail::ESMTP>
and L<Net::Server::Mail::LMTP>.

=head1 AUTHOR

Olivier Poitrey E<lt>rs@rhapsodyk.netE<gt>

=head1 AVAILABILITY

Available on CPAN.

anonymous Git repository:

git clone git://github.com/rs/net-server-mail.git

Git repository on the web:

L<https://github.com/rs/net-server-mail>

=head1 BUGS

Please use CPAN system to report a bug (http://rt.cpan.org/).

=head1 LICENCE

This library is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.

This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
USA

=head1 COPYRIGHT

=over

=item Copyright (C) 2002 - Olivier Poitrey

=item Copyright (C) 2007-2013 - Xavier Guimard

=back

=head2 STARTTLS

=over

=item Copyright (C) 2009 - Dan Moore <dan at moore.cx>

=item Copyright (C) 2013 - Mytram <rmytram@gmail.com>

=item Copyright (C) 2013 - Xavier Guimard <x.guimard@free.fr>

=back

=head2 Contributors

=over

=item 2012 - Georg Hoesch (patch to reduce memory consumption)

=back

=cut

1;