aboutsummaryrefslogtreecommitdiff
path: root/vhostcname/vhostcname
blob: 359101c43ed8dc437c0e7c76648215185e133b46 (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
#!/usr/bin/perl
# Copyright (C) 2014 Sergey Poznyakoff <gray@gnu.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

use strict;
use Getopt::Long qw(:config gnu_getopt no_ignore_case);
use Pod::Usage;
use Pod::Man;
use Sys::Hostname;
use Cwd qw(getcwd realpath);
use Net::DNS;

my $script;        # This script name;

my $config_file = "/etc/vhostcname.conf";

my $cnamelist = "/var/run/vhostcname.cache";
my $host;          # This host name.
my @zone;          # List of acceptable DNS zones.
my $nameserver;    # Nameserver to use for updates.
my @tsig_args;     # Arguments to sing_tsig (path to the DNSSEC key file, or
                   # the key name and hash.
my $ttl = 3600;    # Default TTL.
my $confdir;       # Apache configuration directory.
my $confpat = "*"; # A globbing pattern for Apache configuration files.
my $dry_run;       # Dry-run mode.
my $debug;         # Debug level.
my $allow_wildcard_domains;

my $help;          # Display help summary.
my $man;           # Ditto in manpage format.

my $status = 0;    # Default exit status.

sub err {
    print STDERR "$script: ";
    print STDERR $_ for (@_);
    print STDERR "\n";
}		

sub abend {
    my $code = shift;
    &err;
    exit($code);
}

sub read_config_file($) {
    my $file = shift;
    unless (-f $file) {
	print STDERR "$script: configuration file $file does not exist\n"
	    if ($debug);
	return;
    }
    print STDERR "$script: reading $file\n" if ($debug);
    open(my $fd, "<", $file) or abend(1, "cannot open $file: $!");
    while (<$fd>) {
        chomp;
        s/^\s+//;
        s/\s+$//;
        s/\s+=\s+/=/;
        s/#.*//;
        next if ($_ eq "");
        unshift(@ARGV, "--$_");
    }
    close($fd);
}

# Domain names may be formed from the set of alphanumeric ASCII characters 
# (a-z, A-Z, 0-9). In addition the hyphen is permitted if it is surrounded 
# by characters, digits or hyphens, although it is not to start or end a 
# label.
sub valid_domain_name {
    my $name = shift;
    $name =~ s/^\*\.// if ($allow_wildcard_domains);
    foreach my $label (split(/\./, $name)) {
        $label =~ s/-+/-/g;
        $label =~ s/[a-zA-Z0-9]-[a-zA-Z0-9]//g;
        return 0 if $label =~ /^-/ or $label =~ /-$/;
        return 0 if $label =~ /[^a-zA-Z0-9]/;
    }
    return 1;
}

sub get_cnames($) {
    my $dir = shift;
    my %ret;

    foreach my $file (glob "$dir/$confpat") {
	next unless (-f $file);
	print STDERR "$script: reading cnames from $file\n" if ($debug > 2);
	
	open(my $fd, "<", $file) or do {
	    err("can't open file $file: $!");
	    next;
	};
	my $line = 0;
	while (<$fd>) {
	    s/#.*//;
	    s/^\s+//;
	    s/\s+$//;
	    next if (/^$/);
	    if (/^Server(Name|Alias)\s+(.*)/) {
		foreach my $name (split /\s+/, $2) {
		    unless (valid_domain_name($name)) {
			print STDERR "$script: $file:$line: $name: invalid domain name\n";
			next;
		    }
		    foreach my $z (@zone) {
			if ($name =~ /.*\.$z$/) {
			    if ($name =~ /^\*\.(.+)/ and $1 eq $z) {
				print STDERR "$script: $file:$line: $name: first-level wildcard\n";
				next;
			    }
			    $ret{$name} = $z;
			    last;
			}
		    }
		}
	    }
	}
	close($fd)
    }

    return %ret;
}

sub read_cname_list($) {
    my $file = shift;
    my %ret;

    if (-f $file) {
	open(my $fd, "<", $file) or abend(1, "cannot open $file: $!");
	while (<$fd>) {
	    chomp;
	    s/^\s+//;
	    s/\s+$//;
	    s/#.*//;
	    next if ($_ eq "");
	    my @a = split / /;
	    $ret{$a[0]} = $a[1];
	}
	close($fd);
    }
    return %ret;
}

sub write_cname_list {
    my ($file, %hash) = @_;

    return if ($dry_run);

    open(my $fd, ">", $file) or abend(1, "cannot open $file for writing: $!");
    foreach my $h (sort keys %hash) {
	print $fd "$h $hash{$h}\n";
    }
    close($fd);
}

sub ns_update {
    my $resolver = shift;
    my $name = shift;
    my $domain = shift;
    my %hash = @_;
    my %ignorerr;

    print STDERR "$script: updating $name in $domain: ".
	join(',', map { "$_ => $hash{$_}" } keys %hash) .
	"\n" if ($debug > 1);
    return 1 if ($dry_run);
    
    my $update = new Net::DNS::Update($domain);

    while (my ($k, $v) = each %hash) {
	if ($k eq 'ignore') {
	    $ignorerr{$v} = 1;
        } else {
	    $update->push($k => $v);
        }
    }
    $update->sign_tsig(@tsig_args) if ($#tsig_args >= 0);
    my $reply = $resolver->send($update);
    if ($reply) {
	if ($reply->header->rcode eq 'NOERROR') {
	    print STDERR "$script: update successful\n" if ($debug>3);
        } elsif ($ignorerr{$reply->header->rcode}) {
            print STDERR "$script: ignoring " . $reply->header->rcode . ': ' .
                join(',', map { "$_ => $hash{$_}" } keys %hash) . "\n"
		if ($debug>3);
	} else {
	    err("updating $name failed: ",
		join(',', map { "$_ => $hash{$_}" } keys %hash),
		': ',
		$reply->header->rcode);
	    $status = 2;
	    return 0;
	}
    } else {
	err("updating $name failed: ",
	    join(',', map { "$_ => $hash{$_}" } keys %hash),
	    ': ',
	    $resolver->errorstring);
	$status = 2;
	return 0;
    }
    return 1;
}

sub update_cnames_from_hash {
    my %hash = @_;
    
    print STDERR "$script: " . keys(%hash) . " names to update\n"
	if ($debug > 2);
    my %oldhash = read_cname_list($cnamelist);
    my @namelist = sort(keys(%hash));
    if (join(",", @namelist) eq join(".", sort(keys(%oldhash)))) {
	print STDERR "$script: nothing to update\n" if ($debug);
	return;
    }

    my $resolver = new Net::DNS::Resolver;
    $resolver->nameservers($nameserver) if defined($nameserver);
    
    my $name;
    foreach $name (@namelist) {
	if ($oldhash{$name}) {
	    delete $oldhash{$name};
	} else {
	    ns_update($resolver, $name, $hash{$name},
		      prereq => yxdomain($name),
		      update => rr_del($name),
                      ignore => 'NXDOMAIN');
	    print STDERR "$script: $name $ttl CNAME $host\n" if ($debug);
	    delete $hash{$name}
	        unless ns_update($resolver, $name, $hash{$name},
 			     update => rr_add("$name $ttl CNAME $host"));
	}
    }

    foreach $name (keys %oldhash) {
	ns_update($resolver, $name, $oldhash{$name},
		  prereq => yxrrset("$name CNAME"),
		  update => rr_del("$name CNAME"),
                  ignore => 'NXRRSET');
    }

    write_cname_list($cnamelist, %hash);
}

sub update_cnames_from_dir($) {
    update_cnames_from_hash(get_cnames(shift));
}
		      
sub nscleanup {
    print STDERR "$script: Removing DNS CNAME records\n" if ($debug);

    my $resolver = new Net::DNS::Resolver;
    $resolver->nameservers($nameserver) if defined($nameserver);

    my %hash = read_cname_list($cnamelist);
    foreach my $name (keys %hash) {
	print STDERR "$script: removing $name from $hash{$name}\n"
            if ($debug);
	delete $hash{$name}
	    if ns_update($resolver, $name, $hash{$name},
			 prereq => yxrrset("$name CNAME"),
			 update => rr_del("$name CNAME"),
                         ignore => 'NXRRSET');
    }

    write_cname_list($cnamelist, %hash);
}


###
($script = $0) =~ s/.*\///;

## Read configuration
read_config_file($ENV{'VHOSTCNAME_CONF'} ?
		 $ENV{'VHOSTCNAME_CONF'} : $config_file);

GetOptions("help" => \$man,
           "h" => \$help,
           "debug|d+" => \$debug,
	   "dry-run|n" => \$dry_run,
	   "hostname|H=s" => \$host,
	   "apache-config-pattern=s" => \$confpat,
	   "apache-config-directory=s" => \$confdir,
	   "ns-key-file=s" => sub {
	       abend(3, "NS key already set") if ($#tsig_args >= 0);
	       push @tsig_args, $_[1];
	   },
	   "ns-key=s" => sub {
	       abend(3, "NS key already set") if ($#tsig_args >= 0);
	       if ($_[1] =~ /(.+?)=(.+)/) {
                   push @tsig_args, $1;
                   push @tsig_args, $2;
               } else {
                   abend(3, "argument to --ns-key must be NAME=KEY");
               }
           },
	   "cname-file=s" => \$cnamelist,
	   "zone|z=s@" => \@zone,
	   "ttl=i" => \$ttl,
	   "server=s" => \$nameserver,
	   "allow-wildcard-domains" => \$allow_wildcard_domains
	   ) or exit(3);

pod2usage(-message => "$script: update DNS from Apache virtual host configuration",
	  -exitstatus => 0) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;

unless (defined($confdir)) {
    foreach my $dir ("/etc/apache2", "/etc/httpd") {
	if (-e "$dir/sites-enabled" and -e "$dir/sites-available") {
	    $confdir = $dir;
	    last;
	}
	if (-e "$dir/vhosts.d") {
	    $confdir = "$dir/vhosts.d";
	    last;
	}
    }
    abend(3,
	  "don't know where virtual host configurations are located; use --apache-config-directory option")
	unless defined($confdir);
}

$host = hostname() unless defined($host);
push(@zone, $host) if ($#zone == -1);
$debug++ if ($dry_run);

if ($#ARGV == -1) {
    abend(3, "command not given") unless ($ENV{'DIREVENT_FILE'});
    print STDERR "$script: started as direvent handler for " .
	         "$ENV{'DIREVENT_GENEV_NAME'} on $ENV{'DIREVENT_FILE'}\n"
		 if ($debug);
    my $cwd = getcwd;
    my $update_dir;
    if (-d "$confdir/sites-available" && -d "$confdir/sites-enabled") {
	if ($cwd eq "$confdir/sites-available") {
	    foreach my $file (glob "$confdir/sites-enabled/$confpat") {
		next unless (-l $file);
		if (realpath(readlink($file)) eq 
		    "$confdir/sites-available/$ENV{'DIREVENT_FILE'}") {
		    $update_dir = "$confdir/sites-enabled";
		    last;
		}
	    }
	} elsif ($cwd eq "$confdir/sites-enabled") {
	    $update_dir = $cwd;
	}
    } else {
	$update_dir = $cwd;
    }

    update_cnames_from_dir($update_dir) if defined($update_dir);
} elsif ($#ARGV != 0) {
    abend(3, "too many arguments");
} elsif ($ARGV[0] =~ /^start|restart|force-restart|reload$/) {
    nscleanup if ($ARGV[0] =~ /start$/);
    my %cnames = get_cnames(-d "$confdir/sites-enabled" ?
			    "$confdir/sites-enabled" : $confdir);
    update_cnames_from_hash(%cnames);
    print STDERR "$script: no cnames defined\n" unless (keys(%cnames) > 0);
} elsif ($ARGV[0] eq "stop") {
    nscleanup;
} elsif ($ARGV[0] eq "status") {
    err("status command ignored");
} else {
    abend(3, "invalid command, try $script --help for more info");
}

exit($status);

__END__
=head1 NAME

vhostcname - synchronize DNS with Apache virtual host configuration

=head1 SYNOPSIS

B<vhostcname> [OPTIONS] B<COMMAND>

=head1 DESCRIPTION

The program takes a list of DNS zones and scans Apache virtual host
configuration files.  For each hostname found in B<ServerName> and
B<ServerAlias> statements, it checks whether this name ends in a
zone from the list, and if so, attempts to register this hostname
using the DNS dynamic updates mechanism (B<RFC 2136>).

A reverse operation is also supported: deregister all host name
registered on the previous run.

The mode of operation is requested by the B<COMMAND> argument.
The available B<COMMAND>s have been chosen so as to allow
B<vhostcname> to be run as one of the machine's startup
scripts.  The exact ways to register it to be run on server startup
and shutdown depend on the operating system and distribution in use.
For example, on Debian-based GNU/Linux:

    cd /etc/init.d
    ln -sf /usr/bin/vhostcname /etc/init.d
    update-rc.d vhostcname defaults

The program can also be ised as a B<direvent>(8) handler.  This use
allows for immediate updates of the DNS records upon any modifications
to the Apache configuration files.  The following example shows the
corresponding B<direvent.conf>(5) entry:    

    watcher {
        path /etc/apache2/sites-available;
        path /etc/apache2/sites-enabled;
        event (create,delete,write);
        timeout 10;
        option (stderr,stdout);
        command /usr/bin/vhostcname;
    }
    
=head1 COMMANDS

=over 4

=item B<start>

Scan the apache configuration files and register all server names matching
the supplied zones.
    
=item B<stop>

Deregister all hostnames registered previously.

=item B<restart>, B<force-restart>, B<reload>

Same as running B<vhostcname stop; vhostcname start>.    
    
=item B<status>

Ignored    
    
=back    
    
=head1 OPTIONS

=over 4    

=item B<--allow-wildcard-domains>

Allow the use of wildcard (B<*>).  When this option is in effect, a wildcard
will be allowed if it is the very first label in a domain name and it is
separated from the base zone (see the B<--zone> option) by one or more labels.
    
=item B<--apache-config-directory=>I<DIR>

Sets the Apache configuration directory.  I<DIR> should be either a directory
where virtual configuration file are located or a directory which hosts the
B<sites-available> and B<sites-enabled> directories.  In the latter case,
B<vhostcname> will look for files matching B<apache-config-pattern> in
I<DIR>B</sites-enabled>.

If this option is not given, B<vhostcname> will try to deduce where the
configuration files are located.  It will issue a warning message and
terminate if unable to do that.
    
=item B<--apache-config-pattern=>I<GLOB>

Shell globbing pattern for virtual host configuration files.  By default,
B<*> is used, meaning that B<vhostcname> will scan all files in the
configuration directory.
    
=item B<--cname-file=>I<NAME>

Name of the file where B<vhostcname> will keep successfully registered
host names.  Default is B</var/run/vhostcname.cache>.    
    
=item B<-d>, B<--debug>

Increases the debug level.  Multiple B<-d> options are allowed.
    
=item B<-n>, B<--dry-run>,

Enables I<dry-run> mode: print what would have been done without actually
doing it.    
    
=item B<--help>

Displays B<vhostcname> man page.
    
=item B<-h>

Displays a short help summary and exits.
    
=item B<-H>, B<--hostname>=I<NAME>

Sets the hostname.  Use this if B<vhostcname> is unable to correctly
determine it.
    
=item B<--ns-key=>I<NAME>=I<KEY>

Define the TSIG key.   
    
=item B<--ns-key-file=>I<KEYFILE>

Name of the key file.  The argument should be the name of a file
generated by the B<dnssec-keygen> utility.  Either B<.key> or B<.private>
file can be used.

This option cannot be used together with B<--ns-key>.    

=item B<--server=>I<NAME>

Name of the DNS server to use.  Normally B<vhostcname> determines what server
to use based on the B<SOA> record of the zone to be updated, so this option
is rarely needed.    
    
=item B<--ttl=>I<TIME>

TTL value for new DNS records.  Default is 3600.    
    
=item B<--zone=>I<NAME>

Name of the zone which B<vhostcname> can update.  Multiple B<--zone> options
can be given.

If no B<--zone> option is given, B<vhostcname> will take hostname as the
name of the zone.

=back

=head1 CONFIGURATION FILE

If the file B<etc/vhostcname.conf> exists, the program will read its
configuration from it.  A familiar UNIX configuration format is used.
Empty lines and UNIX comments are ignored.  Each non-empty line is either an
option name, or option assignment, i.e. B<opt>=B<val>, with any amount of
optional whitespace around the equals sign.  Valid option names are
the same as the long command line options, but without the leading B<-->.
For example:

  zone   = vhost.example.com
  ns-key-file = /etc/bind/Kvhost+157+43558.key
  ttl    = 3600

=head1 ENVIRONMENT

=over 4

=item B<VHOSTCNAME_CONF>

The name of the configuration file to use instead of the default
F</etc/vhostcname.conf>.

=back

=head1 EXIT CODE

=over 4

=item 0

Success

=item 1

Operating system error (unable to open file, etc.)

=item 2

Some of the host names could not be registered.    
    
=item 3

Command line usage error    

=back
    
=head1 BUGS

Only one key file can be given.  This means that if you use multiple
B<--zone> options, all zones must be configured to accept the same
DNSSEC key.  Ditto for the B<--server> option.    

=head1 SEE ALSO

B<direvent>(8).    
    
=head1 AUTHOR

Sergey Poznyakoff <gray@gnu.org>

=cut
    

Return to:

Send suggestions and report system problems to the System administrator.