aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Fripost/Schema/Local.pm
blob: 8a7b87092f7759c3e94e11f0084c411b2717893a (plain)
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
package Fripost::Schema::Local;

=head1 NAME

Local.pm - Localpart related method for the Fripost Schema

=head1 DESCRIPTION

This module abstracts the LDAP schema definition and provides methods to
add, list or delete virtual users, aliases or lists.

=cut

use 5.010_000;
use strict;
use warnings;
use utf8;

use parent 'Fripost::Schema';
use Fripost::Schema::Mail;
use Fripost::Schema::Util qw/split_addr canonical_dn
                             ldap_error dn2mail softdie email_valid
                             ldap_assert_absent escape_filter_nostar/;
use Net::IDN::Encode qw/email_to_ascii email_to_unicode/;
use Net::LDAP::Util 'escape_filter_value';


=head1 REPRESENTATION

Virtual users, aliases and lists are imported and exported as hash
references, with the following keys:

=over 4

=item B<name>

A UTF-8 string representing the (internationalized) e-mail address for
the user, alias or list.

=item B<type> => user|alias|list

The type of the entry.

=item B<isActive> => 0|1

Whether or not the entry is active.

=item B<description>

An array reference containing UTF-8 strings describing the entry.

=item B<isPending> => 0|1

(List only) Whether or not the entry is pending. New lists are always
marked as pending, and are unlocked on the list manager side.

=item B<quota>

(User only) A string e.g., C<100 MB> representing the current quota on
the user's mailboxes.

=item B<password>

(User and list only) The user or list administrator password. It is
never given back by the server (actually noone has read access on that
attribute), hence only makes sense upon creation. In users entries,
I<password> can be hashed on the client side when prefixed with
B<{SHA}>, B<{SSHA}>, B<{MD5}>, B<{SMD5}>, B<{CRYPT}> or B<{CLEARTEXT}>.
(Otherwise the password will be automatically salted and SHA-1 hashed.)

=item B<owner>

(Alias and list only) An optional array reference containing the
(internationalized) e-mails addresses of the entry owners.

=item B<forward>

(User only) An optional array reference containing (internationalized)
e-mails addresses that will also receive every single message sent to
that user.

=item B<destination>

(Alias only) An array reference containing (internationalized) e-mails
addresses that will receive messages sent to that alias.

=item B<transport> mailman|schleuder

(List only) The list manager associated with list entries.


=head1 METHODS

=over 4

=item B<search> (I<name>, I<OPTIONS>)

Search for I<name>, or list all the known (and visible) users, aliases
and lists when I<name> is not defined. If I<name> does not contain a '@'
symbol, it is interpreted as a domain name, which limits the scope of
that search.  In list context, return a list of entries represented as
hash references, as explained above. In scalar context, only the first
entry found is returned. In void context, no attributes are returned
from the LDAP server, but it may nevertheless be useful, to ensure that
the result set is not empty for instance.

The following options are considered:

=over 4

=item B<-no-star-escape> => 0|1

By default, the local and domain parts of I<name> - when defined - are
safely escaped before insertion into the LDAP DN and filter. When set,
this flag disables escaping of wildcards (*) in I<name>. It is useful if
I<name> contains wildcards for instance. Note that in case the domain
part contains wildcard, this method will query the LDAP server for every
single matching domain.

=item B<-filter> => locked|unlocked

Limit the search scope to pending / non-pending entries only.

=item B<-type> => user|alias|list

Limit the search scope to the given entry type.

=item B<-keys>

An array reference containing the attributes that are to be retrived
from the LDAP server. Note that Access Control List may prevent the
current user to read or even search anything, though. The default is to
retrieve every visible attribute, unless in void context where B<-keys>
is set to [] that is, no attribute is sent back to the client.

=item B<-count> => 0|1

Return the number of entries in the result set. When set, the B<-keys>
option is bypassed not to ask any attribute from the server.

=item B<-sort> => 0|1

In list context, sort the results per localpart.

=back

Errors can be caught with options B<-die> and B<-error>; See
B<Fripost::Schema::Util> for details.

=cut

