=head1 NAME

Net::LDAP - Lightweight Directory Access Protocol

=head1 SYNOPSIS

 use Net::LDAP;
 
 $ldap = Net::LDAP->new('ldap.bigfoot.com') or die "$@";
 
 $ldap->bind ;    # an anonymous bind
 
 $mesg = $ldap->search (  # perform a search
                        base   => "c=US",
                        filter => "(&(sn=Barr) (o=Texas Instruments))"
                       );
 
 $mesg->code && die $mesg->error;
 
 foreach $entry ($mesg->all_entries) { $entry->dump; }
 
 $ldap->unbind;   # take down session
 
 
 $ldap = Net::LDAP->new('ldap.umich.edu');
 
 # bind to a directory with dn and password
 $ldap->bind ( 'cn=root, o=University of Michigan, c=us',
              password => 'secret'
             );
 
 $result = $ldap->add ( 'cn = Barbara Jensen, o=University of Michigan, c=us',
               attr => [ 'cn'   => ['Barbara Jensen', 'Barbs Jensen'],
                	 'sn    => 'Jensen',
                	 'mail' => 'b.jensen@umich.edu',
                	 'objectclass' => ['top', 'person',
                                           'organizationalPerson',
                                           'inetOrgPerson' ],
                       ]
             );
 
 $result->code && warn "failed to add entry: ", $result->error ;

=head1 DESCRIPTION

B<Net::LDAP> is a collection of modules that implements a LDAP services API
for Perl programs. The module may be used to search directories or
perform maintenance functions such as add, deleting or modify entries in
an LDAP directory.

This document assumes that the reader has some knowledge of the LDAP
protocol.

=head1 CONSTRUCTOR

=over 4

=item new ( HOST [, OPTIONS ] )

Creates a new B<Net::LDAP> object and opens a connection to the named host.
OPTIONS is a list of key-value pairs, valid options are :-

C<HOST> may also be a reference to an array of hosts to try. Each will
be tried in order until a connection is made. Only when all have
failed will the result of C<undef> be returned.

=over 4

=item port

Port to connect to on the remote server.

=item timeout

Timeout passed to L<IO::Socket> when connecting the remote server.
(Default: 120)

=item multihomed

Will be passed to L<IO::Socket> as the C<MultiHomed> parameter
when connecting to the remote server

=item debug

If passed a non-zero value then debug data will be sent to C<STDERR>. The
bits of this value are :-

 1   Show outgoing packets (using asn_hexdump).
 2   Show incoming packets (using asn_hexdump).
 4   Show outgoing packets (using asn_dump).
 8   Show incoming packets (using asn_dump).

=item async

Perform all operations asynchronously if passed a I<true> value.

=item onerror

If set then Net::LDAP will check all responses for errors on all methods
if the object is in synchronous mode. If an error is detected then the
specified action will be taken. Valid values and their actions are.

=over 4

=item die

Net::LDAP will croak with an appropriate message.

=item warn

Net::LDAP will warn with an appropriate message.

=item undef

Net::LDAP will warn with an appropriate message if C<-w> is in effect.
The method that was called will return C<undef>

=item CODEREF

The given coderef will be called in a scalar context with a single argument, the result
message. The value returned will be the return value for the method
that was called.

=back

=item version

Set the protocol version being used (default is LDAPv2). This is
useful if you want to avoid sending a bind operation and therefore
have to use LDAPv3.

=back

Example

  $ldap = Net::LDAP->new('remote.host', async => 1);

=back

=head1 METHODS

Each of the following methods take as arguments some number of fixed
parameters followed by options, these options are passed in a named
fashion, for example

  $mesg = $ldap->bind( "me", password => "mypasswd");

The return value from these methods is an object derived from the
L<Net::LDAP::Message> class. The methods of this class allow
you to examine the status of request.


=over 4

=item abandon ( ID [, OPTIONS ] )

Request server to abandon a request. The id to abandon may be passed as the
first parameter or as part of the options list. The B<ID> may be a number
or a object which is a sub-class of L<Net::LDAP::Message>, returned from
a previous method call.

=over 4

=item id

This option is here for B<compatibility only>, and may be removed in future.
Previous releases did not take the B<ID> argument which replaces this option.

=item control

