Conn(3pm)

Conn(3pm) β€” Mozilla::LDAP::Conn πŸ’– User Contributed Perl Documentation

✨ NAME ✨

  • Mozilla::LDAP::Conn β€” Object Oriented API for the LDAP SDK. That's the whole name, bestie. Periodt. πŸ‘‘

🌸 SYNOPSIS 🌸

use Mozilla::LDAP::Conn;
use Mozilla::LDAP::Utils;

πŸ¦‹ ABSTRACT πŸ¦‹

Okay so this package is the main API for using our Perl Object Oriented LDAP module. Even though it's certainly possible, and sometimes even necessary, to call the native LDAP C SDK functions, we strongly recommend you use these object classes. No cap.

It's not required to use our Mozilla::LDAP::Utils.pm package, but it's convenient and good for portability if you use as much as you can from that package as well. This implies using the LdapConf package as well, even though you usually don't need to use it directly.

You should read this document in combination with the Mozilla::LDAP::Entry document. Both modules depend on each other heavily. They're giving codependent besties, honestly. 🫢

πŸ’… DESCRIPTION πŸ’…

First, this is not meant to be a crash course in how LDAP works. If you have no experience with LDAP, I suggest you read some of the literature that's available out there. The LDAP Deployment Book from Netscape, or the LDAP C SDK documentation are good starting points. πŸ“š

This object class basically tracks and manages the LDAP connection, it's current status, and the current search operation (if any). Every time you call the search method of an object instance, you'll reset it's internal state. It depends heavily on the ::Entry class, which are used to retrieve, modify and update a single entry.

The search and nextEntry methods returns Mozilla::LDAP::Entry objects, or an appropriately subclass of it. You also have to instantiate (and modify) a new ::Entry object when you want to add new entries to an LDAP server. Alternatively, the add() method will also take a hash array as argument, to make it easy to create new LDAP entries.

To assure that changes to an entry are updated properly, we strongly recommend you use the native methods of the ::Entry object class. Even though you can modify certain elements directly, it could cause changes not to be committed to the LDAP server. If there's something missing from the API, please let us know, or even fix it yourself. We love a DIY queen. πŸ‘‘

πŸ‘‘ SOME PERLDAP/OO BASICS πŸ‘‘

An entry consist of a DN, and a hash array of pointers to attribute values. Each attribute value (except the DN) is an array, but you have to remember the hash array in the entry stores pointers to the array, not the array. So, to access the first CN value of an entry, you'd do

$cn = $entry->{cn}[0];

To set the CN attribute to a completely new array of values, you'd do

$entry->{cn} = [ "Leif Hedstrom", "The Swede" ];

As long as you remember this, and try to use native Mozilla::LDAP::Entry methods, this package will take care of most the work. Once you master this, working with LDAP in Perl is surprisingly easy. ✨

We already mentioned DN, which stands for Distinguished Name. Every entry on an LDAP server must have a DN, and it's always guaranteed to be unique within your database. Some typical DNs are

uid=leif,ou=people,o=netscape.com
cn=gene-staff,ou=mailGroup,o=netscape.com
dc=data,dc=netscape,dc=com

There's also a term called RDN, which stands for Relative Distinguished Name. In the above examples, "uid=leif", "cn=gene-staff" and "dc=data" are all RDNs. One particular property for a RDN is that they must be unique within it's sub-tree. Hence, there can only be one user with "uid=leif" within the "ou=people" tree, there can never be a name conflict. No duplicates allowed, bestie. πŸ’€

πŸŽ€ CREATING A NEW OBJECT INSTANCE πŸŽ€

Before you can do anything with PerLDAP, you'll need to instantiate at least one Mozilla::LDAP::Conn object, and connect it to an LDAP server. As you probably guessed already, this is done with the new method:

$conn = Mozilla::LDAP::Conn->new("ldap", "389", $bind, $pswd, $cert, $ver);
die "Couldn't connect to LDAP server ldap" unless  $conn;

The arguments are: Host name, port number, and optionally a bind-DN, it's password, and a certificate. A recent addition is the LDAP protocol version, which is by default LDAP v3. If there is no bind-DN, the connection will be bound as the anonymous user. If the certificate file is specified, the connection will be over SSL, and you should then probably connect to port 636. You have to check that the object was created properly, and take proper actions if you couldn't get a connection. Don't just vibe and hope, bestie. Check it. 🫢

There's one convenient alternative call method to this function. Instead of providing each individual argument, you can provide one hash array (actually, a pointer to a hash). For example:

%ld = Mozilla::LDAP::Utils::ldapArgs();
$conn = Mozilla::LDAP::Conn->new(\%ld);

The components of the hash are:

  • $ld->{"host"}
  • $ld->{"port"}
  • $ld->{"base"}
  • $ld->{"bind"}
  • $ld->{"pswd"}
  • $ld->{"cert"}
  • $ld->{"vers"}

and (not used in the new method)

  • $ld->{"scope"}

New for PerLDAP v1.5 and later are the following:

  • $ld->{"nspr"}
  • $ld->{"timeout"}
  • $ld->{"callback"}
  • $ld->{"entryclass"}

The nspr flag (1/0) indicates that we wish to use the NSPR layer for the LDAP connection. This obviously only works if PerLDAP has been compiled with NSPR support and libraries. The default is for NSPR to be disabled. 🚫

For an NSPR enabled connection, you can also provide an optional timeout parameter, which will be used during the lifetime of the connection. This includes the initial setup and connection to the LDAP server. You can change this parameter later using the setNSPRTimeout() method.

During the bind process, you can provide a callback function to be called when the asynchronus bind has completed. The callback should take two arguments, a reference to the ::Conn object ("self") and a result structure as returned by the call to ldap_result().

Finally, you can optionally specify what class the different methods should use when instantiating Entry result objects. The default is Mozilla::LDAP::Entry.

Once a connection is established, the package will take care of the rest. If for some reason the connection is lost, the object should reconnect on it's own, automatically. [Note: This doesn't work now... ]. You can use the Mozilla::LDAP:Conn object for any number of operations, but since everything is currently done synchronously, you can only have one operation active at any single time. You can of course have multiple Mozilla::LDAP::Conn instanced active at the same time. πŸ‘―β€β™€οΈ

πŸ” PERFORMING LDAP SEARCHES πŸ”

okay bestie, so first things first: we're assuming you already know the LDAP filter syntax, because literally every search this object class runs uses those filters. You should also be comfy with LDAP URLs and LDAP object classes β€” those are like, the bare minimum you actually must know about LDAP. No skipping. πŸ™…

The simplest filter ever is this:

(uid=leif)

That matches every entry whose UID is set to "leif". Normally that'd only match one entry, but ngl there's no guarantee of that. So if you wanted to find everyone named "leif", you'd do:

(cn=*leif*)

Wanna get fancy? Logic operators, babes. To find all mail groups owned by "leif" (or actually his DN, bestie, the DN), you could do:

(&(objectclass=mailGroup)(owner=uid=leif,ou=people,o=netscape))

The owner attribute is what we call a DN attribute, so to match on it we gotta spell out the entire DN in the filter above. Sure, we could do a substring "wild card" match instead, but it's less efficient and honestly it needs indexes to perform reasonably well. lowkey not worth it. πŸ’…

okay so now we're ready to actually do a real search on the LDAP server:

$base = "o=netscape.com";
$conn = Mozilla::LDAP::Conn->new("ldap", "389", "", ""); die "No LDAP connection" unless $conn;

$entry = $conn->search($base, "subtree", "(uid=leif)");
if (! $entry)
  { # handle this event, no entries found, dude!
  }
else
  {
    while ($entry)
      {
        $entry->printLDIF();
        $entry = $conn->nextEntry();
      }
  }

This is literally a poor man's implementation of the ldapsearch command line utility, no cap. The search method hands you back an Mozilla::LDAP::Entry object (or a derived subclass), which holds the first entry from the search β€” if there even is one. To get the second and all the subsequent entries, you keep calling the entry method until there are no more entries. And printLDIF is just a cute convenience function that asks the entry to print itself on STDOUT in LDIF format. iconic. ✨

The arguments to the search methods are the LDAP Base-DN, the scope of the search ("base", "one" or "sub"), and the actual LDAP filter. The entry you get back contains the DN and all attribute values. To grab one specific attribute value, you just use the hash array:

$cn = $entry->{cn}[0];

Because sooo many LDAP attributes can have more than one value, the value of the hash array is another array (or actually a pointer to an array). In a lot of cases you can just assume the value is chilling in the first slot (indexed by [0]), but for some attributes you've gotta support multiple values. To find out how many values a specific attribute has, you call the size method:

$numVals = $entry->size("objectclass");
one caveat, bestie 🫢 many LDAP attributes are case insensitive, but the methods in the Mozilla::LDAP::Entry package are not aware of this. So if you compare values with case sensitivity, you can experience some genuinely weird behavior. If you know an attribute is CIS (Case Insensitive), make sure you do case insensitive string comparisons. periodt.