sub search {
    my $self = shift;
    my ($localname, $domainname) = split_addr(shift);
    my %options = @_;

    # Nothing to do after an error.
    return if $options{'-error'} && ${$options{'-error'}};

    my @filters;
    if (defined $options{'-type'}) {
        # Limit the scope to the given type.
        if ($options{'-type'} eq 'user') {
            push @filters, 'objectClass=FripostVirtualUser';
        }
        elsif ($options{'-type'} eq 'alias') {
            push @filters, 'objectClass=FripostVirtualAlias';
        }
        elsif ($options{'-type'} eq 'list') {
            push @filters, 'objectClass=FripostVirtualList';
        }
    }
    else {
        push @filters, '(|(objectClass=FripostVirtualUser)'.
                         '(objectClass=FripostVirtualAlias)'.
                         '(objectClass=FripostVirtualList))';
    }

    my @domainnames;
    if ($domainname) {
        if ($options{'-no-star-escape'}) {
            # If the domain part contains a wildcard, we have to query
            # the LDAP server to list the matching domains.
            my %opts = ( '-no-star-escape' => 1, -keys => [ 'name' ]) ;
            $opts{'-filter'} = 'unlocked';
            foreach (qw/-filter -error -die/) {
                $opts{$_} = $options{$_} if $options{$_};
            }
            push @domainnames, map {$_->{name}}
                                   $self->domain->search($domainname, %opts);
        }
        else {
            # Otherwise, a single query is enough.
            $domainname = Net::LDAP::Util::escape_dn_value($domainname);
            push @domainnames, $domainname;
        }
    }

    if ($localname) {
        $localname = $options{'-no-star-escape'} ?
                         escape_filter_nostar $localname :
                         Net::LDAP::Util::escape_filter_value $localname;
        push @filters, 'fvl='.$localname;
    }

    if (defined $options{'-filter'}) {
        push @filters, 'objectClass=FripostPendingEntry'
            if $options{'-filter'} eq 'locked';
        push @filters, '!(objectClass=FripostPendingEntry)'
            if $options{'-filter'} eq 'unlocked';
    }

    my $attrs = [];
    if (not (defined wantarray)) {
        # In void context, we are only interested in whether or not the
        # result set is empty.
        $attrs = [ '1.1' ];
    }
    elsif (defined $options{'-keys'}) {
        $attrs = @{$options{'-keys'}} ? [ &_keys_to_attrs(@{$options{'-keys'}}) ]
                                      : [ '1.1' ];
    }

    my $filter = Fripost::Schema::Util::ldap_and_filter(@filters);
    my $count = 0;
    my @resultset;
    foreach my $domainname (@domainnames) {
        # We query the server for each matching domain.
        my $locals = $self->ldap->search( base => $self->mail2dn($domainname)
                                        , scope => 'one'
                                        , deref => 'never'
                                        , filter => $filter
                                        , attrs => $attrs
                                        );
        ldap_error($locals, %options) // return;
        next unless defined wantarray; # We'll drop the result anyway

        if ($options{'-count'}) {
            $count += $locals->count;
        }
        elsif (wantarray) {
            push @resultset,
                 &_entries_to_locals( $domainname, $options{'-keys'},
                                      $locals->entries );
        }
        else {
            # In scalar context, we stop here if we got a match.
            return &_entries_to_locals( $domainname, $options{'-keys'},
                                        $locals->pop_entry )
                       if $locals->count;
        }
    }

    return $count if $options{'-count'};
    # In list context, we return the whole result set, maybe sorted.
    $options{'-sort'} ? sort { $a->{name} cmp $b->{name} } @resultset
                      : @resultset;
}