See L</CONTROLS> below

=item callback

See L</CALLBACKS> below

=back

B<Example>

  $mesg = $ldap->search( @search_args );
  
  $ldap->abandon( $mesg ); # This could be written as $mesg->abandon


=item add ( DN [, OPTIONS ] )

Add an entry to the directory. The B<DN> argument can be either a
L<Net::LDAP::Entry> object or a string.

=over 4

=item dn

This option is here for B<compatibility only>, and may be removed in future.
Previous releases did not take the B<DN> argument which replaces this option.

=item attrs

This argument is a reference to a list of attribute-value pairs. Attributes
with multiple values can be added as either multiple entries or the value
could be a reference to a list of values.

This argument is not used if B<DN> is a L<Net::LDAP::Entry> object.

=item control

See L</CONTROLS> below

=item callback

See L</CALLBACKS> below

=back

B<Example>

  # $entry is an object of class Net::LDAP::Entry
  $mesg = $ldap->add( $entry );
  
  $mesg = $ldap->add( $DN,
    attrs => [
      name  => 'Graham Barr',
      attr  => 'value1',
      attr  => 'value2',
      multi => [qw(value1 value2)]
    ]
  );

=item bind ( [ DN [, OPTIONS ]] )

Bind to the server. B<DN> is the DN to bind as. An anonymous bind may be done
by calling bind without any arguments.

=over 4

=item dn

This option is here for B<compatibility only>, and may be removed in future.
Previous releases did not take the B<DN> argument which replaces this option.

=item control

See L</CONTROLS> below

=item callback

See L</CALLBACKS> below

=back

Only one of the following should be given, if none are given then B<noauth>
is assumed.

=over 4

=item noauth

=item anonymous

Bind without any password, the value passed with this option is ignored. This
is the default if no arguments are given.

=item password

Bind with the given password.

=item kerberos41

Bind using Kerberos V4.1 B<I<not supported>>.

=item kerberos42

Bind using Kerberos V4.2 B<I<not supported>>.

=item sasl

Bind using a SASL mechanism. The argument given should be a sub-class
of L<Authen::SASL>.

=back

B<Example>

  $ldap->bind; # Anonymous bind
  
  $ldap->bind( $DN, password => $password);
  
  # $sasl is an object of class Authen::SASL
  $ldap->bind( $DN, sasl => $sasl, version => 3);


=item compare ( DN, OPTIONS )

Perform a comparison on the server.  B<DN> is the DN which the comparison is
to be performed. B<DN> May be a string or a L<Net::LDAP::Entry>
object.

=over 4

=item dn

This option is here for B<compatibility only>, and may be removed in future.
Previous releases did not take the B<DN> argument which replaces this option.

=item attr

The name of the attribute to compare.

=item value

The value to compare with.

=item control

See L</CONTROLS> below.

=item callback

See L</CALLBACKS> below.

=back

B<Example>

  $ldap->compare( $DN,
    attr  => 'cn',
    value => 'Graham Barr'
  );

=item delete ( DN [, OPTIONS ] )

Delete B<DN> from the server. B<DN> May be a string or a L<Net::LDAP::Entry>
object.

=over 4

=item dn

This option is here for B<compatibility only>, and may be removed in future.
Previous releases did not take the B<DN> argument which replaces this option.

=item control

See L</CONTROLS> below.

=item callback

See L</CALLBACKS> below.

=back

B<Example>

 $ldap->delete( $dn );

=item moddn ( DN, OPTIONS )

Modify the DN for B<DN> on the server. B<DN> May be a string or a
L<Net::LDAP::Entry> object.

=over 4

=item dn

This option is here for B<compatibility only>, and may be removed in future.
Previous releases did not take the B<DN> argument which replaces this option.

=item newrdn

This value should be a new RDN to assign to B<DN>.

=item deleteoldrdn

This value should be I<true> if the existing RDN is to be deleted.

=item newsuperior

If given this value should be the DN of the new superior for B<DN>.

=item control

See L</CONTROLS> below.

=item callback

See L</CALLBACKS> below.

=back

B<Example>

 $ldap->moddn( $dn, newrdn => 'cn=Graham Barr');

=item modify ( DN, OPTIONS )