Unfortunately, some methods in this package can't do that, and by default they'll do case sensitive comparisons. We're working on it, and in a future release some of the methods will handle this more gracefully. As an extension (for LDAP v3.0) we could also use schema discovery to handle this even better. 🧚

There's an alternative search method: use LDAP URLs instead of a filter string. This is great for easily parsing and processing URLs, which are a compact way of storing a "link" to some specific LDAP information. To process a search like that, you use the searchURL method:

$entry->searchURL("ldap:///o=netscape.com??sub?(uid=leif)");

And plot twist β€” the search method also supports LDAP URL searches. If the search filter looks like a proper URL, we'll actually do a URL search instead. That's for backward compatibility and for ease of use. πŸ’–

To get better performance and use less memory, you can limit your search to only retrieve certain attributes. With LDAP URLs you specify this as an optional parameter, and with the search method you add two more options, like:

$entry = $conn->search($base, "sub", $filter, 0, ("mail", "cn"));

The last argument is an array of attributes to retrieve β€” the fewer attributes, the faster the search will be. πŸ”₯ The second-to-last argument is a boolean value saying whether we should retrieve only the attribute names (and no values). In most cases you want this to be FALSE, so you get both the attribute names and all their values. To do this with the searchURL method, add a second argument, which should be 0 or 1.


⚑ PERFORMING ASYNCHRONOUS SEARCHES ⚑

Conn also supports an async_search method that takes the same arguments as the search method, but returns an instance of SearchIter instead of Entry. As the name implies, the SearchIter is what you use to iterate through the search results. The nextEntry method works exactly like the nextEntry method of Conn. And the abandon method should be called if search result processing is aborted before the last result is received β€” that lets the client and the server release resources. πŸ’…

Example:

$iter = $conn->async_search($base, $scope, $filter, ...);
if ($rc = $iter->getResultCode()) {
    # process error condition
    } else {
    while (my $entry = $iter->nextEntry) {
            # process entry
        if (some abort condition) {
        $iter->abandon;
        last;
        }
    }
    }

πŸ› οΈ MODIFYING AND CREATING NEW LDAP ENTRIES πŸ› οΈ

Once you have an LDAP entry β€” either from a search, or created directly to get a new empty object β€” you're ready to modify it. If you're creating a new entry, the first thing to set is its DN, like:

$entry = $conn->newEntry();
$entry->setDN("uid=leif,ou=people,o=netscape.com");

Alternatively you can still use the new method on the Entry class, like:

$entry = Mozilla::LDAP::Entry->new();
do NOT do this for an existing LDAP entry, bestie 😭 changing the RDN (or DN) for an existing entry has to be done with modifyRDN.

To populate (or modify) some other attributes, we can do:

$entry->{objectclass} = [ "top", "person", "inetOrgPerson" ];
$entry->{cn} = [ "Leif Hedstrom" ];
$entry->{mail} = [ "leif@netscape.com" ];

Once you're done modifying your LDAP entry, call the update method from the Mozilla::LDAP::Conn object instance:

$conn->update($entry);

Or, if you're creating an entirely new LDAP entry, you must call the add method:

$conn->add($entry);

And if all comes to worse and you have to remove an entry again from the LDAP server, just call the delete method, like:

$conn->delete($entry->getDN());

You can't use native Perl functions like push() and splice() on attribute values, because they won't update the ::Entry instance state properly. πŸ™ˆ Instead, use one of the methods provided by the Mozilla::LDAP::Entry object class, for instance:

$entry->addValue("cn", "The Swede");
$entry->removeValue("mailAlternateAddress", "leif@mcom.com");
$entry->remove("seeAlso");

These methods return a TRUE or FALSE value, depending on the outcome of the operation. If there was no value to remove, or a value already exists, we return FALSE, otherwise TRUE. To check if an attribute has a certain value, use the hasValue method, like:

if ($entry->hasValue("mail", "leif@netscape.com")) {
    # Do something
}

There's a similar method, matchValue, which takes a regular expression to match against instead of the entire string. For more info on this and other methods in the Entry class, see below. πŸ‘‘


🌈 OBJECT CLASS METHODS 🌈

We already described the fundamentals of this class earlier. This is a summary of all the available methods you can use. Be careful not to use any undocumented features or behaviour, since the internals in this module are likely to change. πŸ‘€

πŸ”Ž Searching and updating entries

  • add β€” Add a new entry to the LDAP server. Make sure you use the new method for the Mozilla::LDAP::Entry object, so you create a proper entry.
  • browse β€” Searches for an LDAP entry, but sets some default values to begin with, such as scope=BASE, filter=(objectclass=*) and so on. Much like search, except for these defaults. Requires a DN value as an argument. An optional second argument is an array of which attributes to return from the entry. Note that this does not support the "attributesOnly" flag.
