dtrt when deleting accouts wrt forwards, catchalls & other references to
[freeside.git] / FS / FS / svc_domain.pm
1 package FS::svc_domain;
2
3 use strict;
4 use vars qw( @ISA $whois_hack $conf $smtpmachine
5   $tech_contact $from $to @nameservers @nameserver_ips @template
6   @mxmachines @nsmachines $soadefaultttl $soaemail $soaexpire $soamachine
7   $soarefresh $soaretry
8 );
9 use Carp;
10 use Mail::Internet;
11 use Mail::Header;
12 use Date::Format;
13 use Net::Whois 1.0;
14 use Net::SSH qw(ssh);
15 use FS::Record qw(fields qsearch qsearchs dbh);
16 use FS::Conf;
17 use FS::svc_Common;
18 use FS::cust_svc;
19 use FS::svc_acct;
20 use FS::cust_pkg;
21 use FS::cust_main;
22 use FS::domain_record;
23
24 @ISA = qw( FS::svc_Common );
25
26 #ask FS::UID to run this stuff for us later
27 $FS::UID::callback{'FS::domain'} = sub { 
28   $conf = new FS::Conf;
29
30   $smtpmachine = $conf->config('smtpmachine');
31
32   my($internic)="/registries/internic";
33   $tech_contact = $conf->config("$internic/tech_contact");
34   $from = $conf->config("$internic/from");
35   $to = $conf->config("$internic/to");
36   my(@ns) = $conf->config("$internic/nameservers");
37   @nameservers=map {
38     /^\s*\d+\.\d+\.\d+\.\d+\s+([^\s]+)\s*$/
39       or die "Illegal line in $internic/nameservers";
40     $1;
41   } @ns;
42   @nameserver_ips=map {
43     /^\s*(\d+\.\d+\.\d+\.\d+)\s+([^\s]+)\s*$/
44       or die "Illegal line in $internic/nameservers!";
45     $1;
46   } @ns;
47   @template = map { $_. "\n" } $conf->config("$internic/template");
48
49   @mxmachines    = $conf->config('mxmachines');
50   @nsmachines    = $conf->config('nsmachines');
51   $soadefaultttl = $conf->config('soadefaultttl');
52   $soaemail      = $conf->config('soaemail');
53   $soaexpire     = $conf->config('soaexpire');
54   $soamachine    = $conf->config('soamachine');
55   $soarefresh    = $conf->config('soarefresh');
56   $soaretry      = $conf->config('soaretry');
57
58   $qshellmachine = $conf->exists('qmailmachines')
59                    ? $conf->config('shellmachine')
60                    : '';
61 };
62
63 =head1 NAME
64
65 FS::svc_domain - Object methods for svc_domain records
66
67 =head1 SYNOPSIS
68
69   use FS::svc_domain;
70
71   $record = new FS::svc_domain \%hash;
72   $record = new FS::svc_domain { 'column' => 'value' };
73
74   $error = $record->insert;
75
76   $error = $new_record->replace($old_record);
77
78   $error = $record->delete;
79
80   $error = $record->check;
81
82   $error = $record->suspend;
83
84   $error = $record->unsuspend;
85
86   $error = $record->cancel;
87
88 =head1 DESCRIPTION
89
90 An FS::svc_domain object represents a domain.  FS::svc_domain inherits from
91 FS::svc_Common.  The following fields are currently supported:
92
93 =over 4
94
95 =item svcnum - primary key (assigned automatically for new accounts)
96
97 =item domain
98
99 =item catchall - optional svcnum of an svc_acct record, designating an email catchall account.
100
101 =back
102
103 =head1 METHODS
104
105 =over 4
106
107 =item new HASHREF
108
109 Creates a new domain.  To add the domain to the database, see L<"insert">.
110
111 =cut
112
113 sub table { 'svc_domain'; }
114
115 =item insert
116
117 Adds this domain to the database.  If there is an error, returns the error,
118 otherwise returns false.
119
120 The additional fields I<pkgnum> and I<svcpart> (see L<FS::cust_svc>) should be 
121 defined.  An FS::cust_svc record will be created and inserted.
122
123 The additional field I<action> should be set to I<N> for new domains or I<M>
124 for transfers.
125
126 A registration or transfer email will be submitted unless
127 $FS::svc_domain::whois_hack is true.
128
129 The additional field I<email> can be used to manually set the admin contact
130 email address on this email.  Otherwise, the svc_acct records for this package 
131 (see L<FS::cust_pkg>) are searched.  If there is exactly one svc_acct record
132 in the same package, it is automatically used.  Otherwise an error is returned.
133
134 If any I<soamachine> configuration file exists, an SOA record is added to
135 the domain_record table (see <FS::domain_record>).
136
137 If any machines are defined in the I<nsmachines> configuration file, NS
138 records are added to the domain_record table (see L<FS::domain_record>).
139
140 If any machines are defined in the I<mxmachines> configuration file, MX
141 records are added to the domain_record table (see L<FS::domain_record>).
142
143 If a machine is defined in the I<shellmachine> configuration value, the
144 I<qmailmachines> configuration file exists, and the I<catchall> field points
145 to an an account with a home directory (see L<FS::svc_acct>), the command:
146
147   [ -e $dir/.qmail-$qdomain-defualt ] || {
148     touch $dir/.qmail-$qdomain-default;
149     chown $uid:$gid $dir/.qmail-$qdomain-default;
150   }
151
152 is executed on shellmachine via ssh (see L<dot-qmail/"EXTENSION ADDRESSES">).
153 This behaviour can be supressed by setting $FS::svc_domain::nossh_hack true.
154
155 a machine is defined
156 in the 
157
158 =cut
159
160 sub insert {
161   my $self = shift;
162   my $error;
163
164   local $SIG{HUP} = 'IGNORE';
165   local $SIG{INT} = 'IGNORE';
166   local $SIG{QUIT} = 'IGNORE';
167   local $SIG{TERM} = 'IGNORE';
168   local $SIG{TSTP} = 'IGNORE';
169   local $SIG{PIPE} = 'IGNORE';
170
171   my $oldAutoCommit = $FS::UID::AutoCommit;
172   local $FS::UID::AutoCommit = 0;
173   my $dbh = dbh;
174
175   $error = $self->check;
176   return $error if $error;
177
178   return "Domain in use (here)"
179     if qsearchs( 'svc_domain', { 'domain' => $self->domain } );
180
181   my $whois = $self->whois;
182   if ( $self->action eq "N" && ! $whois_hack && $whois ) {
183     $dbh->rollback if $oldAutoCommit;
184     return "Domain in use (see whois)";
185   }
186   if ( $self->action eq "M" && ! $whois ) {
187     $dbh->rollback if $oldAutoCommit;
188     return "Domain not found (see whois)";
189   }
190
191   $error = $self->SUPER::insert;
192   if ( $error ) {
193     $dbh->rollback if $oldAutoCommit;
194     return $error;
195   }
196
197   $self->submit_internic unless $whois_hack;
198
199   if ( $soamachine ) {
200     my $soa = new FS::domain_record {
201       'svcnum'  => $self->svcnum,
202       'reczone' => '@',
203       'recaf'   => 'IN',
204       'rectype' => 'SOA',
205       'recdata' => "$soamachine $soaemail ( ". time2str("%Y%m%d", time). "00 ".
206                    "$soarefresh $soaretry $soaexpire $soadefaultttl )"
207     };
208     $error = $soa->insert;
209     if ( $error ) {
210       $dbh->rollback if $oldAutoCommit;
211       return "couldn't insert SOA record for new domain: $error";
212     }
213
214     foreach my $nsmachine ( @nsmachines ) {
215       my $ns = new FS::domain_record {
216         'svcnum'  => $self->svcnum,
217         'reczone' => '@',
218         'recaf'   => 'IN',
219         'rectype' => 'NS',
220         'recdata' => $nsmachine,
221       };
222       my $error = $ns->insert;
223       if ( $error ) {
224         $dbh->rollback if $oldAutoCommit;
225         return "couldn't insert NS record for new domain: $error";
226       }
227     }
228
229     foreach my $mxmachine ( @mxmachines ) {
230       my $mx = new FS::domain_record {
231         'svcnum'  => $self->svcnum,
232         'reczone' => '@',
233         'recaf'   => 'IN',
234         'rectype' => 'MX',
235         'recdata' => $mxmachine,
236       };
237       my $error = $mx->insert;
238       if ( $error ) {
239         $dbh->rollback if $oldAutoCommit;
240         return "couldn't insert MX record for new domain: $error";
241       }
242     }
243
244   }
245
246   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
247
248   if ( $qshellmachine && $self->catchall && ! $nossh_hack ) {
249     my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $self->catchall } )
250       or warn "WARNING: inserted unknown catchall: ". $self->catchall;
251     if ( $svc_acct && $svc_acct->dir ) {
252       my $qdomain = $self->domain;
253       $qdomain =~ s/\./:/g; #see manpage for 'dot-qmail': EXTENSION ADDRESSES
254       my ( $uid, $gid, $dir ) = (
255         $svc_acct->uid,
256         $svc_acct->gid,
257         $svc_acct->dir,
258       );
259       ssh("root\@$qshellmachine", "[ -e $dir/.qmail-$qdomain-default ] || { touch $dir/.qmail-$qdomain-default; chown $uid:$gid $dir/.qmail-$qdomain-default; }");
260     }
261   }
262
263   ''; #no error
264 }
265
266 =item delete
267
268 Deletes this domain from the database.  If there is an error, returns the
269 error, otherwise returns false.
270
271 The corresponding FS::cust_svc record will be deleted as well.
272
273 =cut
274
275 sub delete {
276   my $self = shift;
277
278   return "Can't delete a domain which has accounts!"
279     if qsearch( 'svc_acct', { 'domsvc' => $self->svcnum } );
280
281   return "Can't delete a domain with (svc_acct_sm) mail aliases!"
282     if qsearch('svc_acct_sm', { 'domsvc' => $self->svcnum } );
283
284   return "Can't delete a domain with (domain_record) zone entries!"
285     if qsearch('domain_record', { 'svcnum' => $self->svcnum } );
286
287   $self->SUPER::delete;
288 }
289
290 =item replace OLD_RECORD
291
292 Replaces OLD_RECORD with this one in the database.  If there is an error,
293 returns the error, otherwise returns false.
294
295 =cut
296
297 sub replace {
298   my ( $new, $old ) = ( shift, shift );
299   my $error;
300
301   return "Can't change domain - reorder."
302     if $old->getfield('domain') ne $new->getfield('domain'); 
303
304   $new->SUPER::replace($old);
305
306 }
307
308 =item suspend
309
310 Just returns false (no error) for now.
311
312 Called by the suspend method of FS::cust_pkg (see L<FS::cust_pkg>).
313
314 =item unsuspend
315
316 Just returns false (no error) for now.
317
318 Called by the unsuspend method of FS::cust_pkg (see L<FS::cust_pkg>).
319
320 =item cancel
321
322 Just returns false (no error) for now.
323
324 Called by the cancel method of FS::cust_pkg (see L<FS::cust_pkg>).
325
326 =item check
327
328 Checks all fields to make sure this is a valid domain.  If there is an error,
329 returns the error, otherwise returns false.  Called by the insert and replace
330 methods.
331
332 Sets any fixed values; see L<FS::part_svc>.
333
334 =cut
335
336 sub check {
337   my $self = shift;
338
339   my $x = $self->setfixed;
340   return $x unless ref($x);
341   my $part_svc = $x;
342
343   my $error = $self->ut_numbern('catchall');
344   return $error if $error;
345
346   #hmm
347   my $pkgnum;
348   if ( $self->svcnum ) {
349     my $cust_svc = qsearchs( 'cust_svc', { 'svcnum' => $self->svcnum } );
350     $pkgnum = $cust_svc->pkgnum;
351   } else {
352     $pkgnum = $self->pkgnum;
353   }
354
355   my($recref) = $self->hashref;
356
357   unless ( $whois_hack ) {
358     unless ( $self->email ) { #find out an email address
359       my @svc_acct;
360       foreach ( qsearch( 'cust_svc', { 'pkgnum' => $pkgnum } ) ) {
361         my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $_->svcnum } );
362         push @svc_acct, $svc_acct if $svc_acct;
363       }
364
365       if ( scalar(@svc_acct) == 0 ) {
366         return "Must order an account in package ". $pkgnum. " first";
367       } elsif ( scalar(@svc_acct) > 1 ) {
368         return "More than one account in package ". $pkgnum. ": specify admin contact email";
369       } else {
370         $self->email($svc_acct[0]->email );
371       }
372     }
373   }
374
375   #if ( $recref->{domain} =~ /^([\w\-\.]{1,22})\.(com|net|org|edu)$/ ) {
376   if ( $recref->{domain} =~ /^([\w\-]{1,22})\.(com|net|org|edu)$/ ) {
377     $recref->{domain} = "$1.$2";
378   # hmmmmmmmm.
379   } elsif ( $whois_hack && $recref->{domain} =~ /^([\w\-\.]+)$/ ) {
380     $recref->{domain} = $1;
381   } else {
382     return "Illegal domain ". $recref->{domain}.
383            " (or unknown registry - try \$whois_hack)";
384   }
385
386   $recref->{action} =~ /^(M|N)$/ or return "Illegal action";
387   $recref->{action} = $1;
388
389   my $svc_acct = qsearchs( 'svc_acct', { 'svcnum' => $recref->{catchall} } );
390   return "Unknown catchall" unless $svc_acct || ! $recref->{catchall};
391
392   $self->ut_textn('purpose');
393
394 }
395
396 =item whois
397
398 Returns the Net::Whois::Domain object (see L<Net::Whois>) for this domain, or
399 undef if the domain is not found in whois.
400
401 (If $FS::svc_domain::whois_hack is true, returns that in all cases instead.)
402
403 =cut
404
405 sub whois {
406   $whois_hack or new Net::Whois::Domain $_[0]->domain;
407 }
408
409 =item _whois
410
411 Depriciated.
412
413 =cut
414
415 sub _whois {
416   die "_whois depriciated";
417 }
418
419 =item submit_internic
420
421 Submits a registration email for this domain.
422
423 =cut
424
425 sub submit_internic {
426   my $self = shift;
427
428   my $cust_pkg = qsearchs( 'cust_pkg', { 'pkgnum' => $self->pkgnum } );
429   return unless $cust_pkg;
430   my $cust_main = qsearchs( 'cust_main', { 'custnum' => $cust_pkg->custnum } );
431   return unless $cust_main;
432
433   my %subs = (
434     'action'       => $self->action,
435     'purpose'      => $self->purpose,
436     'domain'       => $self->domain,
437     'company'      => $cust_main->company 
438                         || $cust_main->getfield('first'). ' '.
439                            $cust_main->getfield('last')
440                       ,
441     'city'         => $cust_main->city,
442     'state'        => $cust_main->state,
443     'zip'          => $cust_main->zip,
444     'country'      => $cust_main->country,
445     'last'         => $cust_main->getfield('last'),
446     'first'        => $cust_main->getfield('first'),
447     'daytime'      => $cust_main->daytime,
448     'fax'          => $cust_main->fax,
449     'email'        => $self->email,
450     'tech_contact' => $tech_contact,
451     'primary'      => shift @nameservers,
452     'primary_ip'   => shift @nameserver_ips,
453   );
454
455   #yuck
456   my @xtemplate = @template;
457   my @body;
458   my $line;
459   OLOOP: while ( defined( $line = shift @xtemplate ) ) {
460
461     if ( $line =~ /^###LOOP###$/ ) {
462       my(@buffer);
463       LOADBUF: while ( defined( $line = shift @xtemplate ) ) {
464         last LOADBUF if ( $line =~ /^###ENDLOOP###$/ );
465         push @buffer, $line;
466       }
467       my %lubs = (
468         'address'      => $cust_main->address2 
469                             ? [ $cust_main->address1, $cust_main->address2 ]
470                             : [ $cust_main->address1 ]
471                           ,
472         'secondary'    => [ @nameservers ],
473         'secondary_ip' => [ @nameserver_ips ],
474       );
475       LOOP: while (1) {
476         my @xbuffer = @buffer;
477         SUBLOOP: while ( defined( $line = shift @xbuffer ) ) {
478           if ( $line =~ /###(\w+)###/ ) {
479             #last LOOP unless my($lub)=shift@{$lubs{$1}};
480             next OLOOP unless my $lub = shift @{$lubs{$1}};
481             $line =~ s/###(\w+)###/$lub/e;
482             redo SUBLOOP;
483           } else {
484             push @body, $line;
485           }
486         } #SUBLOOP
487       } #LOOP
488
489     }
490
491     if ( $line =~ /###(\w+)###/ ) {
492       #$line =~ s/###(\w+)###/$subs{$1}/eg;
493       $line =~ s/###(\w+)###/$subs{$1}/e;
494       redo OLOOP;
495     } else {
496       push @body, $line;
497     }
498
499   } #OLOOP
500
501   my $subject;
502   if ( $self->action eq "M" ) {
503     $subject = "MODIFY DOMAIN ". $self->domain;
504   } elsif ( $self->action eq "N" ) { 
505     $subject = "NEW DOMAIN ". $self->domain;
506   } else {
507     croak "submit_internic called with action ". $self->action;
508   }
509
510   $ENV{SMTPHOSTS} = $smtpmachine;
511   $ENV{MAILADDRESS} = $from;
512   my $header = Mail::Header->new( [
513     "From: $from",
514     "To: $to",
515     "Sender: $from",
516     "Reply-To: $from",
517     "Date: ". time2str("%a, %d %b %Y %X %z", time),
518     "Subject: $subject",
519   ] );
520
521   my($msg)=Mail::Internet->new(
522     'Header' => $header,
523     'Body' => \@body,
524   );
525
526   $msg->smtpsend or die "Can't send registration email"; #die? warn?
527
528 }
529
530 =back
531
532 =head1 VERSION
533
534 $Id: svc_domain.pm,v 1.16 2001-08-20 09:41:52 ivan Exp $
535
536 =head1 BUGS
537
538 All BIND/DNS fields should be included (and exported).
539
540 Delete doesn't send a registration template.
541
542 All registries should be supported.
543
544 Should change action to a real field.
545
546 The $recref stuff in sub check should be cleaned up.
547
548 =head1 SEE ALSO
549
550 L<FS::svc_Common>, L<FS::Record>, L<FS::Conf>, L<FS::cust_svc>,
551 L<FS::part_svc>, L<FS::cust_pkg>, L<Net::Whois>, L<ssh>,
552 L<dot-qmail>, schema.html from the base documentation, config.html from the
553 base documentation.
554
555 =cut
556
557 1;
558
559