#!/usr/bin/perl
#Copyright (c) 2006, Midwest Connections Inc.
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without 
#modification, are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#		this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice,
#		this list of conditions and the following disclaimer in the documentation
#		and/or other materials provided with the distribution.
#    * Neither the name of the Midwest Connections Inc. nor the names of its
#		contributors may be used to endorse or promote products derived from
#		this software without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
#THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#written by Zane C. Bowers <zanecb@midwest-connections.com>

use strict;
use warnings;
use Net::LDAP;
use Getopt::Std;
use Config::Tiny;
use Term::ReadKey;
use Term::ANSIColor;
use NetAddr::IP;
use Net::LDAP::Entry;


#zLDAPhash is property of Zane C. Bowers <vvelox@vvelox.net>
#Copyright (c) 2006, Zane C. Bowers
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without 
#modification, are permitted provided that the following conditions are met:
#
#    * Redistributions of source code must retain the above copyright notice,
#		this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice,
#		this list of conditions and the following disclaimer in the documentation
#		and/or other materials provided with the distribution.
#    * Neither the name of the Zane C. Bowers nor the names of its contributors
#		may be used to endorse or promote products derived from this software
#		without specific prior written permission.
#
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
#FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
#DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
#SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
#CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
#THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
sub  zLDAPhash {
	my $mesg = $_[0]; #the object returned from a LDAP search

	#used for holding the data, before returning it
	my %data;

	#builds it
	my $entryinter=0;
	my $max = $mesg->count;
	for ( $entryinter = 0 ; $entryinter < $max ; $entryinter++ ){
        my $entry = $mesg->entry ( $entryinter );
        $data{$entry->dn}={ldap=>{dn=>$entry->dn},internal=>{changed=>0}};
        #builds a hash of attributes
#       my $attrinter=0;
        foreach my $attr ( $entry->attributes ) {
#       while (defined($entry->attributes($attrinter))) {
#               my $attr=$entry->attributes($attrinter);
                $data{$entry->dn}{ldap}{$attr}=[];

                #builds the array of values for the attribute
                my $valueinter=0;
                my @attributes=$entry->get_value($attr);
                while (defined($attributes[$valueinter])){
                        $data{$entry->dn}{ldap}{$attr}[$valueinter]=$attributes[$valueinter];
                        $valueinter++;
                };

#               $attrinter++;
        };
	};

	return %data;
};
	
sub main::HELP_MESSAGE {


	exit 1;
};

sub main::VERSION_MESSAGE {
    print "mwcDHAadd v. 1.0.4\n";
}

#used for checking if a entry exists
sub LdapEntryExists{
	my $dn=$_[0];
	my $binder=$_[1];
	my $password=$_[2];
	my $server=$_[3];
	my $port=$_[4];

	#connect to the LDAP server
	my %ldapconnection=mwcqbinder($binder, $password, $server, $port, "1");

	#search the LDAP server and return only one entry.
	my $mesg = $ldapconnection{ldap}->search(base=>$dn,filter=>'(objectclass=*)',scope=>'base');

#uncomment to get...
#Can't locate object method "count" via package "Net::LDAP::Unbind" at ./mwcLDA.pl line 76, <STDIN> line 1.
#
#it should just work...
#	$mesg = $ldapconnection{ldap}->unbind;
	
	my %hash=zLDAPhash($mesg);
	my @keys=keys(%hash);
	if (!defined($keys[0])){
		return 0;
	};

	return 1;
};

