aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Fripost/Schema/Domain.pm
blob: 56e973728c2222fc086b43b4f108547bf48465a9 (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
package Fripost::Schema::Domain;

=head1 NAME

Domain.pm -

=head1 DESCRIPTION

Domain.pm abstracts the LDAP schema definition and provides methods to
add, list or delete virtual domains.

=cut

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

use parent 'Fripost::Schema';
use Net::LDAP qw/LDAP_SUCCESS LDAP_COMPARE_TRUE/;
use Fripost::Schema::Util qw/concat get_perms explode must_attrs
                             email_valid canonical_dn/;
use Net::IDN::Encode qw/domain_to_ascii domain_to_unicode
                        email_to_ascii email_to_unicode/;
use Encode;
use Net::Domain::TLD 'tld_exists';
use Net::DNS::Dig;
use Net::Whois::Parser 'parse_whois';
use String::Random;
use Template;
use MIME::Entity;


=head1 METHODS

=over 4

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

List every known (and visible) domain. The output is a array of hash
references, sorted by domain names.

=cut

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

    my $concat = $options{'-concat'};
    my $filter = '(objectClass=FripostVirtualDomain)';

    if (defined $options{'-filter'}) {
        if ($options{'-filter'} eq 'locked') {
            # Will only work if we're the owner, but otherwise we
            # shouldn't see the domain anyway.
            $filter = '(&'.$filter.'(fripostPendingToken=*))';
        }
        elsif ($options{'-filter'} eq 'nonlocked') {
            $filter = '(&'.$filter.'(!(fripostPendingToken=*)))';
        }
        else {
            die "Unknown filter: ".$options{'-filter'}."\n";
        }
    }
    else {
        my @domains0 = map {{ %$_, ispending => 1 }}
                           $self->search(%options, -filter => 'locked');
        my @domains1 = map {{ %$_, ispending => 0 }}
                           $self->search(%options, -filter => 'nonlocked');
        return sort {$a->{domain} cmp $b->{domain}} (@domains0, @domains1);
    }

    my $domains = $self->ldap->search(
                      base => canonical_dn(@{$self->suffix}),
                      scope => 'one',
                      deref => 'never',
                      filter => $filter,
                      attrs => [ qw/fvd description fripostIsStatusActive/ ]
                  );
    if ($domains->code) {
        die $options{'-die'}."\n" if defined $options{'-die'};
        die $domains->error."\n";
    }

    return map { { domain => domain_to_unicode($_->get_value('fvd'))
                 , isactive => $_->get_value('fripostIsStatusActive') eq 'TRUE'
                 , description => concat($concat, $_->get_value('description'))
                 }
               }
               $domains->sorted('fvd')
}


=item B<get> (I<domain>, I<OPTIONS>)

Returns a hash with all the (visible) attributes for the given
*non-pending* domain.

=cut

sub get {
    my $self = shift;
    my $d = domain_to_ascii(shift);
    my %options = @_;
    my $concat = $options{'-concat'};

    my $attrs = $options{'-attrs'} //
                    [ qw/fvd description
                         fripostIsStatusActive
                         fripostOptionalMaildrop
                         fripostCanAddAlias
                         fripostCanAddList
                         fripostOwner
                         fripostPostmaster/ ];

    my $domains = $self->ldap->search(
                      base => canonical_dn({fvd => $d}, @{$self->suffix}),
                      scope => 'base',
                      deref => 'never',
                      filter => '(&(objectClass=FripostVirtualDomain)
                                   (!(fripostPendingToken=*)))',
                      attrs => $attrs
                  );
    if ($domains->code) {
        die $options{'-die'}."\n" if defined $options{'-die'};
        die $domains->error."\n";
    }

    # The following is not supposed to happen.
    die "Error: Multiple matching entries found." if $domains->count > 1;
    my $domain = $domains->pop_entry;
    unless (defined $domain) {
        die $options{'-die'}."\n" if defined $options{'-die'};
        die "No such such domain: ‘$d\n";
    }

    return ( domain => domain_to_unicode($domain->get_value('fvd'))
           , isactive => $domain->get_value('fripostIsStatusActive') eq 'TRUE'
           , description => concat($concat, $domain->get_value('description'))
           , catchalls => concat($concat, map { &_email_to_unicode ($_) }
                                              $domain->get_value('fripostOptionalMaildrop'))
           , permissions => get_perms($domain, $self->whoami)
           , canAddAlias => concat($concat, map { &_email_to_unicode ($self->_dn2fvu($_)) }
                                               $domain->get_value('fripostCanAddAlias'))
           , canAddList => concat($concat, map { &_email_to_unicode ($self->_dn2fvu($_)) }
                                              $domain->get_value('fripostCanAddList'))
           )
}


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

Replace an existing domain with the given one.

=cut

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

    foreach (qw/description catchalls canAddAlias canAddList/) {
        $d->{$_} = explode ($options{'-concat'}, $d->{$_})
            if defined $d->{$_};
    }

    eval {
        &_is_valid($d);
        my $dn = canonical_dn( {fvd => $d->{domain}}, @{$self->suffix} );
        my $mesg = $self->ldap->modify( $dn,
                       replace => { fripostIsStatusActive => $d->{isactive} ?
                                        'TRUE' : 'FALSE'
                                  , description => $d->{description}
                                  , fripostOptionalMaildrop => $d->{catchalls}
                                  , fripostCanAddAlias =>
                                          [ map $self->_fvu2dn($_),
                                                @{$d->{canAddAlias}} ]
                                  , fripostCanAddList =>
                                          [ map $self->_fvu2dn($_),
                                                @{$d->{canAddList}} ]
                   } );
        die $mesg->error."\n" if $mesg->code;
    };
    return $@;
}


