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 neces‐
15 sary, to call the native LDAP C SDK functions, we strongly recommend
16 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 heav‐
25 ily.
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 con‐
81 flict.
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 proto‐
93 col version, which is by default LDAP v3. If there is no bind-DN, the
94 connection will be bound as the anonymous user. If the certificate file
95 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 connec‐
98 tion.
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 com‐
130 piled 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 time‐
134 out parameter, which will be used during the lifetime of the connec‐
135 tion. 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 opera‐
152 tions, but since everything is currently done synchronously, you can
153 only have one operation active at any single time. You can of course
154 have multiple Mozilla::LDAP::Conn instanced active at the same time.
155
157 We assume that you are familiar with the LDAP filter syntax already,
158 all searches performed by this object class uses these filters. You
159 should also be familiar with LDAP URLs, and LDAP object classes. There
160 are some of the few things you actually must know about LDAP. Perhaps
161 the simples filter is
162
163 (uid=leif)
164
165 This matches all entries with the UID set to "leif". Normally that
166 would only match one entry, but there is no guarantee for that. To find
167 everyone with the name "leif", you'd instead do
168
169 (cn=*leif*)
170
171 A more complicated search involves logic operators. To find all mail
172 groups owned by "leif" (or actually his DN), you could do
173
174 (&(objectclass=mailGroup)(owner=uid=leif,ou=people,o=netscape))
175
176 The owner attribute is what's called a DN attribute, so to match on it
177 we have to specify the entire DN in the filter above. We could of
178 course also do a sub string "wild card" match, but it's less efficient,
179 and requires indexes to perform reasonably well.
180
181 Ok, now we are prepared to actually do a real search on the LDAP
182 server:
183
184 $base = "o=netscape.com";
185 $conn = Mozilla::LDAP::Conn->new("ldap", "389", "", ""); die "No LDAP
186 connection" unless $conn;
187
188 $entry = $conn->search($base, "subtree", "(uid=leif)");
189 if (! $entry)
190 { # handle this event, no entries found, dude!
191 }
192 else
193 {
194 while ($entry)
195 {
196 $entry->printLDIF();
197 $entry = $conn->nextEntry();
198 }
199 }
200
201 This is in fact a poor mans implementation of the ldapsearch command
202 line utility. The search method returns an Mozilla::LDAP::Entry object
203 (or derived subclass), which holds the first entry from the search, if
204 any. To get the second and subsequent entries you call the entry
205 method, until there are no more entries. The printLDIF method is a con‐
206 venient function, requesting the entry to print itself on STDOUT, in
207 LDIF format.
208
209 The arguments to the search methods are the LDAP Base-DN, the scope of
210 the search ("base", "one" or "sub"), and the actual LDAP filter. The
211 entry return contains the DN, and all attribute values. To access a
212 specific attribute value, you just have to use the hash array:
213
214 $cn = $entry->{cn}[0];
215
216 Since many LDAP attributes can have more than one value, value of the
217 hash array is another array (or actually a pointer to an array). In
218 many cases you can just assume the value is in the first slot (indexed
219 by [0]), but for some attributes you have to support multiple values.
220 To find out how many values a specific attribute has, you'd call the
221 size method:
222
223 $numVals = $entry->size("objectclass");
224
225 One caveat: Many LDAP attributes are case insensitive, but the methods
226 in the Mozilla::LDAP::Entry package are not aware of this. Hence, if
227 you compare values with case sensitivity, you can experience weird
228 behavior. If you know an attribute is CIS (Case Insensitive), make sure
229 you do case insensitive string comparisons.
230
231 Unfortunately some methods in this package can't do this, and by
232 default will do case sensitive comparisons. We are working on this, and
233 in a future release some of the methods will handle this more grace‐
234 fully. As an extension (for LDAP v3.0) we could also use schema discov‐
235 ery for handling this even better.
236
237 There is an alternative search method, to use LDAP URLs instead of a
238 filter string. This can be used to easily parse and process URLs, which
239 is a compact way of storing a "link" to some specific LDAP information.
240 To process such a search, you use the searchURL method:
241
242 $entry->searchURL("ldap:///o=netscape.com??sub?(uid=leif)");
243
244 As it turns out, the search method also supports LDAP URL searches. If
245 the search filter looks like a proper URL, we will actually do an URL
246 search instead. This is for backward compatibility, and for ease of
247 use.
248
249 To achieve better performance and use less memory, you can limit your
250 search to only retrieve certain attributes. With the LDAP URLs you
251 specify this as an optional parameter, and with the search method you
252 add two more options, like
253
254 $entry = $conn->search($base, "sub", $filter, 0, ("mail", "cn"));
255
256 The last argument specifies an array of attributes to retrieve, the
257 fewer the attributes, the faster the search will be. The second to last
258 argument is a boolean value indicating if we should retrieve only the
259 attribute names (and no values). In most cases you want this to be
260 FALSE, to retrieve both the attribute names, and all their values. To
261 do this with the searchURL method, add a second argument, which should
262 be 0 or 1.
263
265 Conn also supports an async_search method that takes the same arguments
266 as the search method but returns an instance of SearchIter instead of
267 Entry. As its name implies, the SearchIter is used to iterate through
268 the search results. The nextEntry method works just like the nextEntry
269 method of Conn. The abandon method should be called if search result
270 processing is aborted before the last result is received, to allow the
271 client and server to release resources. Example:
272
273 $iter = $conn->async_search($base, $scope, $filter, ...);
274 if ($rc = $iter->getResultCode()) {
275 # process error condition
276 } else {
277 while (my $entry = $iter->nextEntry) {
278 # process entry
279 if (some abort condition) {
280 $iter->abandon;
281 last;
282 }
283 }
284 }
285
287 Once you have an LDAP entry, either from a search, or created directly
288 to get a new empty object, you are ready to modify it. If you are cre‐
289 ating a new entry, the first thing to set it it's DN, like
290
291 $entry = $conn->newEntry();
292 $entry->setDN("uid=leif,ou=people,o=netscape.com");
293
294 alternatively you can still use the new method on the Entry class, like
295
296 $entry = Mozilla::LDAP::Entry->new();
297
298 You should not do this for an existing LDAP entry, changing the RDN (or
299 DN) for such an entry must be done with modifyRDN. To populate (or mod‐
300 ify) some other attributes, we can do
301
302 $entry->{objectclass} = [ "top", "person", "inetOrgPerson" ];
303 $entry->{cn} = [ "Leif Hedstrom" ];
304 $entry->{mail} = [ "leif@netscape.com" ];
305
306 Once you are done modifying your LDAP entry, call the update method
307 from the Mozilla::LDAP::Conn object instance:
308
309 $conn->update($entry);
310
311 Or, if you are creating an entirely new LDAP entry, you must call the
312 add method:
313
314 $conn->add($entry);
315
316 If all comes to worse, and you have to remove an entry again from the
317 LDAP server, just call the delete method, like
318
319 $conn->delete($entry->getDN());
320
321 You can't use native Perl functions like push() and splice() on
322 attribute values, since they won't update the ::Entry instance state
323 properly. Instead use one of the methods provided by the
324 Mozilla::LDAP::Entry object class, for instance
325
326 $entry->addValue("cn", "The Swede");
327 $entry->removeValue("mailAlternateAddress", "leif@mcom.com");
328 $entry->remove("seeAlso");
329
330 These methods return a TRUE or FALSE value, depending on the outcome of
331 the operation. If there was no value to remove, or a value already
332 exists, we return FALSE, otherwise TRUE. To check if an attribute has a
333 certain value, use the hasValue method, like
334
335 if ($entry->hasValue("mail", "leif@netscape.com")) {
336 # Do something
337 }
338
339 There is a similar method, matchValue, which takes a regular expression
340 to match against, instead of the entire string. For more information
341 this and other methods in the Entry class, see below.
342
344 We have already described the fundamentals of this class earlier. This
345 is a summary of all available methods which you can use. Be careful not
346 to use any undocumented features or heaviour, since the internals in
347 this module is likely to change.
348
349 Searching and updating entries
350
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 mod‐
446 ule. It requires at least three arguments: The Base DN,
447 the scope, and the search strings. Two more optional argu‐
448 ments can be given, the first specifies if only attribute
449 names should be returned (TRUE or FALSE). The second argu‐
450 ment 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 signfi‐
455 cantly reduce the search time. An example of an efficient
456 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 cre‐
474 dentials (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 exam‐
477 ple:
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
506 getErrorCode Return the error code (numeric) from the last LDAP API
507 function call. Remember that this can only be called after
508 the successful creation of a new :Conn object instance. A
509 typical usage could be
510
511 if (! $opt_n) {
512 $conn->modifyRDN($rdn, $entry->getDN());
513 $conn->printError() if $conn->getErrorCode();
514 }
515
516 Which will report any error message as generated by the
517 call to modifyRDN. Some LDAP functions return extra error
518 information, which can be retrieved like:
519
520 $err = getErrorCode(\$matched, \$string);
521
522 $matched will then contain the portion of the matched DN
523 (if applicable to the error code), and $string will con‐
524 tain any additional error string returned by the LDAP
525 server.
526
527 getErrorString
528 Very much like getErrorCode, but return a string with a
529 human readable error message. This can then be used to
530 print a good error message on the console.
531
532 getLD Return the (internal) LDAP* connection handle, which you
533 can use (carefully) to call the native LDAP API functions.
534 You shouldn't have to use this in most cases, unless of
535 course our OO layer is seriously flawed.
536
537 getRes Just like getLD, except it returns the internal LDAP
538 return message structure. Again, use this very carefully,
539 and be aware that this might break in future releases of
540 PerLDAP. These two methods can be used to call some useful
541 API functions, like
542
543 $cld = $conn->getLD();
544 $res = $conn->getRes();
545 $count = Mozilla::LDAP::API::ldap_count_entries($cld, $res);
546
547 isURL Returns TRUE or FALSE if the given argument is a properly
548 formed URL.
549
550 printError Print the last error message on standard output.
551
552 setRebindProc
553 Tell the LDAP SDK to call the provided Perl function when
554 it has to follow referrals. The Perl function should
555 return an array of three elements, the new Bind DN, pass‐
556 word and authentication method. A typical usage is
557
558 sub rebindProc {
559 return ("uid=ldapadmin", "secret", LDAP_AUTH_SIMPLE);
560 }
561
562 $ld->setRebindProc(\&rebindProc);
563
564 setDefaultRebindProc
565 This is very much like the previous function, except
566 instead of specifying the function to use, you give it the
567 DN, password and Auth method. Then we'll use a default
568 rebind procedure (internal in C) to handle the rebind cre‐
569 dentials. This was a solution for the Windows/NT prob‐
570 lem/bugs we have with rebind procedures written in Perl.
571
572 setVersion Change the LDAP protocol version on the already initial‐
573 ized connection. The default is LDAP v3 (new for PerLDAP
574 v1.5!), but you can downgrade the connection to LDAP v2 if
575 necessary using this function. Example:
576
577 $conn->setVersion(2);
578
579 getVersion Return the protocol version currently in used by the con‐
580 nection.
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 connec‐
604 tion 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 pack‐
618 age. See the installation procedures which are part of this package.
619
621 This package can be retrieved from a number of places, including:
622
623 http://www.mozilla.org/directory/
624 Your local CPAN server
625
627 Most of this code was developed by Leif Hedstrom, Netscape Communica‐
628 tions Corporation.
629
631 None. :)
632
634 Mozilla::LDAP::Entry, LDAP::Mozilla:Utils LDAP::Mozilla:API and of
635 course Perl.
636
637
638
639perl v5.8.8 2007-06-14 Conn(3)