#quickly binds to a LDAP server and returns it.
sub mwcqbinder{
	my $binder=$_[0];
	my $password=$_[1];
	my $server=$_[2];
	my $port=$_[3];
	my $errorMethode=$_[4];#0 continue and return error
						   #1 exit with error and be verbose
						   #2 exit with error and be quiet

	#sets the port if it is not defined
	if (!defined($port)){
		$port="389";
	};
	
	#sets the $errorMethode if it is not defined
	if (!defined($errorMethode)){
		$errorMethode="1";
	};
	
	my %ldapconnection=();
	
	#connect to the ldap server
	$ldapconnection{ldap} = Net::LDAP->new( $server ) or $ldapconnection{status}=0;
	#checks if the status is equal to 0.
	if (defined($ldapconnection{status}) && $ldapconnection{status} == 0){
		if ($errorMethode == 0){
			$ldapconnection{LONGerror}="Could not contact the server.";
			return 1;
		};
		if ($errorMethode == 1){
			print "Could not contact the server.\n".
				"server: ".$server."\nport: ".$port."\n";			
			exit 1;
		};
		if ($errorMethode == 2){		
			exit 1;
		};
	};

	$ldapconnection{bindMesg} = $ldapconnection{ldap}->bind( $binder, password=>$password, version=>3 );
	if ($ldapconnection{bindMesg}->code) { #check for a failed bind
		if ($errorMethode == 0){
			$ldapconnection{status}=0;
			$ldapconnection{LONGerror}="Could not bind to the server.";
			return %ldapconnection;
		};
		if ($errorMethode == 1){
			print "Could not bind to the server.\nserver: ".$server."\nport: ".$port.
			"\nbinder: ".$binder."\n";
			exit 1;
		};
		if ($errorMethode == 2){
			exit 1;
		};
	}
	
	#$ldapconnection{status}=1;
	my $ldapconnectionHRef=%ldapconnection;
	#return $ldapconnectionHRef;
	return %ldapconnection;
};

sub mwc_dhcp_host_add{
	my $ldapconnection=$_[0];
	my $ip=$_[1];
	my $mac=$_[2];
	my $baseDN=$_[3];
	my $user=$_[4];
	
	my %return=();
	
	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime;
	$mon++;#perl starts it at 0
	$year+=1900;#perl starts it at 1900
	if ($mon < 10){$mon="0".$mon}; #puts in a 0 before it if it is less than 10
	
#	print "\n\n".$year.$mon.$mday."-".$hour.$min.$sec."\n";
	
	my $newEntry = Net::LDAP::Entry->new;
	
	#puts the new entry together
	$newEntry->dn("cn=".$ip.",".$baseDN);
	$newEntry->add(objectClass=>['top','dhcpHost','mwcDHCPhost'],
					cn=>$ip,
					mwcDHCPhostAuthedAs=>$user,
					dhcpHWAddress=>"ethernet ".$mac,
					dhcpStatements=>"fixed-address ".$ip,);
#					mwcDHCPhostDstamp=>$year.$mon.$mday."-".$hour.$min.$sec
#					);
	

#	print "\n".$newEntry->dn."\n";
#	print join(" ", keys(%{$newEntry->{attrs}}))."\n";
#	print join(" ", keys(%{$ldapconnection}))."\n";
#	print $ldapconnection."\n\n";

	#tells it that this will be added.
	$newEntry->changetype('add');
	
	#adds the new entry
	#my $result=$newEntry->update(${$ldapconnection}{LDAP});
	my $result=$newEntry->update($ldapconnection);
#	print join(" ", keys(%{$result}))."\n";
#	print $result->{errorMessage}."\n";
#	print $result->{resultCode}."\n";
	
	return $result;
};

#get the list of options it was ran with and do help check
$Getopt::Std::STANDARD_HELP_VERSION = 1;
my %opts=();
getopts("u:m:i:e:c:", \%opts);
#m=mac#
#i=IP#
#u=dhcp user
#e=entry
#c=config

#creates the config hash
my %config=();

#gets the ip switch
if (defined($opts{i})){
	#makes sure only the proper characters are in the IP#
	my $iptest=$opts{i};
	$iptest=~s/[0123456789]+.[0123456789]+.[0123456789]+.[0123456789]+//g;
	if (!$iptest eq ""){
		print "IP# contains improper characters.\n";
	};
	$config{ip}=$opts{i};
};