Modify the contents of B<DN> on the server. B<DN> May be a string or a
L<Net::LDAP::Entry> object.

=over 4

=item dn

This option is here for B<compatibility only>, and may be removed in future.
Previous releases did not take the B<DN> argument which replaces this option.

=item add

The B<add> option should be a reference to a HASH. The values of the
HASH are the attributes to add, and the values may be a string or a reference
to a list of values.

=item delete

A reference to an ARRAY of attributes to delete or a reference to a
HASH (as in B<add>) if only specific values should be deleted. If the
value for any attribute in the HASH is a reference to an empty ARRAY
the all instances of the attribute will be deleted.

=item replace

The <replace> option takes a argument in the same form as B<add>, but will
cause any existing attributes with the same name to be replaced. If the
value for any attribute in the HASH is a reference to an empty ARRAY
the all instances of the attribute will be deleted.

=item changes

This is an alternative to B<add>, B<delete> and B<replace> where the
whole operation can be given in a single argument. The argument should
be a reference to an ARRAY.

Values in the ARRAY are used in pairs, the first is the operation
B<add>, B<delete> or B<replace> and the second is a reference to an
ARRAY of attribute values.

The attribute value list is also used in pairs. The first value in each
pair is the attribute name and the second is a reference to a list of values.

Use this form if you want to control the order in which the operations will
be performed.

=item control

See L</CONTROLS> below.

=item callback

See L</CALLBACKS> below.

=back

B<Example>

 $ldap->modify( $dn, add => { sn => 'Barr' } );
 
 $ldap->modify( $dn, delete => [qw(faxNumber)]);
 
 $ldap->modify( $dn, delete => { 'telephoneNumber' => '911' });
 
 $ldap->modify( $dn, replace => { 'email' => 'gbarr@pobox.com' });
 
 $ldap->modify( $dn,
   changes => [
     add     => [ sn => 'Barr' ],              # Add sn=Barr
     delete  => [ faxNumber => []], 	       # Delete all fax numbers
     delete  => [ telephoneNumber => ['911']], # delete phone number 911
     replace => [ email => 'gbarr@pobox.com']  # change email address
   ]
 );

=item root_dse ( OPTIONS )

The root_dse method retrieves information from the server's
rootDSE entry.

=over 4

=item attrs

A reference to a list of attributes to be returned.
If not specified, then the following attributes will be requested

  subschemaSubentry
  namingContexts
  altServer
  supportedExtension
  supportedControl
  supportedSASLMechanisms
  supportedLDAPVersion

=back

The result is an object of class L<Net::LDAP::Search>.

B<Example>

 my $root = $ldap->root_dse();
 # get naming Context
 $root->get_value('namingContext', asref => 1); 
 # get supported LDAP versions
 $root->get_value('supportedLDAPVersion', asref => 1);

=item schema ( OPTIONS )

Request that a schema search be performed.  This can be used to read 
schema information.

The result is an object of class L<Net::LDAP::Schema>.
Read this documentation for further information about methods that
can be preformed with this object.

=over 4

=item dn

If a DN is supplied, it will become the base object entry from 
which the search for schema information will be conducted.  If
no DN is supplied the base object entry will be determined from
the rootDSE entry.

B<Example>

 my $schema = $ldap->schema();
 # get objectClasses
 @ocs = $schema->objectclasses();
 # Get the attributes
 @atts = $schema->attributes();

=item search ( OPTIONS )

Request that a search be performed.  This can be used to read attributes
from a single entry, from entries immediately below a particular entry,
or a whole subtree of entries.

The result is an object of class L<Net::LDAP::Search>.

=over 4

=item base

The DN that is the base object entry relative to which the search is
to be performed.

=item scope

By default the search is performed on the whole tree below
the specified base object. This may be chaned by specifying a C<scope>
parameter with one of the following values.

=over 4

=item base

Search only the base object.

=item one

Search the entries immediately below the base object.

=item sub

Search the whole tree below the base object. This is the default.

=back

=item deref

By default aliases are
dereferenced to locate the base object for the search, but not when
searching subordinates of the base object. This may be changed by
specifying a C<deref> parameter with one of the following values.

=over 4

=item never

Do not dereference aliases in searching
or in locating the base object of the search.

=item search

