aboutsummaryrefslogtreecommitdiff
path: root/contrib/ldap/dhcpd-conf-to-ldap
blob: aee6c97925d25172d6de504748032d7a0566d727 (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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
#!/usr/bin/perl -w

# Brian Masney <masneyb@gftp.org>
# To use this script, set your base DN below. Then run 
# ./dhcpd-conf-to-ldap.pl < /path-to-dhcpd-conf/dhcpd.conf > output-file
# The output of this script will generate entries in LDIF format. You can use
# the slapadd command to add these entries into your LDAP server. You will
# definately want to double check that your LDAP entries are correct before
# you load them into LDAP.

# This script does not do much error checking. Make sure before you run this
# that the DHCP server doesn't give any errors about your config file

# FailOver notes:
#   Failover is disabled by default, since it may need manually intervention.
#   You can try the '--use=failover' option to see what happens :-)
#
#   If enabled, the failover pool references will be written to LDIF output.
#   The failover configs itself will be added to the dhcpServer statements
#   and not to the dhcpService object (since this script uses only one and
#   it may be usefull to have multiple service containers in failover mode).
#   Further, this script does not check if primary or secondary makes sense,
#   it simply converts what it gets...

use Net::Domain qw(hostname hostfqdn hostdomain);
use Getopt::Long;

my $domain = hostdomain();           # your.domain
my $basedn = "dc=".$domain;
   $basedn =~ s/\./,dc=/g;           # dc=your,dc=domain
my $server = hostname();             # hostname (nodename)
my $dhcpcn = 'DHCP Config';          # CN of DHCP config tree
my $dhcpdn = "cn=$dhcpcn, $basedn";  # DHCP config tree DN
my $second = '';                     # secondary server DN / hostname
my $i_conf = '';                     # dhcp.conf file to read or stdin
my $o_ldif = '';                     # output ldif file name or stdout
my @use    = ();                     # extended flags (failover)

sub usage($;$)
{
  my $rc = shift;
  my $err= shift;

  print STDERR "Error: $err\n\n" if(defined $err);
  print STDERR <<__EOF_USAGE__;
usage: 
  $0 [options] < dhcpd.conf > dhcpd.ldif

options:

  --basedn  "dc=your,dc=domain"        ("$basedn")

  --dhcpdn  "dhcp config DN"           ("$dhcpdn")

  --server  "dhcp server name"         ("$server")

  --second  "secondary server or DN"   ("$second")

  --conf    "/path/to/dhcpd.conf"      (default is stdin)
  --ldif    "/path/to/output.ldif"     (default is stdout)

  --use     "extended features"        (see source comments)
__EOF_USAGE__
  exit($rc);
}


sub next_token
{
  local ($lowercase) = @_;
  local ($token, $newline);

  do 
    {
      if (!defined ($line) || length ($line) == 0)
        {
          $line = <>;
          return undef if !defined ($line);
          chop $line;
          $line_number++;
          $token_number = 0;
        }

      $line =~ s/#.*//;
      $line =~ s/^\s+//;
      $line =~ s/\s+$//;
    }
  while (length ($line) == 0);

  if (($token, $newline) = $line =~ /^(.*?)\s+(.*)/)
    {
      if ($token =~ /^"/) {
       #handle quoted token
       if ($token !~ /"\s*$/)
       {
         ($tok, $newline)  = $newline =~ /([^"]+")(.*)/;
         $token .= " $tok";
        }
      }
      $line = $newline;
    }
  else
    {
      $token = $line;
      $line = '';
    }
  $token_number++;

  $token =~ y/[A-Z]/[a-z]/ if $lowercase;

  return ($token);
}


sub remaining_line
{
  local ($block) = shift || 0;
  local ($tmp, $str);

  $str = "";
  while (defined($tmp = next_token (0)))
    {
      $str .= ' ' if !($str eq "");
      $str .= $tmp;
      last if $tmp =~ /;\s*$/;
      last if($block and $tmp =~ /\s*[}{]\s*$/);
    }

  $str =~ s/;$//;
  return ($str);
}


sub
add_dn_to_stack
{
  local ($dn) = @_;

  $current_dn = "$dn, $current_dn";
}


sub
remove_dn_from_stack
{
  $current_dn =~ s/^.*?,\s*//;
}


sub
parse_error
{
  print "Parse error on line number $line_number at token number $token_number\n";
  exit (1);
}


sub
print_entry
{
  return if (scalar keys %curentry == 0);

  if (!defined ($curentry{'type'}))
    {
      $hostdn = "cn=$server, $basedn";
      print "dn: $hostdn\n";
      print "cn: $server\n";
      print "objectClass: top\n";
      print "objectClass: dhcpServer\n";
      print "dhcpServiceDN: $current_dn\n";
      if(grep(/FaIlOvEr/i, @use))
        {
          foreach my $fo_peer (keys %failover)
            {
              next if(scalar(@{$failover{$fo_peer}}) <= 1);
              print "dhcpStatements: failover peer $fo_peer { ",
                    join('; ', @{$failover{$fo_peer}}), "; }\n";
            }
        }
      print "\n";

      print "dn: $current_dn\n";
      print "cn: $dhcpcn\n";
      print "objectClass: top\n";
      print "objectClass: dhcpService\n";
      if (defined ($curentry{'options'}))
        {
          print "objectClass: dhcpOptions\n";
        }
      print "dhcpPrimaryDN: $hostdn\n";
      if(grep(/FaIlOvEr/i, @use) and ($second ne ''))
        {
          print "dhcpSecondaryDN: $second\n";
        }
    }
  elsif ($curentry{'type'} eq 'subnet')
    {
      print "dn: $current_dn\n";
      print "cn: " . $curentry{'ip'} . "\n";
      print "objectClass: top\n";
      print "objectClass: dhcpSubnet\n";
      if (defined ($curentry{'options'}))
        {
          print "objectClass: dhcpOptions\n";
        }
      
      print "dhcpNetMask: " . $curentry{'netmask'} . "\n";
      if (defined ($curentry{'ranges'}))
        {
          foreach $statement (@{$curentry{'ranges'}})
            {
              print "dhcpRange: $statement\n";
            }
        }
    }
  elsif ($curentry{'type'} eq 'shared-network')
    {
      print "dn: $current_dn\n";
      print "cn: " . $curentry{'descr'} . "\n";
      print "objectClass: top\n";
      print "objectClass: dhcpSharedNetwork\n";
      if (defined ($curentry{'options'}))
        {
          print "objectClass: dhcpOptions\n";
        }
    }
  elsif ($curentry{'type'} eq 'group')
    {
      print "dn: $current_dn\n";
      print "cn: group", $curentry{'idx'}, "\n";
      print "objectClass: top\n";
      print "objectClass: dhcpGroup\n";
      if (defined ($curentry{'options'}))
        {
          print "objectClass: dhcpOptions\n";
        }
    }
  elsif ($curentry{'type'} eq 'host')
    {
      print "dn: $current_dn\n";
      print "cn: " . $curentry{'host'} . "\n";
      print "objectClass: top\n";
      print "objectClass: dhcpHost\n";
      if (defined ($curentry{'options'}))
        {
          print "objectClass: dhcpOptions\n";
        }

      if (defined ($curentry{'hwaddress'}))
        {
          $curentry{'hwaddress'} =~ y/[A-Z]/[a-z]/;
          print "dhcpHWAddress: " . $curentry{'hwaddress'} . "\n";
        }
    }
  elsif ($curentry{'type'} eq 'pool')
    {
      print "dn: $current_dn\n";
      print "cn: pool", $curentry{'idx'}, "\n";
      print "objectClass: top\n";
      print "objectClass: dhcpPool\n";
      if (defined ($curentry{'options'}))
        {
          print "objectClass: dhcpOptions\n";
        }

      if (defined ($curentry{'ranges'}))
        {
          foreach $statement (@{$curentry{'ranges'}})
            {
              print "dhcpRange: $statement\n";
            }
        }
    }
  elsif ($curentry{'type'} eq 'class')
    {
      print "dn: $current_dn\n";
      print "cn: " . $curentry{'class'} . "\n";
      print "objectClass: top\n";
      print "objectClass: dhcpClass\n";
      if (defined ($curentry{'options'}))
        {
          print "objectClass: dhcpOptions\n";
        }
    }
  elsif ($curentry{'type'} eq 'subclass')
    {
      print "dn: $current_dn\n";
      print "cn: " . $curentry{'subclass'} . "\n";
      print "objectClass: top\n";
      print "objectClass: dhcpSubClass\n";
      if (defined ($curentry{'options'}))
        {
          print "objectClass: dhcpOptions\n";
        }
      print "dhcpClassData: " . $curentry{'class'} . "\n";
    }

  if (defined ($curentry{'statements'}))
    {
      foreach $statement (@{$curentry{'statements'}})
        {
          print "dhcpStatements: $statement\n";
        }
    }

  if (defined ($curentry{'options'}))
    {
      foreach $statement (@{$curentry{'options'}})
        {
          print "dhcpOption: $statement\n";
        }
    }

  print "\n";
  undef (%curentry);
}


sub parse_netmask
{
  local ($netmask) = @_;
  local ($i);

  if ((($a, $b, $c, $d) = $netmask =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) != 4)
    {
      parse_error ();
    }

  $num = (($a & 0xff) << 24) |
         (($b & 0xff) << 16) |
         (($c & 0xff) << 8) |
          ($d & 0xff);

  for ($i=1; $i<=32 && $num & (1 << (32 - $i)); $i++)
    {
    }
  $i--;

  return ($i);
}


sub parse_subnet
{
  local ($ip, $tmp, $netmask);

  print_entry () if %curentry;
    
  $ip = next_token (0);
  parse_error () if !defined ($ip);

  $tmp = next_token (1);
  parse_error () if !defined ($tmp);
  parse_error () if !($tmp eq 'netmask');

  $tmp = next_token (0);
  parse_error () if !defined ($tmp);
  $netmask = parse_netmask ($tmp);

  $tmp = next_token (0);
  parse_error () if !defined ($tmp);
  parse_error () if !($tmp eq '{');

  add_dn_to_stack ("cn=$ip");
  $curentry{'type'} = 'subnet';
  $curentry{'ip'} = $ip;
  $curentry{'netmask'} = $netmask;
  $cursubnet = $ip;
  $curcounter{$ip} = { pool  => 0, group => 0 };
}


sub parse_shared_network
{
  local ($descr, $tmp);

  print_entry () if %curentry;

  $descr = next_token (0);
  parse_error () if !defined ($descr);

  $tmp = next_token (0);
  parse_error () if !defined ($tmp);
  parse_error () if !($tmp eq '{');

  add_dn_to_stack ("cn=$descr");
  $curentry{'type'} = 'shared-network';
  $curentry{'descr'} = $descr;
}


sub parse_host
{
  local ($descr, $tmp);

  print_entry () if %curentry;

  $host = next_token (0);
  parse_error () if !defined ($host);

  $tmp = next_token (0);
  parse_error () if !defined ($tmp);
  parse_error () if !($tmp eq '{');

  add_dn_to_stack ("cn=$host");
  $curentry{'type'} = 'host';
  $curentry{'host'} = $host;
}


sub parse_group
{
  local ($descr, $tmp);

  print_entry () if %curentry;

  $tmp = next_token (0);
  parse_error () if !defined ($tmp);
  parse_error () if !($tmp eq '{');

  my $idx;
  if(exists($curcounter{$cursubnet})) {
    $idx = ++$curcounter{$cursubnet}->{'group'};
  } else {
    $idx = ++$curcounter{''}->{'group'};
  }

  add_dn_to_stack ("cn=group".$idx);
  $curentry{'type'} = 'group';
  $curentry{'idx'} = $idx;
}


sub parse_pool
{
  local ($descr, $tmp);

  print_entry () if %curentry;

  $tmp = next_token (0);
  parse_error () if !defined ($tmp);
  parse_error () if !($tmp eq '{');

  my $idx;
  if(exists($curcounter{$cursubnet})) {
    $idx = ++$curcounter{$cursubnet}->{'pool'};
  } else {
    $idx = ++$curcounter{''}->{'pool'};
  }

  add_dn_to_stack ("cn=pool".$idx);
  $curentry{'type'} = 'pool';
  $curentry{'idx'} = $idx;
}


sub parse_class
{
  local ($descr, $tmp);

  print_entry () if %curentry;

  $class = next_token (0);
  parse_error () if !defined ($class);

  $tmp = next_token (0);
  parse_error () if !defined ($tmp);
  parse_error () if !($tmp eq '{');

  $class =~ s/\"//g;
  add_dn_to_stack ("cn=$class");
  $curentry{'type'} = 'class';
  $curentry{'class'} = $class;
}


sub parse_subclass
{
  local ($descr, $tmp);

  print_entry () if %curentry;

  $class = next_token (0);
  parse_error () if !defined ($class);

  $subclass = next_token (0);
  parse_error () if !defined ($subclass);

  $tmp = next_token (0);
  parse_error () if !defined ($tmp);
  parse_error () if !($tmp eq '{');

  add_dn_to_stack ("cn=$subclass");
  $curentry{'type'} = 'subclass';
  $curentry{'class'} = $class;
  $curentry{'subclass'} = $subclass;
}


sub parse_hwaddress
{
  local ($type, $hw, $tmp);

  $type = next_token (1);
  parse_error () if !defined ($type);

  $hw = next_token (1);
  parse_error () if !defined ($hw);
  $hw =~ s/;$//;

  $curentry{'hwaddress'} = "$type $hw";
}

    
sub parse_range
{
  local ($tmp, $str);

  $str = remaining_line ();

  if (!($str eq ''))
    {
      $str =~ s/;$//;
      push (@{$curentry{'ranges'}}, $str);
    }
}


sub parse_statement
{
  local ($token) = shift;
  local ($str);

  if ($token eq 'option')
    {
      $str = remaining_line ();
      push (@{$curentry{'options'}}, $str);
    }
  elsif($token eq 'failover')
    {
      $str = remaining_line (1); # take care on block
      if($str =~ /[{]/)
        {
          my ($peername, @statements);

          parse_error() if($str !~ /^\s*peer\s+(.+?)\s+[{]\s*$/);
          parse_error() if(($peername = $1) !~ /^\"?[^\"]+\"?$/);

          #
          # failover config block found:
          # e.g. 'failover peer "some-name" {'
          #
          if(not grep(/FaIlOvEr/i, @use))
            {
              print STDERR "Warning: Failover config 'peer $peername' found!\n";
              print STDERR "         Skipping it, since failover disabled!\n";
              print STDERR "         You may try out --use=failover option.\n";
            }

          until($str =~ /[}]/ or $str eq "")
            {
                $str = remaining_line (1);
                # collect all statements, except ending '}'
                push(@statements, $str) if($str !~ /[}]/);
            }
          $failover{$peername} = [@statements];
        }
      else
        {
          #
          # pool reference to failover config is fine
          # e.g. 'failover peer "some-name";'
          #
          if(not grep(/FaIlOvEr/i, @use))
            {
              print STDERR "Warning: Failover reference '$str' found!\n";
              print STDERR "         Skipping it, since failover disabled!\n";
              print STDERR "         You may try out --use=failover option.\n";
            }
          else
            {
              push (@{$curentry{'statements'}}, $token. " " . $str);
            }
        }
    }
  elsif($token eq 'zone')
    {
      $str = $token;
      while($str !~ /}$/) {
        $str .= ' ' . next_token (0);
      }
      push (@{$curentry{'statements'}}, $str);
    }
  elsif($token =~ /^(authoritative)[;]*$/)
    {
      push (@{$curentry{'statements'}}, $1);
    }
  else
    {
      $str = $token . " " . remaining_line ();
      push (@{$curentry{'statements'}}, $str);
    }
}


my $ok = GetOptions(
    'basedn=s'      => \$basedn,
    'dhcpdn=s'      => \$dhcpdn,
    'server=s'      => \$server,
    'second=s'      => \$second,
    'conf=s'        => \$i_conf,
    'ldif=s'        => \$o_ldif,
    'use=s'         => \@use,
    'h|help|usage'  => sub { usage(0); },
);

unless($server =~ /^\w+/)
  {
    usage(1, "invalid server name '$server'");
  }
unless($basedn =~ /^\w+=[^,]+/)
  {
    usage(1, "invalid base dn '$basedn'");
  }

if($dhcpdn =~ /^cn=([^,]+)/i)
  {
    $dhcpcn = "$1";
  }
$second = '' if not defined $second;
unless($second eq '' or $second =~ /^cn=[^,]+\s*,\s*\w+=[^,]+/i)
  {
    if($second =~ /^cn=[^,]+$/i)
      {
        # relative DN 'cn=name'
        $second = "$second, $basedn";
      }
    elsif($second =~ /^\w+/)
      {
        # assume hostname only
        $second = "cn=$second, $basedn";
      }
    else
      {
        usage(1, "invalid secondary '$second'")
      }
  }

usage(1) unless($ok);

if($i_conf ne "" and -f $i_conf)
  {
    if(not open(STDIN, '<', $i_conf))
      {
        print STDERR "Error: can't open conf file '$i_conf': $!\n";
        exit(1);
      }
  }
if($o_ldif ne "")
  {
    if(-e $o_ldif)
      {
        print STDERR "Error: output ldif name '$o_ldif' already exists!\n";
        exit(1);
      }
    if(not open(STDOUT, '>', $o_ldif))
      {
        print STDERR "Error: can't open ldif file '$o_ldif': $!\n";
        exit(1);
      }
  }


print STDERR "Creating LDAP Configuration with the following options:\n";
print STDERR "\tBase DN: $basedn\n";
print STDERR "\tDHCP DN: $dhcpdn\n";
print STDERR "\tServer DN: cn=$server, $basedn\n";
print STDERR "\tSecondary DN: $second\n"
             if(grep(/FaIlOvEr/i, @use) and $second ne '');
print STDERR "\n";

my $token;
my $token_number = 0;
my $line_number = 0;
my %curentry;
my $cursubnet = '';
my %curcounter = ( '' => { pool => 0, group => 0 } );

$current_dn = "$dhcpdn";
$curentry{'descr'} = $dhcpcn;
$line = '';
%failover = ();

while (($token = next_token (1)))
  {
    if ($token eq '}')
      {
        print_entry () if %curentry;
        if($current_dn =~ /.+?,\s*${dhcpdn}$/) {
          # don't go below dhcpdn ...
          remove_dn_from_stack ();
        }
      }
    elsif ($token eq 'subnet')
      {
        parse_subnet ();
        next;
      }
    elsif ($token eq 'shared-network')
      {
        parse_shared_network ();
        next;
      }
    elsif ($token eq 'class')
      {
        parse_class ();
        next;
      }
    elsif ($token eq 'subclass')
      {
        parse_subclass ();
        next;
      }
    elsif ($token eq 'pool')
      {
        parse_pool ();
        next;
      }
    elsif ($token eq 'group')
      {
        parse_group ();
        next;
      }
    elsif ($token eq 'host')
      {
        parse_host ();
        next;
      }
    elsif ($token eq 'hardware')
      {
        parse_hwaddress ();
        next;
      }
    elsif ($token eq 'range')
      {
        parse_range ();
        next;
      }
    else
      {
        parse_statement ($token);
        next;
      }
  }

close(STDIN)  if($i_conf);
close(STDOUT) if($o_ldif);

print STDERR "Done.\n";