# Map a list of LDAP::Entry object into our public representation of
# users, aliases and lists.
sub _entries_to_locals {
    my $domainname = shift;
    my $keys = shift // [];

    my @locals;
    foreach my $entry (@_) {

        # Ignore bogus entries.
        return unless defined $entry;
        my %local;

        foreach my $attr ($entry->attributes) {
            my $val = $entry->get_value($attr, asref => 1);
            if ($attr eq 'fvl') {
                $local{name} = email_to_unicode($val->[0].'@'.$domainname)
                    if not @$keys or grep { $_ eq 'name' } @$keys;
            }
            elsif ($attr eq 'fripostIsStatusActive') {
                $local{isActive} = $val->[0] eq 'TRUE'
                    if not @$keys or grep { $_ eq 'isActive' } @$keys;
            }
            elsif ($attr eq 'objectClass') {
                if (grep { lc $_ eq lc 'FripostVirtualUser' } @$val) {
                    $local{type} = 'user';
                }
                elsif (grep { lc $_ eq lc 'FripostVirtualAlias' } @$val) {
                    $local{type} = 'alias';
                }
                elsif (grep { lc $_ eq lc 'FripostVirtualList' } @$val) {
                    $local{type} = 'list';
                }
                $local{isPending} = scalar (grep { lc $_ eq lc 'FripostPendingEntry' }
                                                  @$val )
                    if not @$keys or grep { $_ eq 'isPending' } @$keys;
            }
            elsif ($attr eq 'description') {
               $local{description} = [ map { Encode::_utf8_on($_); $_ } @$val ]
                    if not @$keys or grep { $_ eq 'description' } @$keys;
            }
            elsif ($attr eq 'fripostUserQuota') {
                $local{quota} = $val->[0]
                    if not @$keys or grep { $_ eq 'quota' } @$keys;
            }
            elsif ($attr eq 'fripostOwner') {
                $local{owner} = [ map { dn2mail($_) } @$val ]
                    if not @$keys or grep { $_ eq 'owner' } @$keys;
            }
            elsif ($attr eq 'fripostOptionalMaildrop') {
                $local{forward} = [ map { email_to_unicode($_) } @$val ]
                    if not @$keys or grep { $_ eq 'forward' } @$keys;
            }
            elsif ($attr eq 'fripostMaildrop') {
                $local{destination} = [ map { email_to_unicode($_) } @$val ]
                    if not @$keys or grep { $_ eq 'destination' } @$keys;
            }
            elsif ($attr eq 'fripostListManager') {
                $local{transport} = $val->[0]
                    if not @$keys or grep { $_ eq 'transport' } @$keys;
            }
            else {
                die "Missing translation for local attribute ‘".$attr."’";
            }
        }

        # Stop after the first processed domain in scalar mode.
        return \%local unless wantarray;
        push @locals, \%local;
    }
    return @locals;
}

# Map our domain keys into the LDAP attribute(s) that are required to
# fetch this information.
sub _keys_to_attrs {
    my %map = ( name => 'fvl'
              , type => 'objectClass'
              , isActive => 'fripostIsStatusActive'
              , description => 'description'
              , isPending => 'objectClass'
              , quota => 'fripostUserQuota'
              , owner => 'fripostOwner'
              , forward => 'fripostOptionalMaildrop'
              , destination => 'fripostMaildrop'
              , transport => 'fripostListManager'
              );
    my %attrs;
    foreach my $k (@_) {
        die "Missing translation for key ‘".$k."’"
            unless exists $map{$k};
        if (ref $map{$k} eq 'ARRAY') {
            $attrs{$_} = 1 for @{$map{$k}};
        }
        else {
            $attrs{$map{$k}} = 1;
        }
    }
    return keys %attrs;
}


our %list_commands = ( mailman => [ qw/admin bounces confirm join leave
                                       owner request subscribe unsubscribe/ ]
                     , schleuder => [ qw/bounce sendkey/ ]
                     );