$secondEntry = $conn->browse($entry->getDN());
  • close β€” Close the LDAP connection, and clean up the object. If you don't call this directly, the destructor for the object instance will do the job for you. 🫢
  • compare β€” Compares an attribute and value to a given DN without first doing a search. Requires three arguments: a DN, the attribute name, and the value of the attribute. Returns TRUE if the attribute/value compared ok.
print "not" unless $conn->compare($entry->getDN(), "cn", "Big Swede");
print "ok";
  • delete β€” This will delete the current entry, or possibly an entry as specified with the optional argument. You can use this function to delete any entry you like, by passing it an explicit DN. If you don't pass it this argument, delete defaults to deleting the current entry, from the last call to search or entry. I'd recommend doing a delete with the explicit DN, like:
$conn->delete($entry->getDN());
  • modifyRDN β€” This will rename the specified LDAP entry, by modifying its RDN. For example, assuming you have a DN of
uid=leif, ou=people, dc=netscape, dc=com

and you wish to rename to

uid=fiel, ou=people, dc=netscape, dc=com

you'd do something like

$rdn = "uid=fiel";
$conn->modifyRDN($rdn, $entry->getDN());

Note that this can only be done on the RDN β€” you could not change, say, "ou=people" to be "ou=hackers" in the example above. To do that, you have to add a new entry (a copy of the old one), and then remove the old entry. πŸ’€

The last argument is a boolean (0 or 1), which indicates if the old RDN value should be removed from the entry. The default is TRUE ("1").

✨ METHODS ✨

  • new β€” okay so this one is literally the main character πŸ’… It creates and initializes a new LDAP connection and object. The required arguments are host name, port number, bind DN and the bind password. An optional argument is a certificate (public key), which causes the LDAP connection to be established over an SSL channel. Currently we do not support Client Authentication, so you still have to use the simple authentication method (i.e. with a password).

A typical usage could be something like

%ld = Mozilla::LDAP::Utils::ldapArgs();
$conn = Mozilla::LDAP::Conn->new(\%ld);

Also, remember that if you use SSL, the port is (usually) 636.

  • newEntry β€” this will create an empty Mozilla::LDAP::Entry object, which is properly tied into the appropriate objectclass. Use this method instead of manually creating new Entry objects, or at least make sure that you use the "tie" function when creating the entry. This function takes no arguments, and returns a pointer to an ::Entry object. For instance
$entry = $conn->newEntry();

or

$entry = Mozilla::LDAP::Conn->newEntry();
  • nextEntry β€” this method will return the next entry from the search result, and can therefore only be called after a successful search has been initiated. If there are no more entries to retrieve, it returns nothing (empty string). No cap.
  • search β€” the search method is the main entry point into this module. It requires at least three arguments: The Base DN, the scope, and the search strings. Two more optional arguments can be given, the first specifies if only attribute names should be returned (TRUE or FALSE). The second argument is a list (array) of attributes to return.

The last option is very important for performance. If you are only interested in say the "mail" and "mailHost" attributes, specifying this in the search will significantly reduce the search time. An example of an efficient search is

@attr = ("cn", "uid", "mail");
$filter = "(uid=*)";
$entry = $conn->search($base, $scope, $filter, 0, @attr);
while ($entry) {
    # do something
    $entry = $conn->nextEntry();
}
  • searchURL β€” this is almost identical to search, except this function takes only two arguments, an LDAP URL and an optional flag to specify if we only want the attribute names to be returned (and no values). This function isn't very useful, since the search method will actually honor properly formed LDAP URL's, and use it if appropriate.
  • simpleAuth β€” this method will rebind the LDAP connection using new credentials (i.e. a new user-DN and password). To rebind "anonymously", just don't pass a DN and password, and it will default to binding as the unprivileged user. For example:
$user = "leif";
$password = "secret";
$conn = Mozilla::LDAP::Conn->new($host, $port);     # Anonymous bind
die "Could't connect to LDAP server $host" unless $conn;

$entry = $conn->search($base, $scope, "(uid=$user)", 0, (uid));
exit (-1) unless $entry;

$ret = $conn->simpleAuth($entry->getDN(), $password);
exit (-1) unless $ret;

$ret = $conn->simpleAuth();         # Bind as anon again.
  • update β€” after modifying an Ldap::Entry entry (see below), use the update method to commit changes to the LDAP server. Only attributes that has been changed will be updated, assuming you have used the appropriate methods in the Entry object. For instance, do not use push or splice to modify an entry, the update will not recognize such changes.

