1Conn(3) User Contributed Perl Documentation Conn(3)
2
3
4
6 Mozilla::LDAP::Conn - Object Oriented API for the LDAP SDK.
7
9 use Mozilla::LDAP::Conn;
10 use Mozilla::LDAP::Utils;
11
13 This package is the main API for using our Perl Object Oriented LDAP
14 module. Even though it's certainly possible, and sometimes even
15 necessary, to call the native LDAP C SDK functions, we strongly
16 recommend you use these object classes.
17
18 It's not required to use our Mozilla::LDAP::Utils.pm package, but it's
19 convenient and good for portability if you use as much as you can from
20 that package as well. This implies using the LdapConf package as well,
21 even though you usually don't need to use it directly.
22
23 You should read this document in combination with the
24 Mozilla::LDAP::Entry document. Both modules depend on each other
25 heavily.
26
28 First, this is not ment to be a crash course in how LDAP works, if you
29 have no experience with LDAP, I suggest you read some of the literature
30 that's available out there. The LDAP Deployment Book from Netscape, or
31 the LDAP C SDK documentation are good starting points.
32
33 This object class basically tracks and manages the LDAP connection,
34 it's current status, and the current search operation (if any). Every
35 time you call the search method of an object instance, you'll reset
36 it's internal state. It depends heavily on the ::Entry class, which are
37 used to retrieve, modify and update a single entry.
38
39 The search and nextEntry methods returns Mozilla::LDAP::Entry objects,
40 or an appropriately subclass of it. You also have to instantiate (and
41 modify) a new ::Entry object when you want to add new entries to an
42 LDAP server. Alternatively, the add() method will also take a hash
43 array as argument, to make it easy to create new LDAP entries.
44
45 To assure that changes to an entry are updated properly, we strongly
46 recommend you use the native methods of the ::Entry object class. Even
47 though you can modify certain elements directly, it could cause changes
48 not to be committed to the LDAP server. If there's something missing
49 from the API, please let us know, or even fix it yourself.
50
52 An entry consist of a DN, and a hash array of pointers to attribute
53 values. Each attribute value (except the DN) is an array, but you have
54 to remember the hash array in the entry stores pointers to the array,
55 not the array. So, to access the first CN value of an entry, you'd do
56
57 $cn = $entry->{cn}[0];
58
59 To set the CN attribute to a completely new array of values, you'd do
60
61 $entry->{cn} = [ "Leif Hedstrom", "The Swede" ];
62
63 As long as you remember this, and try to use native
64 Mozilla::LDAP::Entry methods, this package will take care of most the
65 work. Once you master this, working with LDAP in Perl is surprisingly
66 easy.
67
68 We already mentioned DN, which stands for Distinguished Name. Every
69 entry on an LDAP server must have a DN, and it's always guaranteed to
70 be unique within your database. Some typical DNs are
71
72 uid=leif,ou=people,o=netscape.com
73 cn=gene-staff,ou=mailGroup,o=netscape.com
74 dc=data,dc=netscape,dc=com
75
76 There's also a term called RDN, which stands for Relative Distinguished
77 Name. In the above examples, "uid=leif", "cn=gene-staff" and "dc=data"
78 are all RDNs. One particular property for a RDN is that they must be
79 unique within it's sub-tree. Hence, there can only be one user with
80 "uid=leif" within the "ou=people" tree, there can never be a name
81 conflict.
82
84 Before you can do anything with PerLDAP, you'll need to instantiate at
85 least one Mozilla::LDAP::Conn object, and connect it to an LDAP server.
86 As you probably guessed already, this is done with the new method:
87
88 $conn = Mozilla::LDAP::Conn->new("ldap", "389", $bind, $pswd, $cert, $ver);
89 die "Couldn't connect to LDAP server ldap" unless $conn;
90
91 The arguments are: Host name, port number, and optionally a bind-DN,
92 it's password, and a certificate. A recent addition is the LDAP
93 protocol version, which is by default LDAP v3. If there is no bind-DN,
94 the connection will be bound as the anonymous user. If the certificate
95 file is specified, the connection will be over SSL, and you should then
96 probably connect to port 636. You have to check that the object was
97 created properly, and take proper actions if you couldn't get a
98 connection.
99
100 There's one convenient alternative call method to this function.
101 Instead of providing each individual argument, you can provide one hash
102 array (actually, a pointer to a hash). For example:
103
104 %ld = Mozilla::LDAP::Utils::ldapArgs();
105 $conn = Mozilla::LDAP::Conn->new(\%ld);
106
107 The components of the hash are:
108
109 $ld->{"host"}
110 $ld->{"port"}
111 $ld->{"base"}
112 $ld->{"bind"}
113 $ld->{"pswd"}
114 $ld->{"cert"}
115 $ld->{"vers"}
116
117 and (not used in the new method)
118
119 $ld->{"scope"}
120
121 New for PerLDAP v1.5 and later are the following:
122
123 $ld->{"nspr"}
124 $ld->{"timeout"}
125 $ld->{"callback"}
126 $ld->{"entryclass"}
127
128 The nspr flag (1/0) indicates that we wish to use the NSPR layer for
129 the LDAP connection. This obviously only works if PerLDAP has been
130 compiled with NSPR support and libraries. The default is for NSPR to be
131 disabled.
132
133 For an NSPR enabled connection, you can also provide an optional
134 timeout parameter, which will be used during the lifetime of the
135 connection. This includes the initial setup and connection to the LDAP
136 server. You can change this parameter later using the setNSPRTimeout()
137 method.
138
139 During the bind process, you can provide a callback function to be
140 called when the asynchronus bind has completed. The callback should
141 take two arguments, a reference to the ::Conn object ("self") and a
142 result structure as returned by the call to ldap_result().
143
144 Finally, you can optionally specify what class the different methods
145 should use when instantiating Entry result objects. The default is
146 Mozilla::LDAP::Entry.
147
148 Once a connection is established, the package will take care of the
149 rest. If for some reason the connection is lost, the object should
150 reconnect on it's own, automatically. [Note: This doesn't work now...
151 ]. You can use the Mozilla::LDAP:Conn object for any number of
152 operations, but since everything is currently done synchronously, you
153 can only have one operation active at any single time. You can of
154 course have multiple Mozilla::LDAP::Conn instanced active at the same
155 time.
156
158 We assume that you are familiar with the LDAP filter syntax already,
159 all searches performed by this object class uses these filters. You
160 should also be familiar with LDAP URLs, and LDAP object classes. There
161 are some of the few things you actually must know about LDAP. Perhaps
162 the simples filter is
163
164 (uid=leif)
165
166 This matches all entries with the UID set to "leif". Normally that
167 would only match one entry, but there is no guarantee for that. To find
168 everyone with the name "leif", you'd instead do
169
170 (cn=*leif*)
171
172 A more complicated search involves logic operators. To find all mail
173 groups owned by "leif" (or actually his DN), you could do
174
175 (&(objectclass=mailGroup)(owner=uid=leif,ou=people,o=netscape))
176
177 The owner attribute is what's called a DN attribute, so to match on it
178 we have to specify the entire DN in the filter above. We could of
179 course also do a sub string "wild card" match, but it's less efficient,
180 and requires indexes to perform reasonably well.
181
182 Ok, now we are prepared to actually do a real search on the LDAP
183 server:
184
185 $base = "o=netscape.com";
186 $conn = Mozilla::LDAP::Conn->new("ldap", "389", "", ""); die "No LDAP
187 connection" unless $conn;
188
189 $entry = $conn->search($base, "subtree", "(uid=leif)");
190 if (! $entry)
191 { # handle this event, no entries found, dude!
192 }
193 else
194 {
195 while ($entry)
196 {
197 $entry->printLDIF();
198 $entry = $conn->nextEntry();
199 }
200 }
201
202 This is in fact a poor mans implementation of the ldapsearch command
203 line utility. The search method returns an Mozilla::LDAP::Entry object
204 (or derived subclass), which holds the first entry from the search, if
205 any. To get the second and subsequent entries you call the entry
206 method, until there are no more entries. The printLDIF method is a
207 convenient function, requesting the entry to print itself on STDOUT, in
208 LDIF format.
209
210 The arguments to the search methods are the LDAP Base-DN, the scope of
211 the search ("base", "one" or "sub"), and the actual LDAP filter. The
212 entry return contains the DN, and all attribute values. To access a
213 specific attribute value, you just have to use the hash array:
214
215 $cn = $entry->{cn}[0];
216
217 Since many LDAP attributes can have more than one value, value of the
218 hash array is another array (or actually a pointer to an array). In
219 many cases you can just assume the value is in the first slot (indexed
220 by [0]), but for some attributes you have to support multiple values.
221 To find out how many values a specific attribute has, you'd call the
222 size method:
223
224 $numVals = $entry->size("objectclass");
225
226 One caveat: Many LDAP attributes are case insensitive, but the methods
227 in the Mozilla::LDAP::Entry package are not aware of this. Hence, if
228 you compare values with case sensitivity, you can experience weird
229 behavior. If you know an attribute is CIS (Case Insensitive), make sure
230 you do case insensitive string comparisons.
231
232 Unfortunately some methods in this package can't do this, and by
233 default will do case sensitive comparisons. We are working on this, and
234 in a future release some of the methods will handle this more
235 gracefully. As an extension (for LDAP v3.0) we could also use schema
236 discovery for handling this even better.
237
238 There is an alternative search method, to use LDAP URLs instead of a
239 filter string. This can be used to easily parse and process URLs, which
240 is a compact way of storing a "link" to some specific LDAP information.
241 To process such a search, you use the searchURL method:
242
243 $entry->searchURL("ldap:///o=netscape.com??sub?(uid=leif)");
244
245 As it turns out, the search method also supports LDAP URL searches. If
246 the search filter looks like a proper URL, we will actually do an URL
247 search instead. This is for backward compatibility, and for ease of
248 use.
249
250 To achieve better performance and use less memory, you can limit your
251 search to only retrieve certain attributes. With the LDAP URLs you
252 specify this as an optional parameter, and with the search method you
253 add two more options, like
254
255 $entry = $conn->search($base, "sub", $filter, 0, ("mail", "cn"));
256
257 The last argument specifies an array of attributes to retrieve, the
258 fewer the attributes, the faster the search will be. The second to last
259 argument is a boolean value indicating if we should retrieve only the
260 attribute names (and no values). In most cases you want this to be
261 FALSE, to retrieve both the attribute names, and all their values. To
262 do this with the searchURL method, add a second argument, which should
263 be 0 or 1.
264
266 Conn also supports an async_search method that takes the same arguments
267 as the search method but returns an instance of SearchIter instead of
268 Entry. As its name implies, the SearchIter is used to iterate through
269 the search results. The nextEntry method works just like the nextEntry
270 method of Conn. The abandon method should be called if search result
271 processing is aborted before the last result is received, to allow the
272 client and server to release resources. Example:
273
274 $iter = $conn->async_search($base, $scope, $filter, ...);
275 if ($rc = $iter->getResultCode()) {
276 # process error condition
277 } else {
278 while (my $entry = $iter->nextEntry) {
279 # process entry
280 if (some abort condition) {
281 $iter->abandon;
282 last;
283 }
284 }
285 }
286
288 Once you have an LDAP entry, either from a search, or created directly
289 to get a new empty object, you are ready to modify it. If you are
290 creating a new entry, the first thing to set it it's DN, like
291
292 $entry = $conn->newEntry();
293 $entry->setDN("uid=leif,ou=people,o=netscape.com");
294
295 alternatively you can still use the new method on the Entry class, like
296
297 $entry = Mozilla::LDAP::Entry->new();
298
299 You should not do this for an existing LDAP entry, changing the RDN (or
300 DN) for such an entry must be done with modifyRDN. To populate (or
301 modify) some other attributes, we can do
302
303 $entry->{objectclass} = [ "top", "person", "inetOrgPerson" ];
304 $entry->{cn} = [ "Leif Hedstrom" ];
305 $entry->{mail} = [ "leif@netscape.com" ];
306
307 Once you are done modifying your LDAP entry, call the update method
308 from the Mozilla::LDAP::Conn object instance:
309
310 $conn->update($entry);
311
312 Or, if you are creating an entirely new LDAP entry, you must call the
313 add method:
314
315 $conn->add($entry);
316
317 If all comes to worse, and you have to remove an entry again from the
318 LDAP server, just call the delete method, like
319
320 $conn->delete($entry->getDN());
321
322 You can't use native Perl functions like push() and splice() on
323 attribute values, since they won't update the ::Entry instance state
324 properly. Instead use one of the methods provided by the
325 Mozilla::LDAP::Entry object class, for instance
326
327 $entry->addValue("cn", "The Swede");
328 $entry->removeValue("mailAlternateAddress", "leif@mcom.com");
329 $entry->remove("seeAlso");
330
331 These methods return a TRUE or FALSE value, depending on the outcome of
332 the operation. If there was no value to remove, or a value already
333 exists, we return FALSE, otherwise TRUE. To check if an attribute has a
334 certain value, use the hasValue method, like
335
336 if ($entry->hasValue("mail", "leif@netscape.com")) {
337 # Do something
338 }
339
340 There is a similar method, matchValue, which takes a regular expression
341 to match against, instead of the entire string. For more information
342 this and other methods in the Entry class, see below.
343
345 We have already described the fundamentals of this class earlier. This
346 is a summary of all available methods which you can use. Be careful not
347 to use any undocumented features or heaviour, since the internals in
348 this module is likely to change.
349
350 Searching and updating entries
351 add Add a new entry to the LDAP server. Make sure you use the
352 new method for the Mozilla::LDAP::Entry object, to create
353 a proper entry.
354
355 browse Searches for an LDAP entry, but sets some default values
356 to begin with, such as scope=BASE, filter=(objectclass=*)
357 and so on. Much like search except for these defaults.
358 Requires a DN value as an argument. An optional second
359 argument is an array of which attributes to return from
360 the entry. Note that this does not support the
361 "attributesOnly" flag.
362
363 $secondEntry = $conn->browse($entry->getDN());
364
365 close Close the LDAP connection, and clean up the object. If you
366 don't call this directly, the destructor for the object
367 instance will do the job for you.
368
369 compare Compares an attribute and value to a given DN without
370 first doing a search. Requires three arguments: a DN, the
371 attribute name, and the value of the attribute. Returns
372 TRUE if the attribute/value compared ok.
373
374 print "not" unless $conn->compare($entry->getDN(), "cn", "Big Swede");
375 print "ok";
376
377 delete This will delete the current entry, or possibly an entry
378 as specified with the optional argument. You can use this
379 function to delete any entry you like, by passing it an
380 explicit DN. If you don't pass it this argument, delete
381 defaults to delete the current entry, from the last call
382 to search or entry. I'd recommend doing a delete with the
383 explicit DN, like
384
385 $conn->delete($entry->getDN());
386
387 modifyRDN This will rename the specified LDAP entry, by modifying
388 it's RDN. For example, assuming you have a DN of
389
390 uid=leif, ou=people, dc=netscape, dc=com
391
392 and you wish to rename to
393
394 uid=fiel, ou=people, dc=netscape, dc=com
395
396 you'd do something like
397
398 $rdn = "uid=fiel";
399 $conn->modifyRDN($rdn, $entry->getDN());
400
401 Note that this can only be done on the RDN, you could not
402 change say "ou=people" to be "ou=hackers" in the example
403 above. To do that, you have to add a new entry (a copy of
404 the old one), and then remove the old entry.
405
406 The last argument is a boolean (0 or 1), which indicates
407 if the old RDN value should be removed from the entry. The
408 default is TRUE ("1").
409
410 new This creates and initialized a new LDAP connection and
411 object. The required arguments are host name, port number,
412 bind DN and the bind password. An optional argument is a
413 certificate (public key), which causes the LDAP connection
414 to be established over an SSL channel. Currently we do not
415 support Client Authentication, so you still have to use
416 the simple authentication method (i.e. with a password).
417
418 A typical usage could be something like
419
420 %ld = Mozilla::LDAP::Utils::ldapArgs();
421 $conn = Mozilla::LDAP::Conn->new(\%ld);
422
423 Also, remember that if you use SSL, the port is (usually)
424 636.
425
426 newEntry This will create an empty Mozilla::LDAP::Entry object,
427 which is properly tied into the appropriate objectclass.
428 Use this method instead of manually creating new Entry
429 objects, or at least make sure that you use the "tie"
430 function when creating the entry. This function takes no
431 arguments, and returns a pointer to an ::Entry object. For
432 instance
433
434 $entry = $conn->newEntry();
435
436 or
437
438 $entry = Mozilla::LDAP::Conn->newEntry();
439
440 nextEntry This method will return the next entry from the search
441 result, and can therefore only be called after a succesful
442 search has been initiated. If there are no more entries to
443 retrieve, it returns nothing (empty string).
444
445 search The search method is the main entry point into this
446 module. It requires at least three arguments: The Base DN,
447 the scope, and the search strings. Two more optional
448 arguments can be given, the first specifies if only
449 attribute names should be returned (TRUE or FALSE). The
450 second argument is a list (array) of attributes to return.
451
452 The last option is very important for performance. If you
453 are only interested in say the "mail" and "mailHost"
454 attributes, specifying this in the search will
455 signficantly reduce the search time. An example of an
456 efficient search is
457
458 @attr = ("cn", "uid", "mail");
459 $filter = "(uid=*)";
460 $entry = $conn->search($base, $scope, $filter, 0, @attr);
461 while ($entry) {
462 # do something
463 $entry = $conn->nextEntry();
464 }
465
466 searchURL This is almost identical to search, except this function
467 takes only two arguments, an LDAP URL and an optional flag
468 to specify if we only want the attribute names to be
469 returned (and no values). This function isn't very useful,
470 since the search method will actually honor properly
471 formed LDAP URL's, and use it if appropriate.
472
473 simpleAuth This method will rebind the LDAP connection using new
474 credentials (i.e. a new user-DN and password). To rebind
475 "anonymously", just don't pass a DN and password, and it
476 will default to binding as the unprivleged user. For
477 example:
478
479 $user = "leif";
480 $password = "secret";
481 $conn = Mozilla::LDAP::Conn->new($host, $port); # Anonymous bind
482 die "Could't connect to LDAP server $host" unless $conn;
483
484 $entry = $conn->search($base, $scope, "(uid=$user)", 0, (uid));
485 exit (-1) unless $entry;
486
487 $ret = $conn->simpleAuth($entry->getDN(), $password);
488 exit (-1) unless $ret;
489
490 $ret = $conn->simpleAuth(); # Bind as anon again.
491
492 update After modifying an Ldap::Entry entry (see below), use the
493 update method to commit changes to the LDAP server. Only
494 attributes that has been changed will be updated, assuming
495 you have used the appropriate methods in the Entry object.
496 For instance, do not use push or splice to modify an
497 entry, the update will not recognize such changes.
498
499 To change the CN value for an entry, you could do
500
501 $entry->{cn} = ["Leif Hedstrom"];
502 $conn->update($entry);
503
504 Other methods
505 getErrorCode Return the error code (numeric) from the last LDAP API
506 function call. Remember that this can only be called after
507 the successful creation of a new :Conn object instance. A
508 typical usage could be
509
510 if (! $opt_n) {
511 $conn->modifyRDN($rdn, $entry->getDN());
512 $conn->printError() if $conn->getErrorCode();
513 }
514
515 Which will report any error message as generated by the
516 call to modifyRDN. Some LDAP functions return extra error
517 information, which can be retrieved like:
518
519 $err = getErrorCode(\$matched, \$string);
520
521 $matched will then contain the portion of the matched DN
522 (if applicable to the error code), and $string will
523 contain any additional error string returned by the LDAP
524 server.
525
526 getErrorString
527 Very much like getErrorCode, but return a string with a
528 human readable error message. This can then be used to
529 print a good error message on the console.
530
531 getLD Return the (internal) LDAP* connection handle, which you
532 can use (carefully) to call the native LDAP API functions.
533 You shouldn't have to use this in most cases, unless of
534 course our OO layer is seriously flawed.
535
536 getRes Just like getLD, except it returns the internal LDAP
537 return message structure. Again, use this very carefully,
538 and be aware that this might break in future releases of
539 PerLDAP. These two methods can be used to call some useful
540 API functions, like
541
542 $cld = $conn->getLD();
543 $res = $conn->getRes();
544 $count = Mozilla::LDAP::API::ldap_count_entries($cld, $res);
545
546 isURL Returns TRUE or FALSE if the given argument is a properly
547 formed URL.
548
549 printError Print the last error message on standard output.
550
551 setRebindProc
552 Tell the LDAP SDK to call the provided Perl function when
553 it has to follow referrals. The Perl function should
554 return an array of three elements, the new Bind DN,
555 password and authentication method. A typical usage is
556
557 sub rebindProc {
558 return ("uid=ldapadmin", "secret", LDAP_AUTH_SIMPLE);
559 }
560
561 $ld->setRebindProc(\&rebindProc);
562
563 setDefaultRebindProc
564 This is very much like the previous function, except
565 instead of specifying the function to use, you give it the
566 DN, password and Auth method. Then we'll use a default
567 rebind procedure (internal in C) to handle the rebind
568 credentials. This was a solution for the Windows/NT
569 problem/bugs we have with rebind procedures written in
570 Perl.
571
572 setVersion Change the LDAP protocol version on the already
573 initialized connection. The default is LDAP v3 (new for
574 PerLDAP v1.5!), but you can downgrade the connection to
575 LDAP v2 if necessary using this function. Example:
576
577 $conn->setVersion(2);
578
579 getVersion Return the protocol version currently in used by the
580 connection.
581
582 setSizelimit Set the sizelimit on a connection, to limit the maximum
583 number of entries that we want to retrieve. For example:
584
585 $conn->setSizelimit(10);
586
587 getSizelimit Get the current sizelimit on a connection (if any).
588
589 setOption Set an (integer) LDAP option.
590
591 getOption Get an (integer) LDAP option.
592
593 installNSPR Install NSPR I/O, threading, and DNS functions so they
594 will be used by 'ld'.
595
596 Pass a non-zero value for the 'shared' parameter if you
597 plan to use this LDAP * handle from more than one thread.
598 This is highly unlikely since PerLDAP is asynchronous.
599
600 setNSPRTimeout
601 Set the TCP timeout value, in millisecond, for the NSPR
602 enabled connection. It's an error to call this before
603 calling installNSPR(), unless you created the new
604 connection object with the nspr option.
605
606 This method can also be invoked as a class method, and it
607 will then apply to all new connections created. Like
608
609 Mozilla::LDAP::Conn->installNSPR(1);
610 Mozilla::LDAP::Conn->setNSPRTimeout(1000);
611
613 There are plenty of examples to look at, in the examples directory. We
614 are adding more examples every day (almost).
615
617 Installing this package is part of the Makefile supplied in the
618 package. See the installation procedures which are part of this
619 package.
620
622 This package can be retrieved from a number of places, including:
623
624 http://www.mozilla.org/directory/
625 Your local CPAN server
626
628 Most of this code was developed by Leif Hedstrom, Netscape
629 Communications Corporation.
630
632 None. :)
633
635 Mozilla::LDAP::Entry, LDAP::Mozilla:Utils LDAP::Mozilla:API and of
636 course Perl.
637
638
639
640perl v5.32.0 2020-07-28 Conn(3)