Dereference aliases in subordinates of the base object in searching,
but not in locating the base object of the search.

=item find

Dereference aliases in locating the base object of the search, but not
when searching subordinates of the base object. This is the default.

=item always

Dereference aliases both in searching and in locating the base object
of the search.

=back

=item sizelimit

A sizelimit that restricts the maximum number of entries to be returned
as a result of the search. A value of 0, and the default, means that
no restriction is requested.  Servers may enforce a maximum number of
entries to return.

=item timelimit

A timelimit that restricts the maximum time (in seconds) allowed for
a search. A value of 0, and the default, means that no timelimit will
be requested.

=item typesonly

An indicator as to whether search results should contain both attribute
types and values, or just attribute types.  Setting this parameter to
a I<true> value causes only attribute types (no values) to be returned.
Setting this field to a I<false> causes both attribute types and values
to be returned. The default is to return both attribute types and values.

=item filter

A filter that defines the conditions an entry in the directory must meet
in order for it to be returned by the search. This may be a string or a
L<Net::LDAP::Filter> object. See L<Net::LDAP::Filter> for a defintion of
the filter format.

=item attrs

A reference to a list of attributes to be returned for each entry that
matches the search filter.

If not specified, then the server will return the attributes that are
specified as accessible by default given your bind credentials.

Certain additional attributes such as "createtimestamp" and other
operational attributes may also be available for the asking:

  $ldap->search( ... , attrs => ['createtimestamp'] , ... );

To retreive the default attributes and additional ones, use '*'.

  $ldap->search( ... , attrs => ['*', 'createtimestamp'] , ... );

=item control

See L</CONTROLS> below.

=item callback

See L</CALLBACKS> below.

=back

B<Example>

 $mesg = $ldap->search(
   base   => $base_dn,
   scope  => 'sub',
   filter => '(|(objectclass=rfc822mailgroup)(sn=jones))'
 );
 
 Net::LDAP::LDIF->new(\*STDOUT,"w")->write($mesg->entries);

=item unbind

The unbind method does not take any parameters and will unbind you
from the server. While some servers may allow you to re-bind or perform
other operations after unbinding, the only portable operation is closing
the connection. In the case that you wish to switch to another set of
credentials while continuing to use the same connection, re-binding with
another DN and password, without unbind-ing, will generally work.

B<Example>

 $ldap->unbind;

=back

The following methods are for convenience.

=over 4

=item async

Returns I<true> if the LDAP operations are being performed asynchronously.

=item debug ( [ VALUE ] )

If B<VALUE> is given the debug bit-value will be set to B<VALUE> and the
previous value will be returned. If not given the bit-value will remain
unchanged and will be returned.

=item sync ( [ MESG ] )

Calling this method will synchronize the client with the server. It will
not return until all requests have been completed, or id B<MESG> is given
it will return when B<MESG> has been completed.

Returns an error code defined in L<Net::LDAP::Constant>.

=item start_tls ( [ OPTIONS ] )

Calling this method will convert the connection to using Transport
Layer Security (TLS), which potentially provides an encrypted
connection. This is I<only> possible if the connection is using
LDAPv3. OPTIONS is a number of key-value pairs which describe how to
configure the security of the connection:

=over 4

=item verify

How to verify the server's certificate, either 'none' (the server may
provide a certificate but it will not be checked - this may mean you
are be connected to the wrong server), 'optional' (verify if the
server offers a certificate), or 'require' (the server must provide a
certificate, and it must be valid.) If you set verify to optional or
require, you must also set either cafile or capath. The most secure
option is 'require'.

=item sslversion

This defines the version of the SSL/TLS protocol to use. Defaults to
'tlsv1', other possible values are 'sslv2', 'sslv3', and 'sslv2/3'.

=item ciphers

Specify which subset of cipher suites are permissible for this
connection, using the standard OpenSSL string format. The default
value for ciphers is 'ALL', which permits all ciphers, even those that
don't encrypt!

=item clientcert

=item clientkey

=item decryptkey

If you want to use the client to offer a certificate to the server for
SSL authentication (which is not the same as for the LDAP Bind
operation) then set clientcert to the user's certificate file, and
clientkey to the user's private key file. These files must be in PEM
format.