sub add {
    my $self = shift;
    my $local = shift;
    my %options = @_;

    # Nothing to do after an error.
    return if $options{'-error'} && ${$options{'-error'}};

    my $name = $local->{name};
    # Check validity.
    &_assert_valid($local, %options) // return;
    my ($localname, $domainname) = split_addr($name);

    my $exists;
    my $t = $local->{type};
    if ($options{'-dry-run'} or $options{'-append'}) {
        # Search for an existing entry with the same name. We can't
        # use our previously defined method here, since the current user
        # may not have read access to the entry. There is a race
        # condition since someone could modify the directory between
        # this check and the actual insertion, but then the insertion
        # would fail.
        $exists = ldap_assert_absent( $self, $name, undef, %options ) // return;

        if ($t eq 'list') {
            # Ensure that all commands are available.
            foreach (@{$list_commands{$local->{transport}}}) {
                 my $name = $localname.'-'.$_.'@'.$domainname;
                 ldap_assert_absent( $self, $name, undef, %options ) // return;
            }
        }
        return 1 if $options{'-dry-run'};
    }

    # Convert the domain into a LDAP entry, and remove keys to empty values.
    my %attrs = $self->_local_to_entry (%$local);
    Fripost::Schema::Util::ldap_clean_entry( \%attrs );

    my $mesg;
    my $dn = $self->mail2dn( $local->{name} );
    if ($options{'-append'} and $exists) {
        # Replace single valued attributes; Add other attributes.
        my %unique;
        foreach (qw/fripostIsStatusActive userPassword fripostUserQuota/) {
            $unique{$_} = delete $attrs{$_} if exists $attrs{$_};
        }
        $mesg = $self->ldap->modify( $dn, replace => \%unique, add => \%attrs );
    }
    else {
        # The default owner is the current user.
        $attrs{fripostOwner} //= [ $self->whoami ] unless $t eq 'user';
        my $die = exists $options{'-die'};
        $options{'-die'} = { Net::LDAP::Constant::LDAP_ALREADY_EXISTS =>
                                "‘".$name."’ exists"
                           , Net::LDAP::Constant::LDAP_SUCCESS => 0 }
            unless $die;

        if ($t eq 'list') {
            # Lists need special care since we have to create the
            # commands as well, and we need to communicate with the list
            # manager.
            my $pw = delete $attrs{userPassword};
            $attrs{objectClass} = [ qw/FripostVirtualList FripostPendingEntry/ ];
            $attrs{fripostLocalAlias} = &_mkLocalAlias($name);

            my @done;
            my $res = $self->ldap->add( $dn, attrs => [ %attrs ] );
            push @done, $dn unless $res->code;

            foreach (@{$list_commands{$local->{transport}}}) {
                # Create the commands; Stop if something goes wrong
                last if $res->code;
                my $name = $localname.'-'.$_.'@'.$domainname;
                $options{'-die'} = { Net::LDAP::Constant::LDAP_ALREADY_EXISTS =>
                                        "‘".$name."’ exists"
                                   , Net::LDAP::Constant::LDAP_SUCCESS => 0 }
                    unless $die;
                my %attrs = ( objectClass => [ qw/FripostVirtualListCommand
                                                  FripostPendingEntry/ ]
                            , fripostLocalAlias => &_mkLocalAlias($name)
                            );
                my $dn = $self->mail2dn( $name );
                $res = $self->ldap->add( $dn, attrs => [ %attrs ] );
                push @done, $dn unless $res->code;
            }
            $mesg = $res;
            if ($mesg->code) {
                # Something went wrong. We try to clean up after us, and
                # delete the bogus entries we created.
                # It's not too bad if it doesn't work out, because
                # it'll be cleaned by our service hopefully.
                $self->ldap->delete($_) for @done;
                ldap_error($mesg, %options);
                return;
            }

#            my $member = dn2mail ($self->whoami);
#            my $to = email_valid( 'mklist+'.$local->{transport}.'@fripost.org' );
#            Fripost::Schema::Mail::->new(
#                From    => 'Fripost Admin Panel <AdminWebPanel@fripost.org>',
#                To      => $to,
#                Subject => "New ".$local->{transport}." list",
#                Data    => [ map { $_ . "\n"} ($local->{name}, $member, $pw) ]
#            )->send(-sign => 1, -encrypt => 1);
        }
        else {
            $attrs{objectClass} =  $t eq 'user' ? 'FripostVirtualUser' :
                                   $t eq 'alias'? 'FripostVirtualAlias' :
                                   '';
            $mesg = $self->ldap->add( $dn, attrs => [ %attrs ] );
        }
    }

    ldap_error($mesg, %options) // return;
    1;
}


# Convert our representation of local entries into a hash which keys are
# LDAP attributes.
sub _local_to_entry {
    my $self = shift;
    my %local = @_;
    my %entry;

    foreach my $key (keys %local) {
        if ($key eq 'name') {
            # Its value is forced by the DN.
        }
        elsif ($key eq 'type') {
            # We fix that one later.
        }
        elsif ($key eq 'isActive') {
            $entry{fripostIsStatusActive} = $local{isActive} ? 'TRUE' : 'FALSE';
        }
        elsif ($key eq 'description') {
            $entry{description} = $local{description};
        }
        elsif ($key eq 'quota') {
            $entry{fripostUserQuota} = $local{quota};
        }
        elsif ($key eq 'owner') {
            $entry{fripostOwner} =
                [ map { $self->mail2dn($_) } @{$local{owner}} ];
        }
        elsif ($key eq 'forward') {
            $entry{fripostOptionalMaildrop} = $local{forward};
        }
        elsif ($key eq 'destination') {
            $entry{fripostMaildrop} = $local{destination};
        }
        elsif ($key eq 'transport') {
            $entry{fripostListManager} = $local{transport};
        }
        elsif ($key eq 'password') {
            $entry{userPassword} = $local{password};
        }
        else {
            die "Missing translation for key ‘".$key."’";
        }
    }
    return %entry;
}