To change the CN value for an entry, you could do

$entry->{cn} = ["Leif Hedstrom"];
$conn->update($entry);

🌈 Other methods 🌈

  • getErrorCode β€” return the error code (numeric) from the last LDAP API function call. Remember that this can only be called after the successful creation of a new :Conn object instance. A typical usage could be
if (! $opt_n) {
    $conn->modifyRDN($rdn, $entry->getDN());
    $conn->printError() if $conn->getErrorCode();
}

Which will report any error message as generated by the call to modifyRDN. Some LDAP functions return extra error information, which can be retrieved like:

$err = getErrorCode(\$matched, \$string);

$matched will then contain the portion of the matched DN (if applicable to the error code), and $string will contain any additional error string returned by the LDAP server.

  • getErrorString β€” very much like getErrorCode, but return a string with a human readable error message. This can then be used to print a good error message on the console.
  • getLD β€” return the (internal) LDAP* connection handle, which you can use (carefully) to call the native LDAP API functions. You shouldn't have to use this in most cases, unless of course our OO layer is seriously flawed.
  • getRes β€” just like getLD, except it returns the internal LDAP return message structure. Again, use this very carefully, and be aware that this might break in future releases of PerLDAP. These two methods can be used to call some useful API functions, like
$cld = $conn->getLD();
$res = $conn->getRes();
$count = Mozilla::LDAP::API::ldap_count_entries($cld, $res);
  • isURL β€” returns TRUE or FALSE if the given argument is a properly formed URL.
  • printError β€” print the last error message on standard output.
  • setRebindProc β€” tell the LDAP SDK to call the provided Perl function when it has to follow referrals. The Perl function should return an array of three elements, the new Bind DN, password and authentication method. A typical usage is
sub rebindProc {
    return ("uid=ldapadmin", "secret", LDAP_AUTH_SIMPLE);
}

$ld->setRebindProc(\&rebindProc);
  • setDefaultRebindProc β€” this is very much like the previous function, except instead of specifying the function to use, you give it the DN, password and Auth method. Then we'll use a default rebind procedure (internal in C) to handle the rebind credentials. This was a solution for the Windows/NT problem/bugs we have with rebind procedures written in Perl.
  • setVersion β€” change the LDAP protocol version on the already initialized connection. The default is LDAP v3 (new for PerLDAP v1.5!), but you can downgrade the connection to LDAP v2 if necessary using this function. Example:
$conn->setVersion(2);
  • getVersion β€” return the protocol version currently in used by the connection.
  • setSizelimit β€” set the sizelimit on a connection, to limit the maximum number of entries that we want to retrieve. For example:
$conn->setSizelimit(10);
  • getSizelimit β€” get the current sizelimit on a connection (if any).
  • setOption β€” set an (integer) LDAP option.
  • getOption β€” get an (integer) LDAP option.
  • installNSPR β€” install NSPR I/O, threading, and DNS functions so they will be used by 'ld'.

Pass a non-zero value for the 'shared' parameter if you plan to use this LDAP * handle from more than one thread. This is highly unlikely since PerLDAP is asynchronous.

  • setNSPRTimeout β€” set the TCP timeout value, in millisecond, for the NSPR enabled connection. It's an error to call this before calling installNSPR(), unless you created the new connection object with the nspr option.

This method can also be invoked as a class method, and it will then apply to all new connections created. Like

Mozilla::LDAP::Conn->installNSPR(1);
Mozilla::LDAP::Conn->setNSPRTimeout(1000);

✨ EXAMPLES ✨

There are plenty of examples to look at, in the examples directory. We are adding more examples every day (almost).

πŸ› οΈ INSTALLATION πŸ› οΈ

Installing this package is part of the Makefile supplied in the package. See the installation procedures which are part of this package.

🌍 AVAILABILITY 🌍

This package can be retrieved from a number of places, including:

http://www.mozilla.org/directory/
Your local CPAN server

πŸ’– CREDITS πŸ’–

Most of this code was developed by Leif Hedstrom, Netscape Communications Corporation.

πŸ› BUGS πŸ›

None. :)

πŸ‘€ SEE ALSO πŸ‘€

Mozilla::LDAP::Entry, LDAP::Mozilla:Utils LDAP::Mozilla:API and of course Perl.


That's the tea, bestie! This page is from Perl v5.40.0, dated 2025-01-03, for Conn(3pm). Stay slay! πŸ’…βœ¨

πŸ“¦ where this page comes from