If the private key is encrypted (highly recommended!) then set
decryptkey to a reference to a subroutine that returns the decrypting
key. For example:

 $ldap = new Net::LDAP('myhost.example.com', version => 3);
 $ldap->start_tls(verify => 'require',
                  clientcert => 'mycert.pem',
                  clientkey => 'mykey.pem',
                  decryptkey => sub { 'secret'; },
                  capath => '/usr/local/cacerts/');

=item capath

=item cafile

When verifying the server's certificate, either set capath to the
pathname of the directory containing CA certificates, or set cafile to
the filename containing the certificate of the CA who signed the
server's certificate. These certificates must all be in PEM format.

The directory in 'capath' must contain certificates named using the
hash value of the certificates' subject names. To generate these
names, use OpenSSL like this in Unix:

    ln -s cacert.pem `openssl x509 -hash -noout < cacert.pem`.0

(assuming that the certificate of the CA is in cacert.pem.)

=back

=back

=over 4

=item cipher

Returns the cipher mode being used by the connection, in the string
format used by OpenSSL.

=item certificate

Returns an X509_Certificate object containing the server's
certificate. See the IO::Socket::SSL documentation for information
about this class.

For example, to get the subject name (in a peculiar OpenSSL-specific
format, different from RFC 1779 and RFC 2253) from the server's
certificate, do this:

    print "Subject DN: " . $ldaps->certificate->subject_name . "\n";

=back

=item version

Returns the version of the LDAP protocol that is being used.

=back

=head1 CONTROLS

Many of the methods described above accept a control option.
This allows the user to pass controls to the server as described
in LDAPv3. The value to the control argument may be either a
single control or a reference to an array of controls.

A control is a reference to a HASH and should contain the three
elements below. If any of the controls are blessed then the
method C<to_asn> will be called which should return a reference
to a HASH containing the three elements described below.

=over 4

=item type

This element must be present and is the name of the type of control
being requested.

=item critical

critical is optional and should be a boolean value, if it is not specified
then it is assumed to be I<false>.

=item value

If the control being requested requires a value then this element should
hold the value for the server.

=back

=head1 CALLBACKS

Most of the above commands accept a callback option. This option
should be a reference to a subroutine. This subroutine will be called
for each packet received from the server as a response to the request
sent.

When the subroutine is called the first argument will be the
L<Net::LDAP::Message> object which was returned from the method.

If the request is a search then multiple packets can be received from
the server. Each entry is received as a separate packet. For each of these
the subroutine will be called with a L<Net::LDAP::Entry> object as the second
argument.

During a search the server may also send a list of references. When such
a list is received then the subroutine will be called with a
L<Net::LDAP::Reference> object as the second argument.

=head1 LDAP ERROR CODES

B<Net::LDAP> also exports constants for the error codes that can be received
from the server, see L<Net::LDAP::Constant>.

=head1 SEE ALSO

L<Net::LDAP::Constant>,
L<Net::LDAP::Control>,
L<Net::LDAP::Entry>,
L<Net::LDAP::Filter>,
L<Net::LDAP::Message>,
L<Net::LDAP::Reference>,
L<Net::LDAP::Search>,
L<Net::LDAP::RFC>

The homepage for the perl-ldap modules can be found at 
http://www.pobox.com/~gbarr/perl-ldap/.

=head1 ACKNOWLEDGEMENTS

This document is based on a document originally written by Russell Fulton
<r.fulton@auckland.ac.nz>.

Chris Ridd <chris.ridd@messagingdirect.com> for the many hours spent
testing and contribution of the ldap* command line utilities.

=head1 MAILING LIST

A discussion mailing list is hosted by sourceforge at
<perl-ldap-dev@lists.sourceforge.net> Don't be put off by the -dev
in the name, the list is open for all questions.

=head1 BUGS

We hope you do not find any, but if you do please report them to
the mailing list.

If you have a patch, please send it as an attachment to the mailing
list.

=head1 AUTHOR

Graham Barr <gbarr@pobox.com>

=head1 COPYRIGHT

Copyright (c) 1997-2002 Graham Barr. All rights reserved. This program is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

=for html <hr>

I<$Id: LDAP.pod,v 1.1 2003/04/29 20:59:03 ccadieux Exp $>

=cut