sub list_postmasters {
    my $self = shift;
    my $hostname = shift;
    my @postmasters;

    my $tld = domain_to_ascii($hostname);
    my $domain;
    until ( tld_exists($tld) ) {
        die "‘".$hostname."’ has an Invalid TLD.\n" unless $tld =~ /\./;
        $domain = $tld;

        my %mx = Net::DNS::Dig->new()->for( $domain, 'MX' )->rdata;
        push @postmasters, 'postmaster@'.$domain  # RFC 822, appendix C.6
        if grep {!/\bfripost\.org$/} (values %mx);

        $tld =~ s/^[^\.]*\.//;
    }

    my $info = parse_whois( domain => $domain );
    die "Cannot WHOIS ‘".$domain."’.\n" unless defined $info;
    if (defined $info) {
        push @postmasters, @{$info->{emails}};
    }

    my %hash;
    $hash{$_} = 1 for grep {email_valid($_ // '', -nodie => 1 )}
                           @postmasters;
    sort keys %hash;
}

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

    foreach (qw/description catchalls canAddAlias canAddList/) {
        $d->{$_} = explode ($options{'-concat'}, $d->{$_})
            if defined $d->{$_};
    }

    eval {
        my $domain = $d->{domain};
        Encode::_utf8_on($domain);
        &_is_valid($d);

        my $dn = canonical_dn( {fvd => $d->{domain}}, @{$self->suffix} );

        my $mesg = $self->ldap->search(
                       base => $dn,
                       scope => 'base',
                       deref => 'never',
                       filter => 'objectClass=FripostVirtualDomain',
                       attrs => [] );
        if ($mesg->code == LDAP_SUCCESS) {
            die "Domain ‘".$domain."’ already exists.\n";
        }
        elsif ($mesg->code != 32) {
            die $mesg->error."\n";
        }

        return if $options{'-dry-run'};

        my %attrs = ( objectClass => 'FripostVirtualDomain'
                    , fripostIsStatusActive => $d->{isactive} ?
                        'TRUE' : 'FALSE'
                    );
        $attrs{description} = $d->{description}
            if defined $d->{description} and @{$d->{description}};
        $attrs{fripostOptionalMaildrop} = $d->{catchalls}
            if defined $d->{catchalls} and @{$d->{catchalls}};

        if (defined $d->{owner}) {
            $attrs{fripostOwner} = $self->_fvu2dn($d->{owner})
              if $d->{owner} ne '';
        }
        else {
            $attrs{fripostOwner} = $self->whoami;
        }

        my $token;
        if (defined $d->{send_token_to}) {
            $token = String::Random::->new->randregex('\w{32}');
            $attrs{fripostPendingToken} = $token
        }

        $mesg = $self->ldap->add( $dn, attrs => [ %attrs ] );
        die $mesg->error."\n" if $mesg->code;


        if (defined $d->{send_token_to}) {
            my $tt = Template->new({
              INCLUDE_PATH => './templates',  # TODO: use a config option
              INTERPOLATE  => 1,
            }) or die $Template::ERROR."\n";

            my $data;
            my $vars = { domain => $domain, token => $token };
            $vars->{unlockurl} = $options{'-domainurl'}.'?unlock='.$token
                if defined $options{'-domainurl'};
            $tt->process( 'new-domain.tt', $vars, \$data)
                or die $tt->error."\n";

            my $mail = MIME::Entity::->build(
              From     => 'Fripost Admin Panel <AdminWebPanel@fripost.org>',
              To       => $d->{send_token_to},
              Subject  => "Your new domain ".$d->{domain},
              Encoding => 'quoted-printable',
              Charset  => 'utf-8',
              Data     => $data
            );
            $mail->sign( Signature => 'The Fripost administration team.');
            $mail->send;
        }

    };
    return $@;
}

sub unlock {
    my $self = shift;
    my $d = shift;
    my $token = shift;

    my $dn = canonical_dn({fvd => domain_to_ascii($d)}, @{$self->suffix});
    my $mesg = $self->ldap->compare( $dn
                                   , attr => 'fripostPendingToken'
                                   , value => $token );
    die "Wrong unlock code for ‘".$d."’\n"
        unless $mesg->code eq LDAP_COMPARE_TRUE;

    $mesg = $self->ldap->modify( $dn, delete => 'fripostPendingToken' );
    die $mesg->error."\n" if $mesg->code;
}


=back

=head1 GLOBAL OPTIONS

If the B<-concat> option is present, it will intersperse multi-valued
attributes. Otherwise, an array reference containing every values will
be returned for these attributes.

The B<-die> option, if present, overides LDAP croaks and errors.

=cut



# Ensure that the given domain is valid.
sub _is_valid {
    my $d = shift;
    must_attrs( $d, qw/domain isactive/ );
    $d->{domain} = email_valid( $d->{domain}, -prefix => 'fake@',
                                              -error => 'Invalid domain',
                                              -exact => 1 );
    $d->{catchalls} = [ map { email_valid($_, -prefix => 'fake') }
                            @{$d->{catchalls}} ];
    $d->{canAddAlias} = [ map { email_valid($_, -prefix => 'fake') }
                                 @{$d->{canAddAlias}} ];
    $d->{canAddList} = [ map { email_valid($_, -prefix => 'fake') }
                                @{$d->{canAddList}} ];

    $d->{send_token_to} = email_valid( $d->{send_token_to} )
                              if defined $d->{send_token_to};
}


# A variant of email_to_unicode that also takes care of domain aliases.
sub _email_to_unicode {
    my $email = shift;
    return '@'.domain_to_unicode($email) if $email =~ s/^\@//;
    return email_to_unicode($email);
}


=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__