# Create a local alias
sub _mkLocalAlias {
    my $name = email_to_ascii(shift);
    $name =~ /^(.+)@([^\@]+)/ or return;
    return $1.'#'.$2;
}


=item B<replace> (I<entry>, I<OPTIONS>)

Replace the existing entry (user, alias, or list) with the given one.

=over 4

=item B<-dry-run> => 0|1

Merely simulate the replacement. I<entry> is still checked to be a valid
entry in the above representation.

=back

Errors can be caught with options B<-die> and B<-error>; See
B<Fripost::Schema::Util> for details.

=cut

sub replace {
    my $self = shift;
    my $local = shift;
    my %options = @_;

    # Nothing to do after an error.
    return if $options{'-error'} && ${$options{'-error'}};

    # Check validity.
    &_assert_valid($local, %options, -replace => 1) // return;
    return 1 if $options{'-dry-run'};

    my %entry = $self->_local_to_entry (%$local);
    my $mesg = $self->ldap->modify( $self->mail2dn($local->{name})
                                  , replace => \%entry );
    ldap_error($mesg, %options);
}



=item B<delete> (I<name>, I<OPTIONS>)

Delete the given user, alias or list I<name>.

Errors can be caught with options B<-die> and B<-error>; See
B<Fripost::Schema::Util> for details.

=cut

sub delete {
    my $self = shift;
    my $name = shift;
    my %options = @_;

    # Nothing to do after an error.
    return if $options{'-error'} && ${$options{'-error'}};

    my $mesg = $self->ldap->delete( $self->mail2dn($name) );
    ldap_error($mesg, %options);
}



# Ensure that the given entry is valid.
sub _assert_valid {
    my $l = shift;
    my %options = @_;
    eval {
        die "Unspecified type\n" unless defined $l->{type};
        die "Unknown type ‘".$l->{type}."’\n"
            unless grep { $l->{type} eq $_ } qw/user alias list/;

        die "Unspecified name\n" unless $l->{name} =~ /^.+\@[^\@]+$/;
        my ($u, $d) = split_addr($l->{name}, -encode => 'ascii');
        return unless $u and $d;
        my $del = $options{recipient_delimiter} // '+';
        die "Recipient delimiter ‘".$del."’ is not allowed in locaparts\n"
                if $u =~ /\Q$del\E/;
        $l->{name} = email_valid( $l->{name}, -exact => 1 );

        unless ($options{'-append'} or $options{'-replace'}) {
            my @must;
            push @must, $l->{type} eq 'user'  ? 'password' :
                        # TODO: ^ match 'quota' against the Dovecot specifications?
                        $l->{type} eq 'alias' ? 'destination' :
                        $l->{type} eq 'list'  ? qw/transport password/ :
                        ();
            Fripost::Schema::Util::mandatory_attrs( $l, @must );
        }

        if ($l->{type} eq 'user') {
            $l->{forward} = [ map { email_valid($_) } @{$l->{forward}} ]
                if $l->{forward};
        }
        elsif ($l->{type} eq 'alias') {
            $l->{destination} = [ map { email_valid($_) } @{$l->{destination}} ]
                if $l->{destination};
        }
        elsif ($l->{type} eq 'list') {
            # The list manager won't allow arbitrary names.
            die "Invalid list name: ‘".$l->{name}."’\n"
                unless $u =~ /^[[:alnum:]_=\+\-\.]+$/;

            # The list manager has to distinguish posts to commands.
            die "Invalid list name: ‘".$l->{name}."’\n"
                if defined $l->{transport} and
                   grep {$u =~ /-\Q$_\E$/} @{$list_commands{$l->{transport}}};

            die "Invalid transport: ‘".$l->{transport}."’\n"
                if defined $l->{transport} and
                   not grep { $l->{transport} eq $_ } (keys %list_commands);

            $l->{transport} //= 'mailman'
                unless $options{'-append'} or $options{'-replace'};
        }
        $l->{isActive} //= 1 unless $options{'-append'} or $options{'-replace'};
    };
    softdie ($@, %options);
}




=head1 AUTHOR

Guilhem Moulin C<< <guilhem at fripost.org> >>

=head1 COPYRIGHT

Copyright 2012,2013 Guilhem Moulin.

=head1 LICENSE

This program is free software; you can redistribute it and/or modify it
under the same terms as perl itself.

=cut

1;

__END__