#gets the dhcp user
if (defined($opts{u})){
	#exits if ()[]*'\" found in a username
	my $usertest=$opts{u};
	$usertest=~s/[\(\)\[\]\*\\\'\"]//g; #' this is here to handle a highlighting bug in Eclipse
	if ($usertest ne $opts{u}){
		print '()[]*\'\" are not allowed in usernames.'."\n";
		exit 1;
	};	
	$config{user}=$opts{u}
}else{
	print "No username specified.\n";
	exit 1;	
};

#gets the entry to use in the config file
if (defined($opts{e})){
	$config{entry}=$opts{e}
}else{
	$config{entry}="_";
};

#gets the MAC# 
if (defined($opts{m})){
	$config{mac}=lc($opts{m});
	$config{mac}=~s/-/:/g;
	my $mac_test=$config{mac};
	$mac_test=~s/[abcdef0123456789][abcdef0123456789]:[abcdef0123456789][abcdef0123456789]:[abcdef0123456789][abcdef0123456789]:[abcdef0123456789][abcdef0123456789]:[abcdef0123456789][abcdef0123456789]:[abcdef0123456789][abcdef0123456789]//g;
	if ($mac_test ne ""){
		print $opts{m}." appears to contain improper characters or formating.\n";
		exit 1;
	};
}else{
	print "No MAC# specified.\n";
	exit 1;
};

#gets what config file to use
if (defined($opts{c})){
	$config{file}=$opts{c};
}else{
	$config{file}=$ENV{HOME}."/.mwcDHArc"
};

#makes sure the config file exists
if (! -f $config{file}){
	print "Config file does not exist. ".$config{file}."\n";
};

#loads INI file.
my $rc=Config::Tiny->new();
$rc=Config::Tiny->read($config{file});

#reels the INI vars into $config
my @INIvars=("LDAPserver","LDAPuser","baseDN","LDAPpassword","LDAPport","CIDR","skipIPs");
my @INIvars_migrate=@INIvars;#we need to add ENVpass to the list, but it is not required
push(@INIvars_migrate,"ENVpassword");
my $count=0;
while (defined($INIvars_migrate[$count])){
	if (defined($rc->{_}->{$INIvars_migrate[$count]})){
		$config{$INIvars_migrate[$count]}=$rc->{_}->{$INIvars_migrate[$count]};
	};
	$count++;
};

#reels entry specific vars in
if ($config{entry} ne "_"){
	$count=0;
	while (defined($INIvars[$count])){
		if (defined($rc->{$config{entry}}->{$INIvars[$count]})){
			$config{$INIvars[$count]}=$rc->{$config{entry}}->{$INIvars[$count]};
		};
		$count++;
	};
};

#sets the port if it is undefined
if (!defined($config{LDAPport})){
	$config{LDAPport}="389";
};

#gets the password from the enviroment if needed.
if (defined($config{ENVpassword})){
	$config{LDAPpassword}=$ENV{LDAPpassword};
}else{
	#gets the password if none is set.
	if (!defined($config{LDAPpassword})){
		ReadMode('noecho');
		print $config{LDAPuser}."\nLDAP password:";
		$config{LDAPpassword}=ReadLine(0);
		chomp($config{LDAPpassword});
		print "\n";
	};
};

#exists if any of the INIvars are not defined
$count=0;
while (defined($INIvars[$count])){
	if (!defined($config{$INIvars[$count]})){
		print $INIvars[$count]." is not defined in ".$config{file}."\n";
		exit 1;
	};
	$count++;
};


#Breaks the skip list down into a hash. A hash is used for easier check if it all read exists or not.
#It also makes sure there are not any characters in there that should not be.
my %skipIPs=();
$count=0;
my @skipIPs_array=split(/,/,$config{skipIPs});
while (defined($skipIPs_array[$count])){
	my $skipIP_test=$skipIPs_array[$count];
	$skipIP_test=~s/[0123456789]+.[0123456789]+.[0123456789]+.[0123456789]+//g;
	if ($skipIP_test ne ""){
		print "'".$skipIPs_array[$count]."' in skipIPs appears to contain illegal characters.";
	};
	$skipIPs{$skipIPs_array[$count]}="";
	$count++;
};

#connect to the LDAP server
my %ldapconnection=mwcqbinder($config{LDAPuser}, $config{LDAPpassword},
							$config{LDAPserver}, $config{LDAPport}, "1");
							
my $ldapc=$ldapconnection{ldap};

#search the LDAP server and return only one entry.
my $mesg = $ldapconnection{ldap}->search(base=>$config{baseDN},filter=>'(objectclass=*)',scope=>'sub');

#generates zLDAPhash out of the returned message.
my %LDAPhash=zLDAPhash($mesg);

my $ips="";
if ($config{CIDR} ne "auto"){
	#creates the list of IPs
	$ips = new NetAddr::IP($config{CIDR});
}else{
	if (!defined($LDAPhash{$config{baseDN}}{ldap}{cn}[0]) ||
		!defined($LDAPhash{$config{baseDN}}{ldap}{dhcpNetMask}[0])){
		print "baseDN: ".$config{baseDN}."\n lacks either a cn or dhcpNetMask attribute.\n";
	};
	$ips=new NetAddr::IP($LDAPhash{$config{baseDN}}{ldap}{cn}[0]."/".$LDAPhash{$config{baseDN}}{ldap}{dhcpNetMask}[0]);
};


#This adds it if the IP# is manually specified.
if (defined($config{ip})){
	
	#checks if it all ready exists... and exit if it does.
	if(defined($LDAPhash{"cn=".$config{ip}.",".$config{baseDN}})){
		print "cn=".$config{ip}.",".$config{baseDN}."\nAll ready exists.\n";
		exit 1;
	};
	
	#exits if request IP# is in the skipIPs hash
	if (defined($skipIPs{$config{ip}})){
		print $config{ip}." was found in the skipIPs list.\n";

		exit 1;
	};
	
	#this will be used for testing
	my $ip_test=new NetAddr::IP($config{ip}."/32");

	#exits if the IP is not found in the range
	if (defined($config{ip})){

		if (!$ips->contains($ip_test)){
			print $config{CIDR}." does not contain ".$config{ip}."\n";

			exit 1;
		};
	};

	#exits if it is less than first address
	if ($ip_test < $ips->first() ){
		print $config{ip}." is before the first useable address, ".$ips->first().", in ".$config{CIDR}."\n";
		exit 1;
	}elsif($ip_test > $ips->last()){
		print $config{ip}." is after the first useable address, ".$ips->last().", in ".$config{CIDR}."\n";
		exit 1;
	};
	
	my $results=mwc_dhcp_host_add(%ldapconnection,$config{ip},$config{mac},$config{baseDN},$config{user});
	if ($results->{resultCode}==0){
		print "Succesffully added...\nIP#: ".$config{ip}."\nMAC#: ".$config{mac}.
				"\nuser: ".$config{user}."\n";
		exit 0;
	}else{
		print "resultCode: ".$results->{resultCode}."\n".$results->{errorMessage}."\n";	
		exit 1;
	};
};

#auto matically allocates it if not told what to use.
if (!defined($config{ip})){
	#runs through the list finding a open address. When it finds one it will try to create the LDAP entry.
	$count=0;
	while (defined($ips->[$count])){
		my ($ip_number)=split(/\// ,$ips->[$count]);
		if(!defined($skipIPs{$ip_number})){
			#checks if it does not exist... adds it if it does not
			if(!defined($LDAPhash{"cn=".$ip_number.",".$config{baseDN}})){
				#print $ip_number."\n";
				my $results=mwc_dhcp_host_add($ldapc,$ip_number,$config{mac},$config{baseDN},$config{user});
				if ($results->{resultCode}==0){
					print "Succesffully added...\nIP#: ".$ip_number."\nMAC#: ".$config{mac}.
						"\nuser: ".$config{user}."\n";
					exit 0;
				}
			};
		};
		$count++;
	};
};

#-----------------------------------------------------------
# POD documentation section
#-----------------------------------------------------------

=head1 NAME

mwcDHAadd - adds a DHCP LDAP entry.

=head1 SYNPOSIS

mwcDHAadd {B<-i> IP#|B<-u> user} B<-m> MAC# [B<-c> config file] [B<-e> entry]

=head1 OPTIONS


=head2 -i IP#

This is the IP# for a entry being worked on.

=head2 -m MAC#

This is the MAC# for a entry being worked on.

=head2 -u user

This is a user that is currently being worked on.

=head2 -c config file

This is the ini file that settings will be read from. The default is ~/.mwcDHA

=head2 -c entry

This is the entry to use in the config file.

=head1 CONFIG FILE

The config file is a .ini file. The default config file is F<~/.mwcDHArc>. The entry 
over rides any thing found in the root for the .ini file. This file is shared between
mwcDHAadd, mwcDHAls, and mwcDHArm.

=item LDAPserver

This is the IP# of the server that will be connected to.

=item baseDN

This is the DN that the users will be put into.

=item LDAPuser

This is the bind that will be made to the LDAP server.

=item LDAPpassword

This is the password that will be used for connecting to the LDAP server. This this is left out,
it will prompt for a password.

=item LDAPport

This is the port that will be used for connecting 

=item CIDR

This is the CIDR for IP#s on subnet being worked on. If set to 'auto', it will
look at baseDN to figure out what it is.

=item ENVpassword

If this is defined, it will check for the presence of a LDAPpassword enviromental variable.

=item skipIPs

This is a camma seperated list of IP#s to skip over.

=item Example:
	
	LDAPserver=192.168.50.99
	;a freaking comment
	basedn=cn=192.168.0.0,cn=bufo,ou=servers,ou=dhcp,ou=network,dc=fu,dc=bar
	LDAPuser=cn=bufo americanus,ou=employees,dc=fu,dc=bar
	LDAPpassword=somethingannoyinglyeasytofreakingremember
	
	[cognatus]
	basedn=cn=192.168.0.0,cn=cognatus,ou=servers,ou=dhcp,ou=network,dc=fu,dc=bar
	CIDR=192.168.0.0/24
	skipIPs=192.168.0.1
	
	[marinus]
	basedn=cn=192.168.1.0,cn=marinus,ou=servers,ou=dhcp,ou=network,dc=fu,dc=bar
	CIDR=auto
	skipIPs=192.168.1.1

=head1 LDAP notes

See http://cpan.org/authors/id/M/MW/MWCZANECB/ for the required schema
and more info on it.

=head1 AUTHOR

Copyright (c) 2006, Midwest Connections Inc.

All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
    * Neither the name of the Midwest Connections Inc. nor the names of its
     contributors may be used to endorse or promote products derived from
     this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

written by Zane C. Bowers <zanecb@midwest-connections.com>

=head1 SCRIPT CATEGORIES

Unix/System_administration

=head1 OSNAMES

any

=head1 README

mwcDHAadd - adds a DHCP LDAP entry. This is for use with the other mwcDHCP tools and ISC
DHCP LDAP patch.

=head1 CHANGE LOG

=head 2006-10-26

=item version 1.0.4

Fixed a small problem with ENVpassword after uploading it CPAN. Bumping version and reuploading.

=item version 1.0.3

Added in enviromental based password.

=head2 2006-10-16

=item version 1.0.2

Decided it was time for a version bump.

=item POD

Removed the schema from it and made a special POD file for it.

=item auto CIDR

It can now automatically figure out what it's CIDR is.

=head2 2006-10-12

=item version 1.0.1

Bump version because of issues with asking for a password.

=item CHANGELOG

Correct the date before this. It had 2007 instead of 2006.

=head2 2006-09-27

=item version 1.0.0

I am now considering it done. Pod could use a bit of cleaning and --help needs added,
but it appears to be perfectly fine in every function.

=head2 2006-09-26

=item auto

This now works.

=item cleanup

Cleaned up some of the code and output.

=head2 2006-09-14

=item -a

The action switch has been removed. There are going to be similar, but seperate scripts for
listing, removing, and getting.

=head1 TODO

=item more automation

Move the CIDR out of config file and into LDAP.

=item user testing

Test if the user should work on this server and make sure they exist.

=cut

#-----------------------------------------------------------
# End of POD documentation
#-----------------------------------------------------------
