#!/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 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 "mwcDHAls 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;
};

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

#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 or formatting.\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}
};

#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.\n";
		exit 1;
	};
};

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

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

#gets wether it should ask or not
if (defined($opts{p})){
	$config{pretty}="true";
};

#gets if it should operate in semi-match mode or not
if (defined($opts{s})){
	$config{semiMatch}="true";
};

#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");

#this builds the filter
my $semi="";
if (defined($config{semiMatch})){$semi="*"};
my $filter="(&(objectClass=mwcDHCPhost)(objectClass=dhcpHost))";
#if (defined($config{ip})){$filter.="(dhcpStatements=fixed-address ".$config{ip}.")";};
if (defined($config{ip})){$filter="(&(dhcpStatements=fixed-address ".$config{ip}.")".$filter.")";};
if (defined($config{user})){$filter="(&(mwcDHCPhostAuthedAs=".$semi.$config{user}.$semi.")".$filter.")";};
if (defined($config{mac})){$filter="(&(dhcpHWAddress=ethernet ".$config{mac}.")".$filter.")";};

#print $filter."\n";

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

#print join("\n",keys(%{$mesg}))."\n";
#print $mesg->{resultCode}."\n";

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

#get a array of returned DNs
my @DN_array=keys(%LDAPhash);

#used for counting through the list
$count=0;

#print the header
if (defined($config{pretty})){
	print "     MAC#         ,       IP#       , user\n";
	#     "00:11:22:33:44:55 , 255.255.255.255.255 , 
}else{
	print "MAC#,IP#,user\n";
};
while(defined($DN_array[$count])){
	my $mac=$LDAPhash{$DN_array[$count]}{ldap}{dhcpHWAddress}[0];
	$mac=~s/ethernet //g;
	
	#gets what dhcpStatements to use
	my $dhcpStatements_count=0;
	my $ip="";
	while($LDAPhash{$DN_array[$count]}{ldap}{dhcpStatements}[$dhcpStatements_count]){
		my $dhcpStatements_test=$LDAPhash{$DN_array[$count]}{ldap}{dhcpStatements}[$dhcpStatements_count];
		#uses this IP# if it matches.
		if($dhcpStatements_test=~s/fixed-address //g){
			$ip=$LDAPhash{$DN_array[$count]}{ldap}{dhcpStatements}[$dhcpStatements_count];
			$ip=~s/fixed-address //g;
		};
		$dhcpStatements_count++;
	};

	my $user=$LDAPhash{$DN_array[$count]}{ldap}{mwcDHCPhostAuthedAs}[0];
	
	if (defined($config{pretty})){
		printf $mac." , %15s , ".$user."\n", $ip;
		#      "00:11:22:33:44:55 , 255.255.255.255.255 , 
	}else{
		print $mac.",".$ip.",".$user."\n";
	};
	$count++;
};

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

=head1 NAME

mwcDHAls -  list DHCP LDAP entries.

=head1 SYNPOSIS

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

=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.

=head2 -a

Ask if it should remove it.

=head2 -p

Pretty print.

=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

mwcDHAls - list DHCP LDAP entries. This is for use with the other mwcDHCP tools and ISC
DHCP LDAP patch.

=head1 CHANGE LOG

=item version 1.0.4

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

=head 2006-10-24

=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

Cleaned up the LDAP section. I broke it into a seperate file.

=item clean up

Removed $ips and NetAddr::IP, because they are only needed in mwcDHAadd. They
found there way in when it was copied from it.

=head2 2006-10-12

=item version 1.0.1

Fixed a issue with it asking for a password.

=head2 2006-09-27

=item version 1.0.0

I am considering it done.

=item started

Did a quick copy from mwcDHArm and did a bit of renaming of renaming and etc.

=cut

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