985851
#!/usr/bin/perl -w
985851
985851
# Brian Masney <masneyb@ntelos.net>
985851
# To use this script, set your base DN below. Then run 
985851
# ./dhcpd-conf-to-ldap.pl < /path-to-dhcpd-conf/dhcpd.conf > output-file
985851
# The output of this script will generate entries in LDIF format. You can use
985851
# the slapadd command to add these entries into your LDAP server. You will
985851
# definately want to double check that your LDAP entries are correct before
985851
# you load them into LDAP.
985851
985851
# This script does not do much error checking. Make sure before you run this
985851
# that the DHCP server doesn't give any errors about your config file
985851
985851
# FailOver notes:
985851
#   Failover is disabled by default, since it may need manually intervention.
985851
#   You can try the '--use=failover' option to see what happens :-)
985851
#
985851
#   If enabled, the failover pool references will be written to LDIF output.
985851
#   The failover configs itself will be added to the dhcpServer statements
985851
#   and not to the dhcpService object (since this script uses only one and
985851
#   it may be usefull to have multiple service containers in failover mode).
985851
#   Further, this script does not check if primary or secondary makes sense,
985851
#   it simply converts what it gets...
985851
985851
use Net::Domain qw(hostname hostfqdn hostdomain);
985851
use Getopt::Long;
985851
985851
my $domain = hostdomain();           # your.domain
985851
my $basedn = "dc=".$domain;
985851
   $basedn =~ s/\./,dc=/g;           # dc=your,dc=domain
