aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Fripost/Schema/Domain.pm
blob: 993d7713080d5551e183369cff5dbb3cddfd44b9 (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
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 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 $domains = $self->ldap->search(
                      base => canonical_dn(@{$self->suffix}),
                      scope => 'one',
                      deref => 'never',
                      filter => 'objectClass=FripostVirtualDomain',
                      attrs => [ qw/fvd description fripostIsStatusActive
                                    fripostIsStatusPending/ ]
                  );
    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'
                 , ispending => defined $_->get_value('fripostIsStatusPending')
                 , 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 domain.

=cut

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

    my $domains = $self->ldap->search(
                      base => canonical_dn({fvd => $d}, @{$self->suffix}),
                      scope => 'base',
                      deref => 'never',
                      filter => 'objectClass=FripostVirtualDomain',
                      attrs => [ qw/fvd description
                                    fripostIsStatusActive
                                    fripostOptionalMaildrop
                                    fripostCanAddAlias
                                    fripostCanAddList
                                    fripostOwner
                                    fripostPostmaster/ ]
                  );
    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;
    # TODO: there is a bug with the encoding
    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 == 0) {
            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{fripostIsStatusPending} = $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->send;
        }

    };
    return $@;
}

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

    eval {
        my $dn = canonical_dn({fvd => domain_to_ascii($d)}, @{$self->suffix});
        my $domains = $self->ldap->search(
                          base => $dn,
                          scope => 'base',
                          deref => 'never',
                          filter => '(&(objectClass=FripostVirtualDomain)'.
                                      '(fripostIsStatusPending=*))',
                          attrs => [ 'fripostIsStatusPending' ]
                      );
        die $domains->error."\n" if $domains->code;

        my $domain = $domains->pop_entry;
        die "No such such domain: ‘".$d."’\n" unless defined $domain;

        die "Wrong unlock code for ‘".$d."’\n"
            unless $domain->get_value('fripostIsStatusPending') eq $code;
        # TODO: a more secure option would be to add a 'userPassword'
        # attribute to domains. We can bind as the domain to check the
        # validity of the token and add an ACL rule to give =z rights on
        # self and =0 for everyone else.

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


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