985851
my $server = hostname();             # hostname (nodename)
985851
my $dhcpcn = 'DHCP Config';          # CN of DHCP config tree
985851
my $dhcpdn = "cn=$dhcpcn, $basedn";  # DHCP config tree DN
985851
my $second = '';                     # secondary server DN / hostname
985851
my $i_conf = '';                     # dhcp.conf file to read or stdin
985851
my $o_ldif = '';                     # output ldif file name or stdout
985851
my @use    = ();                     # extended flags (failover)
985851
985851
sub usage($;$)
985851
{
985851
  my $rc = shift;
985851
  my $err= shift;
985851
985851
  print STDERR "Error: $err\n\n" if(defined $err);
985851
  print STDERR <<__EOF_USAGE__;
985851
usage: 
985851
  $0 [options] < dhcpd.conf > dhcpd.ldif
985851
985851
options:
985851
985851
  --basedn  "dc=your,dc=domain"        ("$basedn")
985851
985851
  --dhcpdn  "dhcp config DN"           ("$dhcpdn")
985851
985851
  --server  "dhcp server name"         ("$server")
985851
985851
  --second  "secondary server or DN"   ("$second")
985851
985851
  --conf    "/path/to/dhcpd.conf"      (default is stdin)
985851
  --ldif    "/path/to/output.ldif"     (default is stdout)
985851
985851
  --use     "extended features"        (see source comments)
985851
__EOF_USAGE__
985851
  exit($rc);
985851
}
985851
985851
985851
sub next_token
985851
{
985851
  local ($lowercase) = @_;
985851
  local ($token, $newline);
985851
985851
  do 
985851
    {
985851
      if (!defined ($line) || length ($line) == 0)
985851
        {
985851
          $line = <>;
985851
          return undef if !defined ($line);
985851
          chop $line;
985851
          $line_number++;
985851
          $token_number = 0;
985851
        }
985851
985851
      $line =~ s/#.*//;
985851
      $line =~ s/^\s+//;
985851
      $line =~ s/\s+$//;
985851
    }
985851
  while (length ($line) == 0);
985851
985851
  if (($token, $newline) = $line =~ /^(.*?)\s+(.*)/)
985851
    {
985851
      if ($token =~ /^"/) {
985851
       #handle quoted token
985851
       if ($token !~ /"\s*$/)
985851
       {
985851
         ($tok, $newline)  = $newline =~ /([^"]+")(.*)/;
985851
         $token .= " $tok";
985851
        }
985851
      }
985851
      $line = $newline;
985851
    }
985851
  else
985851
    {
985851
      $token = $line;
985851
      $line = '';
985851
    }
985851
  $token_number++;
985851
985851
  $token =~ y/[A-Z]/[a-z]/ if $lowercase;
985851
985851
  return ($token);
985851
}
985851
985851
985851
sub remaining_line
985851
{
985851
  local ($block) = shift || 0;
985851
  local ($tmp, $str);
985851
985851
  $str = "";
985851
  while (defined($tmp = next_token (0)))
985851
    {
985851
      $str .= ' ' if !($str eq "");
985851
      $str .= $tmp;
985851
      last if $tmp =~ /;\s*$/;
985851
      last if($block and $tmp =~ /\s*[}{]\s*$/);
985851
    }
985851
985851
  $str =~ s/;$//;
985851
  return ($str);
985851
}
985851
985851
985851
sub
985851
add_dn_to_stack
985851
{
985851
  local ($dn) = @_;
985851
985851
  $current_dn = "$dn, $current_dn";
985851
}
985851
985851
985851
sub
985851
remove_dn_from_stack
985851
{
985851
  $current_dn =~ s/^.*?,\s*//;
985851
}
985851
985851
985851
sub
985851
parse_error
985851
{
985851
  print "Parse error on line number $line_number at token number $token_number\n";
985851
  exit (1);
985851
}
985851
985851
985851
sub
985851
print_entry
985851
{
985851
  return if (scalar keys %curentry == 0);
985851
985851
  if (!defined ($curentry{'type'}))
985851
    {
985851
      $hostdn = "cn=$server, $basedn";
985851
      print "dn: $hostdn\n";
985851
      print "cn: $server\n";
985851
      print "objectClass: top\n";
985851
      print "objectClass: dhcpServer\n";
985851
      print "dhcpServiceDN: $current_dn\n";
985851
      if(grep(/FaIlOvEr/i, @use))
985851
        {
985851
          foreach my $fo_peer (keys %failover)
985851
            {
985851
              next if(scalar(@{$failover{$fo_peer}}) <= 1);
985851
              print "dhcpStatements: failover peer $fo_peer { ",
985851
                    join('; ', @{$failover{$fo_peer}}), "; }\n";
985851
            }
985851
        }
985851
      print "\n";
985851
985851
      print "dn: $current_dn\n";
985851
      print "cn: $dhcpcn\n";
985851
      print "objectClass: top\n";
985851
      print "objectClass: dhcpService\n";
985851
      if (defined ($curentry{'options'}))
985851
        {
985851
          print "objectClass: dhcpOptions\n";
985851
        }
985851
      print "dhcpPrimaryDN: $hostdn\n";
985851
      if(grep(/FaIlOvEr/i, @use) and ($second ne ''))
985851
        {
985851
          print "dhcpSecondaryDN: $second\n";
985851
        }
985851
    }
985851
  elsif ($curentry{'type'} eq 'subnet')
985851
    {
985851
      print "dn: $current_dn\n";
985851
      print "cn: " . $curentry{'ip'} . "\n";
985851
      print "objectClass: top\n";
985851
      print "objectClass: dhcpSubnet\n";
985851
      if (defined ($curentry{'options'}))
985851
        {
985851
          print "objectClass: dhcpOptions\n";
985851
        }
985851
      
985851
      print "dhcpNetMask: " . $curentry{'netmask'} . "\n";
985851
      if (defined ($curentry{'ranges'}))
985851
        {
985851
          foreach $statement (@{$curentry{'ranges'}})
985851
            {
985851
              print "dhcpRange: $statement\n";
985851
            }
985851
        }
985851
    }
985851
  elsif ($curentry{'type'} eq 'shared-network')
985851
    {
985851
      print "dn: $current_dn\n";
985851
      print "cn: " . $curentry{'descr'} . "\n";
985851
      print "objectClass: top\n";
985851
      print "objectClass: dhcpSharedNetwork\n";
985851
      if (defined ($curentry{'options'}))
985851
        {
985851
          print "objectClass: dhcpOptions\n";
985851
        }
985851
    }
985851
  elsif ($curentry{'type'} eq 'group')
985851
    {
985851
      print "dn: $current_dn\n";
985851
      print "cn: group", $curentry{'idx'}, "\n";
985851
      print "objectClass: top\n";
985851
      print "objectClass: dhcpGroup\n";
985851
      if (defined ($curentry{'options'}))
985851
        {
985851
          print "objectClass: dhcpOptions\n";
985851
        }
985851
    }
985851
  elsif ($curentry{'type'} eq 'host')
985851
    {
985851
      print "dn: $current_dn\n";
985851
      print "cn: " . $curentry{'host'} . "\n";
985851
      print "objectClass: top\n";
985851
      print "objectClass: dhcpHost\n";
985851
      if (defined ($curentry{'options'}))
985851
        {
985851
          print "objectClass: dhcpOptions\n";
985851
        }
985851
985851
      if (defined ($curentry{'hwaddress'}))
985851
        {
985851
          $curentry{'hwaddress'} =~ y/[A-Z]/[a-z]/;
985851
          print "dhcpHWAddress: " . $curentry{'hwaddress'} . "\n";
985851
        }
985851
    }
985851
  elsif ($curentry{'type'} eq 'pool')
985851
    {
985851
      print "dn: $current_dn\n";
985851
      print "cn: pool", $curentry{'idx'}, "\n";
985851
      print "objectClass: top\n";
985851
      print "objectClass: dhcpPool\n";
985851
      if (defined ($curentry{'options'}))
985851
        {
985851
          print "objectClass: dhcpOptions\n";
985851
        }
985851
985851
      if (defined ($curentry{'ranges'}))
985851
        {
985851
          foreach $statement (@{$curentry{'ranges'}})
985851
            {
985851
              print "dhcpRange: $statement\n";
985851
            }
985851
        }
985851
    }
985851
  elsif ($curentry{'type'} eq 'class')
985851
    {
985851
      print "dn: $current_dn\n";
985851
      print "cn: " . $curentry{'class'} . "\n";
985851
      print "objectClass: top\n";
985851
      print "objectClass: dhcpClass\n";
985851
      if (defined ($curentry{'options'}))
985851
        {
985851
          print "objectClass: dhcpOptions\n";
985851
        }
985851
    }
985851
  elsif ($curentry{'type'} eq 'subclass')
985851
    {
985851
      print "dn: $current_dn\n";
985851
      print "cn: " . $curentry{'subclass'} . "\n";
985851
      print "objectClass: top\n";
985851
      print "objectClass: dhcpSubClass\n";
985851
      if (defined ($curentry{'options'}))
985851
        {
985851
          print "objectClass: dhcpOptions\n";
985851
        }
985851
      print "dhcpClassData: " . $curentry{'class'} . "\n";
985851
    }
985851
985851
  if (defined ($curentry{'statements'}))
985851
    {
985851
      foreach $statement (@{$curentry{'statements'}})
985851
        {
985851
          print "dhcpStatements: $statement\n";
985851
        }
985851
    }
985851
985851
  if (defined ($curentry{'options'}))
985851
    {
985851
      foreach $statement (@{$curentry{'options'}})
985851
        {
985851
          print "dhcpOption: $statement\n";
985851
        }
985851
    }
985851
985851
  print "\n";
985851
  undef (%curentry);
985851
}
985851
985851
985851
sub parse_netmask
985851
{
985851
  local ($netmask) = @_;
985851
  local ($i);
985851
985851
  if ((($a, $b, $c, $d) = $netmask =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) != 4)
985851
    {
985851
      parse_error ();
985851
    }
985851
985851
  $num = (($a & 0xff) << 24) |
985851
         (($b & 0xff) << 16) |
985851
         (($c & 0xff) << 8) |
985851
          ($d & 0xff);
985851
985851
  for ($i=1; $i<=32 && $num & (1 << (32 - $i)); $i++)
985851
    {
985851
    }
985851
  $i--;
985851
985851
  return ($i);
985851
}
985851
985851
985851
sub parse_subnet
985851
{
985851
  local ($ip, $tmp, $netmask);
985851
985851
  print_entry () if %curentry;
985851
    
985851
  $ip = next_token (0);
985851
  parse_error () if !defined ($ip);
985851
985851
  $tmp = next_token (1);
985851
  parse_error () if !defined ($tmp);
985851
  parse_error () if !($tmp eq 'netmask');
985851
985851
  $tmp = next_token (0);
985851
  parse_error () if !defined ($tmp);
985851
  $netmask = parse_netmask ($tmp);
985851
985851
  $tmp = next_token (0);
985851
  parse_error () if !defined ($tmp);
985851
  parse_error () if !($tmp eq '{');
985851
985851
  add_dn_to_stack ("cn=$ip");
985851
  $curentry{'type'} = 'subnet';
985851
  $curentry{'ip'} = $ip;
985851
  $curentry{'netmask'} = $netmask;
985851
  $cursubnet = $ip;
985851
  $curcounter{$ip} = { pool  => 0, group => 0 };
985851
}
985851
985851
985851
sub parse_shared_network
985851
{
985851
  local ($descr, $tmp);
985851
985851
  print_entry () if %curentry;
985851
985851
  $descr = next_token (0);
985851
  parse_error () if !defined ($descr);
985851
985851
  $tmp = next_token (0);
985851
  parse_error () if !defined ($tmp);
985851
  parse_error () if !($tmp eq '{');
985851
985851
  add_dn_to_stack ("cn=$descr");
985851
  $curentry{'type'} = 'shared-network';
985851
  $curentry{'descr'} = $descr;
985851
}
985851
985851
985851
sub parse_host
985851
{
985851
  local ($descr, $tmp);
985851
985851
  print_entry () if %curentry;
985851
985851
  $host = next_token (0);
985851
  parse_error () if !defined ($host);
985851
985851
  $tmp = next_token (0);
985851
  parse_error () if !defined ($tmp);
985851
  parse_error () if !($tmp eq '{');
985851
985851
  add_dn_to_stack ("cn=$host");
985851
  $curentry{'type'} = 'host';
985851
  $curentry{'host'} = $host;
985851
}
985851
985851
985851
sub parse_group
985851
{
985851
  local ($descr, $tmp);
985851
985851
  print_entry () if %curentry;
985851
985851
  $tmp = next_token (0);
985851
  parse_error () if !defined ($tmp);
985851
  parse_error () if !($tmp eq '{');
985851
985851
  my $idx;
985851
  if(exists($curcounter{$cursubnet})) {
985851
    $idx = ++$curcounter{$cursubnet}->{'group'};
985851
  } else {
985851
    $idx = ++$curcounter{''}->{'group'};
985851
  }
985851
985851
  add_dn_to_stack ("cn=group".$idx);
985851
  $curentry{'type'} = 'group';
985851
  $curentry{'idx'} = $idx;
985851
}
985851
985851
985851
sub parse_pool
985851
{
985851
  local ($descr, $tmp);
985851
985851
  print_entry () if %curentry;
985851
985851
  $tmp = next_token (0);
985851
  parse_error () if !defined ($tmp);
985851
  parse_error () if !($tmp eq '{');
985851
985851
  my $idx;
985851
  if(exists($curcounter{$cursubnet})) {
985851
    $idx = ++$curcounter{$cursubnet}->{'pool'};
985851
  } else {
985851
    $idx = ++$curcounter{''}->{'pool'};
985851
  }
985851
985851
  add_dn_to_stack ("cn=pool".$idx);
985851
  $curentry{'type'} = 'pool';
985851
  $curentry{'idx'} = $idx;
985851
}
985851
985851
985851
sub parse_class
985851
{
985851
  local ($descr, $tmp);
985851
985851
  print_entry () if %curentry;
985851
985851
  $class = next_token (0);
985851
  parse_error () if !defined ($class);
985851
985851
  $tmp = next_token (0);
985851
  parse_error () if !defined ($tmp);
985851
  parse_error () if !($tmp eq '{');
985851
985851
  $class =~ s/\"//g;
985851
  add_dn_to_stack ("cn=$class");
985851
  $curentry{'type'} = 'class';
985851
  $curentry{'class'} = $class;
985851
}
985851
985851
985851
sub parse_subclass
985851
{
985851
  local ($descr, $tmp);
985851
985851
  print_entry () if %curentry;
985851
985851
  $class = next_token (0);
985851
  parse_error () if !defined ($class);
985851
985851
  $subclass = next_token (0);
985851
  parse_error () if !defined ($subclass);
985851
985851
  $tmp = next_token (0);
985851
  parse_error () if !defined ($tmp);
985851
  parse_error () if !($tmp eq '{');
985851
985851
  add_dn_to_stack ("cn=$subclass");
985851
  $curentry{'type'} = 'subclass';
985851
  $curentry{'class'} = $class;
985851
  $curentry{'subclass'} = $subclass;
985851
}
985851
985851
985851
sub parse_hwaddress
985851
{
985851
  local ($type, $hw, $tmp);
985851
985851
  $type = next_token (1);
985851
  parse_error () if !defined ($type);
985851
985851
  $hw = next_token (1);
985851
  parse_error () if !defined ($hw);
985851
  $hw =~ s/;$//;
985851
985851
  $curentry{'hwaddress'} = "$type $hw";
985851
}
985851
985851
    
985851
sub parse_range
985851
{
985851
  local ($tmp, $str);
985851
985851
  $str = remaining_line ();
985851
985851
  if (!($str eq ''))
985851
    {
985851
      $str =~ s/;$//;
985851
      push (@{$curentry{'ranges'}}, $str);
985851
    }
985851
}
985851
985851
985851
sub parse_statement
985851
{
985851
  local ($token) = shift;
985851
  local ($str);
985851
985851
  if ($token eq 'option')
985851
    {
985851
      $str = remaining_line ();
985851
      push (@{$curentry{'options'}}, $str);
985851
    }
985851
  elsif($token eq 'failover')
985851
    {
985851
      $str = remaining_line (1); # take care on block
985851
      if($str =~ /[{]/)
985851
        {
985851
          my ($peername, @statements);
985851
985851
          parse_error() if($str !~ /^\s*peer\s+(.+?)\s+[{]\s*$/);
985851
          parse_error() if(($peername = $1) !~ /^\"?[^\"]+\"?$/);
985851
985851
          #
985851
          # failover config block found:
985851
          # e.g. 'failover peer "some-name" {'
985851
          #
985851
          if(not grep(/FaIlOvEr/i, @use))
985851
            {
985851
              print STDERR "Warning: Failover config 'peer $peername' found!\n";
985851
              print STDERR "         Skipping it, since failover disabled!\n";
985851
              print STDERR "         You may try out --use=failover option.\n";
985851
            }
985851
985851
          until($str =~ /[}]/ or $str eq "")
985851
            {
985851
                $str = remaining_line (1);
985851
                # collect all statements, except ending '}'
985851
                push(@statements, $str) if($str !~ /[}]/);
985851
            }
985851
          $failover{$peername} = [@statements];
985851
        }
985851
      else
985851
        {
985851
          #
985851
          # pool reference to failover config is fine
985851
          # e.g. 'failover peer "some-name";'
985851
          #
985851
          if(not grep(/FaIlOvEr/i, @use))
985851
            {
985851
              print STDERR "Warning: Failover reference '$str' found!\n";
985851
              print STDERR "         Skipping it, since failover disabled!\n";
985851
              print STDERR "         You may try out --use=failover option.\n";
985851
            }
985851
          else
985851
            {
985851
              push (@{$curentry{'statements'}}, $token. " " . $str);
985851
            }
985851
        }
985851
    }
985851
  elsif($token eq 'zone')
985851
    {
985851
      $str = $token;
985851
      while($str !~ /}$/) {
985851
        $str .= ' ' . next_token (0);
985851
      }
985851
      push (@{$curentry{'statements'}}, $str);
985851
    }
985851
  elsif($token =~ /^(authoritative)[;]*$/)
985851
    {
985851
      push (@{$curentry{'statements'}}, $1);
985851
    }
985851
  else
985851
    {
985851
      $str = $token . " " . remaining_line ();
985851
      push (@{$curentry{'statements'}}, $str);
985851
    }
985851
}
985851
985851
985851
my $ok = GetOptions(
985851
    'basedn=s'      => \$basedn,
985851
    'dhcpdn=s'      => \$dhcpdn,
985851
    'server=s'      => \$server,
985851
    'second=s'      => \$second,
985851
    'conf=s'        => \$i_conf,
985851
    'ldif=s'        => \$o_ldif,
985851
    'use=s'         => \@use,
985851
    'h|help|usage'  => sub { usage(0); },
985851
);
985851
985851
unless($server =~ /^\w+/)
985851
  {
985851
    usage(1, "invalid server name '$server'");
985851
  }
985851
unless($basedn =~ /^\w+=[^,]+/)
985851
  {
985851
    usage(1, "invalid base dn '$basedn'");
985851
  }
985851
985851
if($dhcpdn =~ /^cn=([^,]+)/i)
985851
  {
985851
    $dhcpcn = "$1";
985851
  }
985851
$second = '' if not defined $second;
985851
unless($second eq '' or $second =~ /^cn=[^,]+\s*,\s*\w+=[^,]+/i)
985851
  {
985851
    if($second =~ /^cn=[^,]+$/i)
985851
      {
985851
        # relative DN 'cn=name'
985851
        $second = "$second, $basedn";
985851
      }
985851
    elsif($second =~ /^\w+/)
985851
      {
985851
        # assume hostname only
985851
        $second = "cn=$second, $basedn";
985851
      }
985851
    else
985851
      {
985851
        usage(1, "invalid secondary '$second'")
985851
      }
985851
  }
985851
985851
usage(1) unless($ok);
985851
985851
if($i_conf ne "" and -f $i_conf)
985851
  {
985851
    if(not open(STDIN, '<', $i_conf))
985851
      {
985851
        print STDERR "Error: can't open conf file '$i_conf': $!\n";
985851
        exit(1);
985851
      }
985851
  }
985851
if($o_ldif ne "")
985851
  {
985851
    if(-e $o_ldif)
985851
      {
985851
        print STDERR "Error: output ldif name '$o_ldif' already exists!\n";
985851
        exit(1);
985851
      }
985851
    if(not open(STDOUT, '>', $o_ldif))
985851
      {
985851
        print STDERR "Error: can't open ldif file '$o_ldif': $!\n";
985851
        exit(1);
985851
      }
985851
  }
985851
985851
985851
print STDERR "Creating LDAP Configuration with the following options:\n";
985851
print STDERR "\tBase DN: $basedn\n";
985851
print STDERR "\tDHCP DN: $dhcpdn\n";
985851
print STDERR "\tServer DN: cn=$server, $basedn\n";
985851
print STDERR "\tSecondary DN: $second\n"
985851
             if(grep(/FaIlOvEr/i, @use) and $second ne '');
985851
print STDERR "\n";
985851
985851
my $token;
985851
my $token_number = 0;
985851
my $line_number = 0;
985851
my %curentry;
985851
my $cursubnet = '';
985851
my %curcounter = ( '' => { pool => 0, group => 0 } );
985851
985851
$current_dn = "$dhcpdn";
985851
$curentry{'descr'} = $dhcpcn;
985851
$line = '';
985851
%failover = ();
985851
985851
while (($token = next_token (1)))
985851
  {
985851
    if ($token eq '}')
985851
      {
985851
        print_entry () if %curentry;
985851
        if($current_dn =~ /.+?,\s*${dhcpdn}$/) {
985851
          # don't go below dhcpdn ...
985851
          remove_dn_from_stack ();
985851
        }
985851
      }
985851
    elsif ($token eq 'subnet')
985851
      {
985851
        parse_subnet ();
985851
        next;
985851
      }
985851
    elsif ($token eq 'shared-network')
985851
      {
985851
        parse_shared_network ();
985851
        next;
985851
      }
985851
    elsif ($token eq 'class')
985851
      {
985851
        parse_class ();
985851
        next;
985851
      }
985851
    elsif ($token eq 'subclass')
985851
      {
985851
        parse_subclass ();
985851
        next;
985851
      }
985851
    elsif ($token eq 'pool')
985851
      {
985851
        parse_pool ();
985851
        next;
985851
      }
985851
    elsif ($token eq 'group')
985851
      {
985851
        parse_group ();
985851
        next;
985851
      }
985851
    elsif ($token eq 'host')
985851
      {
985851
        parse_host ();
985851
        next;
985851
      }
985851
    elsif ($token eq 'hardware')
985851
      {
985851
        parse_hwaddress ();
985851
        next;
985851
      }
985851
    elsif ($token eq 'range')
985851
      {
985851
        parse_range ();
985851
        next;
985851
      }
985851
    else
985851
      {
985851
        parse_statement ($token);
985851
        next;
985851
      }
985851
  }
985851
985851
close(STDIN)  if($i_conf);
985851
close(STDOUT) if($o_ldif);
985851
985851
print STDERR "Done.\n";
985851