Что такое код ldap_count_entries


Содержание

Что такое код ldap_count_entries

These routines are used to parse results received from ldap_result (3) or the synchronous LDAP search operation routines ldap_search_s (3) and ldap_search_st (3).

The ldap_first_entry() routine is used to retrieve the first entry in a chain of search results. It takes the result as returned by a call to ldap_result (3) or ldap_search_s (3) or ldap_search_st (3) and returns a pointer to the first entry in the result.

This pointer should be supplied on a subsequent call to ldap_next_entry() to get the next entry, the result of which should be supplied to the next call to ldap_next_entry() , etc. ldap_next_entry() will return NULL when there are no more entries. The entries returned from these calls are used in calls to the routines described in ldap_get_dn (3), ldap_first_attribute (3), ldap_get_values (3), etc.

A count of the number of entries in the search result can be obtained by calling ldap_count_entries() .

PHP ldap_get_entries() return count = zero

Я пытаюсь аутентифицировать логин пользователей против LDAP (сервер Mac El Capitan).
Я могу успешно подключиться и подключиться к серверу ldap.
Я могу искать и сортировать результат.
Но когда я выполняю «ldap_get_entries», я получил запись «Zero».
Я пробовал все: от StackOverFlow до второй страницы Google.
Любые предложения или идеи, почему это может произойти?

‘; echo » «; $fentry= ldap_first_entry($ldap, $result); echo «First Entry = «.$fentry; for ($i=0; $i 1) break; echo «

You are accessing «. $info[$i][«sn»][0] .», » . $info[$i][«givenname»][0] .»
(» . $info[$i][«samaccountname»][0] .»)

\n»; echo »; $userDn = $info[$i][«distinguishedname»][0]; > ldap_close($ldap); > else < echo "Cannot Connect To LDAP."; >>> ?>

Я могу подключиться — bind — search Но «ldap_get_entries()» возвращает ноль.

Во-первых: вы можете пропустить or die «Could not connect to LDAP Server» поскольку этого почти никогда не произойдет. ldap_connect проверяет только параметр синтаксической корректности и фактически не подключается к серверу. Фактическое соединение происходит при первом вызове сервера, который обычно является ldap_bind . Поэтому проблемы с подключением часто ldap_bind на ldap_bind а не на ldap_connect .

Во-вторых: Откуда у вас имя samAccountName ? Это поле, которое обычно используется ActiveDirectory. В Apples OpenDirectory пользователь обычно идентифицируется с помощью uid -attribute. Таким образом, ваш фильтр должен быть sprintf(‘u >.

В-третьих: я сомневаюсь, что только пользователям в группе «Администраторы открытых каталогов» разрешено связывать LDAP. Они наверняка являются единственными, кому разрешено редактировать каталог, но каждый другой пользователь может также связываться.

В-четвертых: ldap_sort устарела. Он не сортируется на стороне сервера, а на стороне клиента. Таким образом, только отсортированные результаты сортируются. Когда вы выталкиваете результаты, это означает, что — хотя вы отсортировали результат — все равно будут записи, которые будут соответствовать прямо между вашими результатами. В настоящее время я работаю над тем, чтобы использовать сортировку на стороне сервера, но это зависит от того, какая функция будет доступна на сервере. Таким образом, вы можете использовать ldap_sort, но вы также можете реализовать свою собственную сортировку по набору результатов.

Поэтому измените фильтр на u > и вы получите ожидаемые результаты. Атрибут mail может также содержать полный адрес электронной почты и, следовательно, может быть с ошибкой! Вы также можете настроить фильтр для поиска нескольких полей. Посмотрите на этот слайд для кратких примеров.

authentication — PHP ldap_get_entries() return count = zero

Я пытаюсь аутентифицировать логин пользователей против LDAP (сервер Mac El Capitan).
Я могу успешно подключиться и подключиться к серверу ldap.
Я могу искать и сортировать результат.
Но когда я выполняю «ldap_get_entries», я получил запись «Zero».
Я пробовал все: от StackOverFlow до второй страницы Google.
Любые предложения или идеи, почему это может произойти?

; echo » «; $fentry= ldap_first_entry($ldap, $result); echo «First Entry = «.$fentry; for ($i=0; $i 1) break; echo «

You are accessing «. $info[$i][«sn»][0] .», » . $info[$i][«givenname»][0] .»
(» . $info[$i][«samaccountname»][0] .»)

n»; echo ; $userDn = $info[$i][«distinguishedname»][0]; > ldap_close($ldap); > else < echo "Cannot Connect To LDAP."; >>> ?>

Я могу подключиться — bind — search Но «ldap_get_entries()» возвращает ноль.

    2 2
  • 30 апр 2020 2020-04-30 09:57:22
  • PSone

2 ответа

Решил. Я использовал «mail» вместо «sAMAccountName».
Здесь подробности —

Извлечение уроков отсюда —

Используйте «Инструмент администрирования LDAP» или какой-то инструмент LDAP, чтобы понять структуру вашей среды LDAP перед тем, как перейти к кодированию. Выучил большой урок.

  • 30 апр 2020 2020-04-30 09:57:23
  • PSone

Во-первых: вы можете пропустить or die «Could not connect to LDAP Server» поскольку этого почти никогда не произойдет. ldap_connect проверяет только параметр синтаксической корректности и фактически не подключается к серверу. Фактическое соединение происходит при первом вызове сервера, который обычно является ldap_bind . Поэтому проблемы с подключением часто ldap_bind на ldap_bind а не на ldap_connect .

Во-вторых: Откуда у вас имя samAccountName ? Это поле, которое обычно используется ActiveDirectory. В Apples OpenDirectory пользователь обычно идентифицируется с помощью uid -attribute. Таким образом, ваш фильтр должен быть sprintf(u >.

В-третьих: я сомневаюсь, что только пользователям в группе «Администраторы открытых каталогов» разрешено связывать LDAP. Они наверняка являются единственными, кому разрешено редактировать каталог, но каждый другой пользователь может также связываться.

В-четвертых: ldap_sort устарела. Он не сортируется на стороне сервера, а на стороне клиента. Таким образом, только отсортированные результаты сортируются. Когда вы выталкиваете результаты, это означает, что — хотя вы отсортировали результат — все равно будут записи, которые будут соответствовать прямо между вашими результатами. В настоящее время я работаю над тем, чтобы использовать сортировку на стороне сервера, но это зависит от того, какая функция будет доступна на сервере. Таким образом, вы можете использовать ldap_sort, но вы также можете реализовать свою собственную сортировку по набору результатов.

Поэтому измените фильтр на u > и вы получите ожидаемые результаты. Атрибут mail может также содержать полный адрес электронной почты и, следовательно, может быть с ошибкой! Вы также можете настроить фильтр для поиска нескольких полей. Посмотрите на этот слайд для кратких примеров.

ldap_count_entries — Посчитать число записей в результатах поиска

(PHP 4, PHP 5, PHP 7)

ldap_count_entries — Посчитать число записей в результатах поиска

Описание

Возвращает число записей, сохраненных в результате предыдущей операции поиска.

Список параметров

Идентификатор ссылки LDAP, возвращенный функцией ldap_connect() .

Внутренний результат LDAP.

Возвращаемые значения

Возвращает число записей в результате или FALSE в случае ошибки.

Примеры

Пример #1 Пример использования функции ldap-count-entries()

Получение числа записей в результате.

// $ds является действительным идентификатором соединения (см. ldap_connect)

$dn = ‘ou=example,dc=org’;
$filter = ‘(|(sn=Doe*)(givenname=John*))’;
$justthese = array(‘ou’, ‘sn’, ‘givenname’, ‘mail’);

$sr = ldap_search($ds, $dn, $filter, $justthese);

Результатом выполнения данного примера будет что-то подобное:

PHP ldap_get_entries() return count=zero

I am trying to authenticate users’ login against LDAP(Server is Mac El Capitan).
I can successfully connect and bind to the ldap server.
I can search and sort the result.
But when I perform «ldap_get_entries»,I received «Zero» entry.
I’ve tried everything from StackOverFlow to Google’s second page.
Any Suggestions or idea why this might be happening?

‘; echo » «; $fentry= ldap_first_entry($ldap, $result); echo «First Entry = «.$fentry; for ($i=0; $i 1) break; echo «

You are accessing «. $info[$i][«sn»][0] .», » . $info[$i][«givenname»][0] .»
(» . $info[$i][«samaccountname»][0] .»)

\n»; echo »; $userDn = $info[$i][«distinguishedname»][0]; > ldap_close($ldap); > else < echo "Cannot Connect To LDAP."; >>> ?>

I can connect — bind — search But «ldap_get_entries()» returns zero.

2 Answers 2

First: You can skip the or die «Could not connect to LDAP Server» as that will almost never happen. ldap_connect only checks the parameter for syntactical correctness and does not actually connect to the server. The actual connection happens on the first call to the server which usually is ldap_bind . That’s why conncetion issues often surface on ldap_bind and not on ldap_connect .

Second: Where did you get samAccountName from? That’s a field that’s usually used by ActiveDirectory. In Apples OpenDirectory the user is usually identified by the uid -attribute. So your filter should be sprintf(‘u >.

Third: I doubt that only Users in the group «Open Directory Administrators» are allowed to bind agains the LDAP. They for sure are the only ones allowed to edit the directory but every other user can bind as well.

Fourth: ldap_sort is deprecated by now. It’s not sorting on the server side but on the client side. So only the returned results are sorted. When you have paged results that means that — even though you sorted the result — there still will be entries that would fit right in between your results. I’m currently working on a way to use server-sided sorting but that relies on the feature to be available on the server. So you can use ldap_sort but you can also implement your own sorting on the result set.

So change the filter to u > and you’ll get the expected results. The mail attribute might also contain the full email-address and might therefore then fail! You can also adapt the filter to search more than one field. Have a look at this slide for short examples.

4
The DBMS_LDAP PL/SQL Package

This chapter introduces the DBMS_LDAP package, which enables PL/SQL programmers to access data from LDAP servers. It provides examples of how to use DBMS_LDAP. This chapter contains these topics:

About the DBMS_LDAP Package

The PL/SQL API in the DBMS_LDAP package is based on the C API described in Chapter 3, «C API for Oracle Internet Directory».

You can use the Oracle Internet Directory API Release 9.2 in the following modes:

  • SSL—All communication secured using SSL
  • Non-SSL—Client-to-server communication not secure

The API uses TCP/IP to connect to an LDAP server. When it does this, it uses, by default, an unencrypted channel. To use the SSL mode, you must use the Oracle SSL call interface. You determine which mode you are using by the presence or absence of the SSL calls in the API usage. You can easily switch between SSL and non-SSL modes.

Building Applications with DBMS_LDAP

To use the PL/SQL LDAP API, you must first load it into the database. You do this by using a script called catldap.sql that is located in the $ ORACLE_HOME /rdbms/admin directory. You must be connected as SYSDBA using the SQL*Plus command line tool.

The following is a sample command sequence that you can use to load the DBMS_LDAP package:

Dependencies and Limitations

The PL/SQL LDAP API for this release has the following limitations:

    The LDAP session handles obtained from the API are val >DBMS_LDAP Sample Programs

This distribution of Oracle Internet Directory ships with sample programs that illustrate the use of DBMS_LDAP in a relational environment. The samples illustrate the use of the DBMS_LDAP API for the following:

  • Synchronizing changes in relational tables to LDAP using database triggers
  • Retrieving LDAP entries that match a certain search criteria

The samples are located in the directory $ORACLE_HOME/ldap/demo/plsql .

Appendix B, «Sample Usage» for a detailed description of the samples

DBMS_LDAP Reference

DBMS_LDAP contains the functions and procedures which can be used by PL/SQL programmers to access data from LDAP servers. This section explains all of the API functions in detail. Be sure that you have read the previous sections before using this section.

This section contains these topics:

Summary of Subprograms

Table 4-1 DBMS_LDAP API Subprograms

init() initializes a session with an LDAP server. This actually establishes a connection with the LDAP server.

The function simple_bind_s can be used to perform simple user name/password based authentication to the directory server.

The function bind_s can be used to perform complex authentication to the directory server.

The function unbind_s is used for closing an active LDAP session.

The function compare_s can be used to test if a particular attribute in a particular entry has a particular value.

The function search_s performs a synchronous search in the LDAP server. It returns control to the PL/SQL environment only after all of the search results have been sent by the server or if the search request is ‘timed-out’ by the server.

The function search_st performs a synchronous search in the LDAP server with a client side time-out. It returns control to the PL/SQL environment only after all of the search results have been sent by the server or if the search request is ‘timed-out’ by the client or the server.

The function first_entry is used to retrieve the first entry in the result set returned by either search_s or search_st.

The function next_entry() is used to iterate to the next entry in the result set of a search operation.

This function is used to count the number of entries in the result set. It can also be used to count the number of entries remaining during a traversal of the result set using a combination of the functions first_entry() and next_entry().

The function first_attribute() fetches the first attribute of a given entry in the result set.

The function next_attribute() fetches the next attribute of a given entry in the result set.

The function get_dn() retrieves the X.500 distinguished name of given entry in the result set.

The function get_values() can be used to retrieve all of the values associated for a given attribute in a given entry.

The function get_values_len() can be used to retrieve values of attributes that have a ‘Binary’ syntax.

This function can be used to remove a leaf entry in the LDAP Directory Information Tree.

The function modrdn2_s() can be used to rename the relative distinguished name of an entry.

The function err2string() can be used to convert an LDAP error code to string in the local language in which the API is operating.

The function create_mod_array() allocates memory for array modification entries that will be applied to an entry using the modify_s() functions.

Populates one set of attribute information for add or modify operations. This procedure call has to happen after DBMS_LDAP.create_mod_array() is called.

Populates one set of attribute information for add or modify operations. This procedure call has to happen after DBMS_LDAP.create_mod_array() is called.

Performs a synchronous modification of an existing LDAP directory entry. Before calling add_s , we have to call DBMS_LDAP.creat_mod_array () and DBMS_LDAP.populate_mod_array () first.

Adds a new entry to the LDAP directory synchronously. Before calling add_s , we have to call DBMS_LDAP.creat_mod_array () and DBMS_LDAP.populate_mod_array () first.

Frees the memory allocated by DBMS_LDAP.create_mod_array ().

Counts the number of values returned by DBMS_LDAP.get_values ().

Counts the number of values returned by DBMS_LDAP.get_values_len ().

Renames an LDAP entry synchronously.

Breaks a DN up into its components.

Establishes an SSL (Secure Sockets Layer) connection over an existing LDAP connection.

This function frees the chain of messages associated with the message handle returned by synchronous search functions.

This function frees the memory associated with a handle to BER ELEMENT.

Function or Procedure Description
See Also:
  • Searching by Using DBMS_LDAP for information about the DBMS_LDAP.search_s() and DBMS_LDAP.search_st() functions
  • Enabling Session Termination by Using DBMS_LDAP for information about the DBMS_LDAP.unbind_s() function

Exception Summary

DBMS_LDAP can generate the following exceptions:

Table 4-2 DBMS_LDAP Exception Summary

Raised anytime an error is encountered that does not have a specific PL/SQL exception associated with it. The error string contains the description of the problem in the local language of the user.

Raised by DBMS_LDAP.init() if there are some problems.

Raised by all functions and procedures in the DBMS_LDAP package if they are passed an invalid session handle.

Raised by DBMS_LDAP.bind_s() if the authentication method requested is not supported.

Raised by all of the ‘search’ functions if the scope of the search is invalid.

Raised by time based search function: DBMS_LDAP.search_st() if it is given an invalid value for the time limit.

Raised by all functions that iterate through a result-set for getting entries from a search operation if the message handle given to them is invalid.

Raised by DBMS_LDAP.count_entries if it cannot count the entries in a given result set.

Raised by DBMS_LDAP.get_dn if the DN of the entry it is retrieving is NULL.

Raised by all the functions that modify/add/rename an entry if they are presented with an invalid entry DN.

Raised by all functions that take a modification array as an argument if they are given an invalid modification array.

Raised by DBMS_LDAP.populate_mod_array if the modification option given is anything other than MOD_ADD, MOD_DELETE or MOD_REPLACE.

Raised by DBMS_LDAP.populate_mod_array if the attribute type that is being modified is NULL.

Raised by DBMS_LDAP.populate_mod_array if the modification value parameter for a given attribute is NULL.

Raised by all functions and procedures that expect a valid RDN if the value of the RDN is NULL.

Raised by DBMS_LDAP.rename_s if the new parent of an entry being renamed is NULL.

Raised by DBMS_LDAP.rename_s if the deleteoldrdn parameter is invalid.

Raised by DBMS_LDAP.explode_dn if the notypes parameter is invalid.

Raised by DBMS_LDAP.open_ssl if the wallet location is NULL but the SSL authentication mode requires a valid wallet.

Raised by DBMS_LDAP.open_ssl if the wallet password given is NULL.

Raised by DBMS_LDAP.open_ssl if the SSL authentication mode is not one of 1, 2 or 3.

Data-Type Summary

The DBMS_LDAP package uses the following data-types:

Table 4-3 DBMS_LDAP Data-Type Summary
Exception Name Oracle Error Number Cause of Exception

Used to hold the handle of the LDAP session. Nearly all of the functions in the API require a valid LDAP session to work.

Used to hold a handle to the message retrieved from the result set. This is used by all functions that work with entries attributes and values.

Used to hold a handle into the array of modifications being passed into either modify_s() or add_s().

Used to pass time limit information to the LDAP API functions that require a time limit.

Used to hold a handle to a BER structure used for decoding incoming messages.

Used to hold a list of VARCHAR2 strings which can be passed on to the LDAP server.

Used to hold a list of RAW data which represent binary data.

Used to hold a list of BERVAL values that are used for populating a modification array.

Subprograms

FUNCTION init

init() initializes a session with an LDAP server. This actually establishes a connection with the LDAP server.

Syntax
Parameters
Table 4-4 INIT Function Parameters
Data-Type Purpose

Contains a space-separated list of host names or dotted strings representing the IP address of hosts running an LDAP server to connect to. Each hostname in the list MAY include a port number which is separated from the host itself with a colon (:) character. The hosts will be tried in the order listed, stopping with the first one to which a successful connection is made.

Contains the TCP port number to connect to. If a host includes a port number then this parameter is ignored. If this parameter is not specified and the hostname also does not contain the port number, a default port number of 389 is assumed.

Return Values
Table 4-5 INIT Function Return Values
Parameter Description

SESSION (function return)

A handle to an LDAP session which can be used for further calls into the API.

Exceptions
Table 4-6 INIT Function Exceptions
Value Description

Raised when there is a problem contacting the LDAP server.

For all other errors. The error string associated with the exception describes the error in detail.

Usage Notes

DBMS_LDAP.init() is the first function that should be called in order to establish a session to the LDAP server. Function DBMS_LDAP.init() returns a «session handle,» a pointer to an opaque structure that MUST be passed to subsequent calls pertaining to the session. This routine will return NULL and raise the «INIT_FAILED» exception if the session cannot be initialized.Subsequent to the call to init(), the connection has to be authenticated using DBMS_LDAP.bind_s or DBMS_LDAP.simple_bind_s().

See Also

FUNCTION simple_bind_s

The function simple_bind_s can be used to perform simple username/password based authentication to the directory server.

Syntax
Parameters
Table 4-7 SIMPLE_BIND_S Function Parameters
Exception Description

A valid LDAP session handle.

The Distinguished Name of the User that we are trying to login as.

A text string containing the password.

Return Values
Table 4-8 SIMPLE_BIND_S Function Return Values
Parameter Description

PLS_INTEGER (function return)

DBMS_LDAP.SUCCESS on a successful completion. If there was a problem, one of the following exceptions will be raised.

Exceptions
Table 4-9 SIMPLE_BIND_S Function Exceptions
Value Description

Raised if the session handle ld is invalid.

For all other errors. The error string associated with this exception will explain the error in detail.

Usage Notes

DBMS_LDAP.simple_bind_s() can be used to authenticate a user whose directory distinguished name and directory password are known. It can be called only after a valid LDAP session handle is obtained from a call to DBMS_LDAP.init().

FUNCTION bind_s

The function bind_s can be used to perform complex authentication to the directory server.

Syntax
Parameters
Table 4-10 BIND_S Function Parameters
Exception Description

A valid LDAP session handle

The Distinguished Name of the User that we are trying to login as

A text string containing the credentials used for authentication

The authentication method

Return Values
Table 4-11 BIND_S Function Return Values
Parameter Description

PLS_INTEGER (function return)

DBMS_LDAP.SUCCESS on a successful completion. One of the following exceptions is raised if there was a problem.

Exceptions
Table 4-12 BIND_S Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the authentication method requested is not supported.

For all other errors. The error string associated with this exception will explain the error in detail.

Usage Notes

DBMS_LDAP.bind_s() can be used to authenticate a user. It can be called only after a valid LDAP session handle is obtained from a call to DBMS_LDAP.init().


See Also

FUNCTION unbind_s

The function unbind_s is used for closing an active LDAP session.

Syntax
Parameters
Table 4-13 UNBIND_S Function Parameters
Exception Description

A valid LDAP session handle.

Return Values
Table 4-14 UNBIND_S Function Return Values
Parameter Description

PLS_INTEGER (function return)

DBMS_LDAP.SUCCESS on proper completion. One of the following exceptions is raised otherwise.

Exceptions
Table 4-15 UNBIND_S Function Exceptions
Value Description

Raised if the sessions handle ld is invalid.

For all other errors. The error string associated with this exception will explain the error in detail.

Usage Notes

The unbind_s() function, will send an unbind request to the server, close all open connections associated with the LDAP session and dispose of all resources associated with the session handle before returning. After a call to this function, the session handle ld is invalid and it is illegal to make any further LDAP API calls using ld.

See Also

FUNCTION compare_s

The function compare_s can be used to test if a particular attribute in a particular entry has a particular value.

Syntax
Parameters
Table 4-16 COMPARE_S Function Parameters
Exception Description

A valid LDAP session handle

The name of the entry to compare against

The attribute to compare against.

A string attribute value to compare against

Return Values
Table 4-17 COMPARE_S Function Return Values
Parameter Description

PLS_INTEGER (function return)

COMPARE_TRUE is the given attribute has a matching value.

COMPARE_FALSE if the value of the attribute does not match the value given.

Exceptions
Table 4-18 COMPARE_S Function Exceptions
Value Description

Raised if the session handle ld is invalid.

For all other errors. The error string associated with this exception will explain the error in detail.

Usage Notes

The function compare_s can be used to assert if the value of a given attribute stored in the directory server matches a certain value.This operation can only be performed on attributes whose syntax definition allows them to be compared. The compare_s function can only be called after a valid LDAP session handle has been obtained from the init() function and authenticated using the bind_s() or simple_bind_s() functions.

See Also

FUNCTION search_s

The function search_s performs a synchronous search in the LDAP server. It returns control to the PL/SQL environment only after all of the search results have been sent by the server or if the search request is ‘timed-out’ by the server.

Syntax
Parameters
Table 4-19 SEARCH_S Function Parameters
Exception Description

A valid LDAP session handle.

The dn of the entry at which to start the search.

One of SCOPE_BASE (0x00), SCOPE_ONELEVEL (0x01), or SCOPE_SUBTREE (0x02), indicating the scope of the search.

A character string representing the search filter. The value NULL can be passed to indicate that the filter «(object >

A collection of strings indicating which attributes to return for each matching entry. Passing NULL for this parameter causes all available user attributes to be retrieved. The special constant string NO_ATTRS («1.1») MAY be used as the only string in the array to indicate that no attribute types are to be returned by the server. The special constant string ALL_USER_ATTRS («*») can be used in the attrs array along with the names of some operational attributes to indicate that all user attributes plus the listed operational attributes are to be returned.

A boolean value that MUST be zero if both attribute types and values are to be returned, and non-zero if only types are wanted.

This is a result parameter which will contain the results of the search upon completion of the call. If no results are returned, *res is set to NULL.

Return Values
Table 4-20 SEARCH_S Function Return Value
Parameter Description

PLS_INTEGER (function return)

DBMS_LDAP.SUCCESS if the search operation succeeded. An exception is raised in all other cases.

res (OUT parameter)

If the search succeeded and there are entries, this parameter is set to a NON-NULL value which can be used to iterate through the result set.

Exceptions
Table 4-21 SEARCH_S Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the search scope is not one of SCOPE_BASE, SCOPE_ONELEVEL, or SCOPE_SUBTREE.

For all other errors. The error string associated with this exception will explain the error in detail.

Usage Notes

The function search_s() issues a search operation and does not return control to the user environment until all of the results have been returned from the server. Entries returned from the search (if any) are contained in the res parameter. This parameter is opaque to the caller. Entries, attributes, values, etc., can be extracted by calling the parsing routines described below.

See Also

DBMS_LDAP.search_st(), DBMS_LDAP.first_entry(), DBMS_LDAP.next_entry.

FUNCTION search_st

The function search_st performs a synchronous search in the LDAP server with a client-side time-out. It returns control to the PL/SQL environment only after all of the search results have been sent by the server or if the search request is ‘timed-out’ by the client or the server.

Syntax
Parameters
Table 4-22 SEARCH_ST Function Parameters
Exception Description

A valid LDAP session handle.

The dn of the entry at which to start the search.

One of SCOPE_BASE (0x00), SCOPE_ONELEVEL (0x01), or SCOPE_SUBTREE (0x02), indicating the scope of the search.

A character string representing the search filter. The value NULL can be passed to indicate that the filter «(object >

A collection of strings indicating which attributes to return for each matching entry. Passing NULL for this parameter causes all available user attributes to be retrieved. The special constant string NO_ATTRS («1.1») MAY be used as the only string in the array to indicate that no attribute types are to be returned by the server. The special constant string ALL_USER_ATTRS («*») can be used in the attrs array along with the names of some operational attributes to indicate that all user attributes plus the listed operational attributes are to be returned.

A boolean value that MUST be zero if both attribute types and values are to be returned, and non-zero if only types are wanted.

The time-out value expressed in seconds and microseconds that should be used for this search.

This is a result parameter which will contain the results of the search upon completion of the call. If no results are returned, *res is set to NULL.

Return Values
Table 4-23 SEARCH_ST Function Return Values
Parameter Description

PLS_INTEGER (function return)

DBMS_LDAP.SUCCESS if the search operation succeeded. An exception is raised in all other cases.

res (OUT parameter)

If the search succeeded and there are entries, this parameter is set to a NON_NULL value which can be used to iterate through the result set.

Exceptions
Table 4-24 SEARCH_ST Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the search scope is not one of SCOPE_BASE, SCOPE_ONELEVEL or SCOPE_SUBTREE.

Raised if the time value specified for the time-out is invalid.

For all other errors. The error string associated with this exception will explain the error in detail.

Usage Notes

This function is very similar to DBMS_LDAP.search_s() except that it requires a time-out value to be given.

See Also

DBMS_LDAP.search_s(), DBML_LDAP.first_entry(), DBMS_LDAP.next_entry.

FUNCTION first_entry

The function first_entry is used to retrieve the first entry in the result set returned by either search_s() or search_st()

Syntax
Parameters
Table 4-25 FIRST_ENTRY Function Parameters
Exception Description

A valid LDAP session handle.

The search result, as obtained by a call to one of the synchronous search routines.

Return Values
Table 4-26 FIRST_ENTRY Return Values
Parameter Description

MESSAGE (function return)

A handle to the first entry in the list of entries returned from the LDAP server. It is set to NULL if there was an error and an exception is raised.

Exceptions
Table 4-27 FIRST_ENTRY Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the incoming «msg» handle is invalid.

Usage Notes

The function first_entry() should always be the first function used to retrieve the results from a search operation.

See Also

DBMS_LDAP.next_entry(), DBMS_LDAP.search_s(), DBMS_LDAP.search_st()

FUNCTION next_entry

The function next_entry() is used to iterate to the next entry in the result set of a search operation.

Syntax
Parameters
Table 4-28 NEXT_ENTRY Function Parameters
Exception Description

A valid LDAP session handle.

The search result, as obtained by a call to one of the synchronous search routines.

Return Values
Table 4-29 NEXT_ENTRY Function Return Values
Parameter Description

A handle to the next entry in the list of entries returned from the LDAP server. It is set to null if there was an error and an exception is raised.

Exceptions
Table 4-30 NEXT_ENTRY Function Exceptions
Value Description

Raised if the session handle, ld is invalid.

Raised if the incoming ‘msg’ handle is invalid.

Usage Notes

The function next_entry() should always be called after a call to the function first_entry(). Also, the return value of a successful call to next_entry() should be used as ‘msg’ argument used in a subsequent call to the function next_entry() to fetch the next entry in the list.

See Also

DBMS_LDAP.first_entry(), DBMS_LDAP.search_s(), DBMS_LDAP.search_st()

FUNCTION count_entries

This function is used to count the number of entries in the result set. It can also be used to count the number of entries remaining during a traversal of the result set using a combination of the functions first_entry() and next_entry().

Syntax
Parameters
Table 4-31 COUNT_ENTRY Function Parameters
Exception Description

A valid LDAP session handle

The search result, as obtained by a call to one of the synchronous search routines

Return Values
Table 4-32 COUNT_ENTRY Function Return Values
Parameter Description

PLS INTEGER (function return)

Non-zero if there are entries in the result set

-1 if there was a problem.

Exceptions
Table 4-33 COUNT_ENTRY Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the incoming ‘msg’ handle is invalid.

Raised if there was a problem in counting the entries.

Usage Notes

count_entries() returns the number of entries contained in a chain of entries; if an error occurs such as the res parameter being invalid, -1 is returned. The count_entries() call can also be used to count the number of entries that remain in a chain if called with a message, entry or reference returned by first_message(), next_message(), first_entry(), next_entry(), first_reference(), next_reference().

See Also

FUNCTION first_attribute

The function first_attribute() fetches the first attribute of a given entry in the result set.

Syntax
Parameters
Table 4-34 FIRST_ATTRIBUTE Function Parameter
Exception Description

A valid LDAP session handle

The entry whose attributes are to be stepped through, as returned by first_entry() or next_entry()

A handle to a BER ELEMENT that is used to keep track of which attribute in the entry has been read

Return Values
Table 4-35 FIRST_ATTRIBUTE Function Return Values
Parameter Description

VARCHAR2 (function return)

The name of the attribute if it exists.

NULL if no attribute exists or if an error occurred.

A handle used by DBMS_LDAP.next_attribute() to iterate over all of the attributes

Exceptions
Table 4-36 FIRST_ATTRIBUTE Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the incoming ‘msg’ handle is invalid

Usage Notes

The handle to the BER_ELEMENT returned as a function parameter to first_attribute() should be used in the next call to next_attribute() to iterate through the various attributes of an entry. The name of the attribute returned from a call to first_attribute() can in turn be used in calls to the functions get_values() or get_values_len() to get the values of that particular attribute.

See Also

DBMS_LDAP.next_attribute(), DBMS_LDAP.get_values(), DBMS_LDAP.get_values_len(), DBMS_LDAP.first_entry(), DBMS_LDAP.next_entry().

FUNCTION next_attribute

The function next_attribute() fetches the next attribute of a given entry in the result set.

Syntax
Parameters
Table 4-37 NEXT_ATTRIBUTE Function Parameters
Exception Description

A valid LDAP session handle.

The entry whose attributes are to be stepped through, as returned by first_entry() or next_entry().

A handle to a BER ELEMENT that is used to keep track of which attribute in the entry has been read.

Return Values
Table 4-38 NEXT_ATTRIBUTE Function Return Values
Parameter Description

VARCHAR2 (function return)

The name of the attribute if it exists.

Exceptions
Table 4-39 NEXT_ATTRIBUTE Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the incoming ‘msg’ handle is invalid.

Usage Notes

The handle to the BER_ELEMENT returned as a function parameter to first_attribute() should be used in the next call to next_attribute() to iterate through the various attributes of an entry. The name of the attribute returned from a call to next_attribute() can in turn be used in calls to the functions get_values() or get_values_len() to get the values of that particular attribute.

See Also

DBMS_LDAP.first_attribute(), DBMS_LDAP.get_values(), DBMS_LDAP.get_values_len(), DBMS_LDAP.first_entry(), DBMS_LDAP.next_entry().

FUNCTION get_dn

The function get_dn() retrieves the X.500 distinguished name of given entry in the result set.

Syntax
Parameters
Table 4-40 GET_DN Function Parameters
Exception Description

A valid LDAP session handle.

The entry whose DN is to be returned.

Return Values


Table 4-41 GET_DN Function Return Values
Parameter Description

VARCHAR2 (function return)

The X.500 Distinguished name of the entry as a PL/SQL string.

NULL if there was a problem.

Exceptions
Table 4-42 GET_DN Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the incoming ‘msg’ handle is invalid.

Raised if there was a problem in determining the DN

Usage Notes

The function get_dn() can be used to retrieve the DN of an entry as the program logic is iterating through the result set. This can in turn be used as an input to explode_dn() to retrieve the individual components of the DN.

See Also

FUNCTION get_values

The function get_values() can be used to retrieve all of the values associated for a given attribute in a given entry.

Syntax
Parameters
Table 4-43 GET_VALUES Function Parameters
Exception Description

A valid LDAP session handle

A valid handle to an entry returned from a search result

The name of the attribute for which values are being sought

Return Values
Table 4-44 GET_VALUES Function Return Values
Parameter Description

STRING_COLLECTION (function return)

A PL/SQL string collection containing all of the values of the given attribute

NULL if there are no values associated with the given attribute

Exceptions
Table 4-45 GET_VALUES Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the incoming ‘entry handle’ is invalid.

Usage Notes

The function get_values() can only be called after the handle to entry has been first retrieved by call to either first_entry() or next_entry(). The name of the attribute may be known beforehand or can also be determined by a call to first_attribute() or next_attribute().The function get_values() always assumes that the data-type of the attribute it is retrieving is ‘String’. For retrieving binary data-types, get_values_len() should be used.

See Also

DBMS_LDAP.first_entry(), DBMS_LDAP.next_entry(), DBMS_LDAP.count_values(), DBMS_LDAP.get_values_len().

FUNCTION get_values_len

The function get_values_len() can be used to retrieve values of attributes that have a ‘Binary’ syntax.

Syntax
Parameters
Table 4-46 GET_VALUES_LEN Function Parameters
Exception Description

A valid LDAP session handle.

A valid handle to an entry returned from a search result.

The string name of the attribute for which values are being sought.

Return Values
Table 4-47 GET_VALUES_LEN Function Return Values
Parameter Description

BINVAL_COLLECTION (function return

A PL/SQL ‘Raw’ collection containing all the values of the given attribute.

NULL if there are no values associated with the given attribute.

Exceptions
Table 4-48 GET_VALUES_LEN Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the incoming ‘entry handle’ is invalid

Usage Notes

The function get_values_len() can only be called after the handle to entry has been first retrieved by call to either first_entry() or next_entry().The name of the attribute may be known beforehand or can also be determined by a call to first_attribute() or next_attribute().This function can be used to retrieve both binary and non-binary attribute values.

See Also

DBMS_LDAP.first_entry(), DBMS_LDAP.next_entry(), DBMS_LDAP.count_values_len(), DBMS_LDAP.get_values().

FUNCTION delete_s

The function delete_s() can be used to remove a leaf entry in the LDAP Directory Information Tree.

Syntax
Parameters
Table 4-49 DELETE_S Function Parameters
Exception Description

A valid LDAP session

The X.500 distinguished name of the entry to delete

Return Values
Table 4-50 DELETE_S Function Return Values
Parameter Name Description

PLS_INTEGER (function return)

DBMS_LDAP.SUCCESS if the delete operation wa successful. And exception is raised otherwise.

Exceptions
Table 4-51 DELETE_S Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the distinguished name of the entry is invalid

For all other errors. The error string associated with this exception will explain the error in detail.

Usage Notes

The function delete_s() can be used to remove only leaf level entries in the LDAP DIT. A leaf level entry is an entry that does not have any children/ldap entries under it. It cannot be used to delete non-leaf entries.

See Also

FUNCTION modrdn2_s

The function modrdn2_s() can be used to rename the relative distinguished name of an entry.

Syntax
Parameters
Table 4-52 MODRDN2_S Function Parameters
Exception Description

A valid LDAP session handle.

The distinguished name of the entry (This entry must be a leaf node in the DIT.).

The new relative distinguished name of the entry.

A boolean value that if non-zero indicates that the attribute values from the old name should be removed from the entry.

Return Values
Table 4-53 MODRDN2_S Function Return Values
Parameter Description

PLS_INTEGER (function return)

DBMS_LDAP.SUCCESS if the operation was successful. An exception is raised otherwise.

Exceptions
Table 4-54 MODRDN2_S Function Exceptions
Value Description

Raised if the session handle ld is invalid.

Raised if the distinguished name of the entry is invalid.

Invalid LDAP RDN.

Invalid LDAP deleteoldrdn.

For all other errors. The error string associated with this exception will explain the error in detail.

Usage Notes

The function nodrdn2_s() can be used to rename the leaf nodes of a DIT. It simply changes the relative distinguished name by which they are known. The use of this function is being deprecated in the LDAP v3 standard. Please use rename_s() which can achieve the same foundation.

See Also

FUNCTION err2string

The function err2string() can be used to convert an LDAP error code to string in the local language in which the API is operating

Syntax
Parameters
Table 4-55 ERR2STRING Function Parameters
Exception Description

An error number returned from one the API calls.

Return Values
Table 4-56 ERR2STRING Function Return Values
Parameter Description

VARCHAR2 (function return)

A character string appropriately translated to the local language which describes the error in detail.

Exceptions
Table 4-57 ERR2STRING Function Exceptions
Value Description
Usage Notes

In this release, the exception handling mechanism automatically invokes this if any of the API calls encounter an error.

See Also

FUNCTION create_mod_array

The function create_mod_array() allocates memory for array modification entries that will be applied to an entry using the modify_s() or add_s() functions.

Syntax
Parameters
Table 4-58 CREATE_MOD_ARRAY Function Parameters
Exception Description

The number of the attributes that you want to add/modify.

Return Values
Table 4-59 CREATE_MOD_ARRAY Function Return Values
Parameter Description

MOD_ARRAY (function return)

The data structure holds a pointer to an LDAP mod array.

NULL if there was a problem.

Exceptions
Table 4-60 CREATE_MOD_ARRAY Function Exceptions
Value Description

No LDAP specific exception will be raised

Usage Notes

This function is one of the preparation steps for DBMS_LDAP.add_s and DBMS_LDAP.modify_s. It is required to call DBMS_LDAP.free_mod_array to free memory after the calls to add_s or modify_s have completed.

See Also

DBMS_LDAP.populate_mod_array(), DBMS_LDAP.modify_s(), DBMS_LDAP.add_s(), and DBMS_LDAP.free_mod_array().

PROCEDURE populate_mod_array (String Version)

Populates one set of attribute information for add or modify operations.

Syntax
Parameters
Table 4-61 POPULATE_MOD_ARRAY (String Version) Procedure Parameters
Exception Description

The data structure holds a pointer to an LDAP mod array.

This field specifies the type of modification to perform.

This field indicates the name of the attribute type to which the modification applies.

This field specifies the attribute values to add, delete, or replace. It is for the string values only.

Return Values
Table 4-62 POPULATE_MOD_ARRAY (String Version) Procedure Return Values
Parameter Description
Exceptions
Table 4-63 POPULATE_MOD_ARRAY (String Version) Procedure Exceptions
Value Description

Invalid LDAP mod array

Invalid LDAP mod option

Invalid LDAP mod type

Invalid LDAP mod value

Usage Notes

This function is one of the preparation steps for DBMS_LDAP.add_s and DBMS_LDAP.modify_s. It has to happen after DBMS_LDAP.create_mod_array called.

See Also

DBMS_LDAP.create_mod_array(), DBMS_LDAP.modify_s(), DBMS_LDAP.add_s(), and DBMS_LDAP.free_mod_array().

PROCEDURE populate_mod_array (Binary Version)

Populates one set of attribute information for add or modify operations. This procedure call has to happen after DBMS_LDAP.create_mod_array() called.

Syntax
Parameters
Table 4-64 POPULATE_MOD_ARRAY (Binary Version) Procedure Parameters
Exception Description

The data structure holds a pointer to an LDAP mod array

This field specifies the type of modification to perform

This field indicates the name of the attribute type to which the modification applies

This field specifies the attribute values to add, delete, or replace. It is for the binary values

Return Values
Exceptions
Table 4-65 POPULATE_MOD_ARRAY (Binary Version) Procedure Exceptions
Parameter Description

Invalid LDAP mod array

Invalid LDAP mod option

Invalid LDAP mod type

Invalid LDAP mod value

Usage Notes

This function is one of the preparation steps for DBMS_LDAP.add_s and DBMS_LDAP.modify_s. It has to happen after DBMS_LDAP.create_mod_array called.

See Also

DBMS_LDAP.create_mod_array(), DBMS_LDAP.modify_s(), DBMS_LDAP.add_s(), and DBMS_LDAP.free_mod_array().

FUNCTION modify_s

Performs a synchronous modification of an existing LDAP directory entry.

Syntax
Parameters
Table 4-66 MODIFY_S Function Parameters
Exception Description

This parameter is a handle to an LDAP session, as returned by a successful call to DBMS_LDAP.init().

This parameter specifies the name of the directory entry whose contents are to be modified.

This parameter is the handle to an LDAP mod structure, as returned by successful call to DBMS_LDAP.create_mod_array().

Return Values
Table 4-67 MODIFY_S Function Return Values
Parameter Description

The indication of the success or failure of the modification operation

Exceptions
Table 4-68 MODIFY_S Function Exceptions
Value Description

Invalid LDAP session

Invalid LDAP entry dn

Invalid LDAP mod array

Usage Notes

This function call has to follow successful calls of DBMS_LDAP.create_mod_array() and DBMS_LDAP.populate_mod_array().

See Also

DBMS_LDAP.create_mod_array(),DBMS_LDAP.populate_mod_array(), DBMS_LDAP.add_s(), and DBMS_LDAP.free_mod_array().

FUNCTION add_s

Adds a new entry to the LDAP directory synchronously. Before calling add_s, we have to call DBMS_LDAP.create_mod_array() and DBMS_LDAP.populate_mod_array().

Syntax
Parameters
Table 4-69 ADD_S Function Parameters
Exception Description

This parameter is a handle to an LDAP session, as returned by a successful call to DBMS_LDAP.init().

This parameter specifies the name of the directory entry to be created.

This parameter is the handle to an LDAP mod structure, as returned by successful call to DBMS_LDAP.create_mod_array().

Return Values
Table 4-70 ADD_S Function Return Values


Parameter Description

The indication of the success or failure of the modification operation.

Exceptions
Table 4-71 ADD_S Function Exceptions
Value Description

Invalid LDAP session.

Invalid LDAP entry dn.

Invalid LDAP mod array.

Usage Notes

The parent entry of the entry to be added must already exist in the directory. This function call has to follow successful calls of DBMS_LDAP.create_mod_array() and DBMS_LDAP.populate_mod_array().

See Also

DBMS_LDAP.create_mod_array(),DBMS_LDAP.populate_mod_array(), DBMS_LDAP.modify_s(), and DBMS_LDAP.free_mod_array().

PROCEDURE free_mod_array

Frees the memory allocated by DBMS_LDAP.create_mod_array().

Syntax
Parameters
Table 4-72 FREE_MOD_ARRAY Procedure Parameters
Exception Description

This parameter is the handle to an LDAP mod structure, as returned by successful call to DBMS_LDAP.create_mod_array().

Return Values
Exceptions

No LDAP specific exception will be raised.

Usage Notes
See Also

DBMS_LDAP.populate_mod_array(), DBMS_LDAP.modify_s(), DBMS_LDAP.add_s(), and DBMS_LDAP.create_mod_array().

FUNCTION count_values

Counts the number of values returned by DBMS_LDAP.get_values().

Syntax
Parameters
Table 4-73 COUNT_VALUES Function Parameters
Parameter Description

The collection of string values.

Return Values
Table 4-74 COUNT_VALUES Function Return Values
Parameter Description

The indication of the success or failure of the operation.

Exceptions
Table 4-75 COUNT_VALUES Function Exceptions
Value Description

No LDAP specific exception will be raised.

Usage Notes
See Also

FUNCTION count_values_len

Counts the number of values returned by DBMS_LDAP.get_values_len().

Syntax
Parameters
Table 4-76 COUNT_VALUES_LEN Function Parameters
Exception Description

The collection of binary values.

Return Values
Table 4-77 COUNT_VALUES_LEN Function Return Values
Parameter Description

The indication of the success or failure of the operation.

Exceptions
Table 4-78 COUNT_VALUES_LEN Function Exceptions
Value Description

No LDAP specific exception will be raised.

Usage Notes
See Also

FUNCTION rename_s

Renames an LDAP entry synchronously.

Syntax
Parameters
Table 4-79 RENAME_S Function Parameters
Exception Description

This parameter is a handle to an LDAP session, as returned by a successful call to DBMS_LDAP.init().

This parameter specifies the name of the directory entry to be renamed or moved.

This parameter specifies the new RDN.

This parameter specifies the DN of the new parent.

This parameter specifies if the old RDN should be retained. If this value is 1, then the old RDN will be removed.

Currently not supported.

Currently not supported.

Return Values
Table 4-80 RENAME_S Function Return Values
Parameter Description

The indication of the success or failure of the operation.

Exceptions
Table 4-81 RENAME_S Function Exceptions
Value Description

Invalid LDAP Session.

Invalid LDAP DN.

Invalid LDAP RDN.

Invalid LDAP newparent.

Invalid LDAP deleteoldrdn.

Usage Notes
See Also

FUNCTION explode_dn

Breaks a DN up into its components.

Syntax
Parameters
Table 4-82 EXPLODE_DN Function Parameters
Exception Description

This parameter specifies the name of the directory entry to be broken up.

This parameter specifies if the attribute tags will be returned. If this value is not 0, then there will be no attribute tags will be returned.

Return Values
Table 4-83 EXPLODE_DN Function Return Values
Parameter Description

An array of strings. If the DN can not be broken up, NULL will be returned.

Exceptions
Table 4-84 EXPLODE_DN Function Exceptions
Value Description

Invalid LDAP DN.

Invalid LDAP notypes value.

Usage Notes
See Also

FUNCTION open_ssl

Establishes an SSL (Secure Sockets Layer) connection over an existing LDAP connection.

Syntax
Parameters
Table 4-85 OPEN_SSL Function Parameters
Exception Description

This parameter is a handle to an LDAP session, as returned by a successful call to DBMS_LDAP.init().

This parameter specifies the wallet location (Required for one-way or two-way SSL connection.)

This parameter specifies the wallet password (Required for one-way or two-way SSL connection.)

This parameter specifies the SSL Authentication Mode (1 for no authentication required, 2 for one way authentication required, 3 for two way authentication required.

Return Values
Table 4-86 OPEN_SSL Function Return Values
Parameter Description

The indication of the success or failure of the operation.

Exceptions
Table 4-87 OPEN_SSL Function Exceptions
Value Description

Invalid LDAP Session.

Invalid LDAP SSL wallet location.

Invalid LDAP SSL wallet passwd.

Invalid LDAP SSL authentication mode.

Usage Notes

Need to call DBMS_LDAP.init() first to acquire a valid ldap session.

See Also

FUNCTION msgfree

This function frees the chain of messages associated with the message handle returned by synchronous search functions.

Syntax
Parameters
Table 4-88 MSGFREE Function Parameters
Exception Description

The message handle as obtained by a call to one of the synchronous search routines.

Return Values
Table 4-89 MSGFREE Return Values
Parameter Description

Indicates the type of the last message in the chain.

The function might return any of the following values:

  • DBMS_LDAP.LDAP_RES_BIND
  • DBMS_LDAP.LDAP_RES_SEARCH_ENTRY
  • DBMS_LDAP.LDAP_RES_SEARCH_REFERENCE
  • DBMS_LDAP.LDAP_RES_SEARCH_RESULT
  • DBMS_LDAP.LDAP_RES_MODIFY
  • DBMS_LDAP.LDAP_RES_ADD
  • DBMS_LDAP.LDAP_RES_DELETE
  • DBMS_LDAP.LDAP_RES_MODDN
  • DBMS_LDAP.LDAP_RES_COMPARE
  • DBMS_LDAP.LDAP_RES_EXTENDED
Value Description
Exceptions

N/A. No LDAP-specific exception is raised.

Usage Notes
See Also

FUNCTION ber_free

This function frees the memory associated with a handle to BER ELEMENT.

Syntax
Parameters
Table 4-90 BER_FREE Function Parameters

A handle to BER ELEMENT.

The value of this flag should be zero while the BER ELEMENT returned from DBMS_LDAP.first_attribute() is being freed. For any other case, the value of this flag should be one.

The default value of this parameter is zero.

Что такое код ldap_count_entries

The ldap_count_entries function counts the number of search entries that a server returned.

Syntax

Parameters

The session handle.

The search result obtained by a call to one of the synchronous search routines or to ldap_result.

Return value

If the function succeeds, it returns the number of entries.

If the function fails, the return value is –1 and the function sets the session error parameters in the LDAP data structure.

Remarks

The ldap_count_entries function returns the number of entries contained, or remaining in a chain of entries. Call the function with the return value from ldap_first_entry, ldap_next_entry, ldap_first_reference, ldap_next_reference, or ldap_result.

XLIX. Функции LDAP

LDAP это Lightweight Directory Access Protocol — протокол, используемый для доступа к «Directory Servers». Directory это особый вид базы данных, которая содержит информацию как древовидную структуру.

Концепция аналогична структуре директорий жёсткого диска, но в данном контексте root/корневая директория это «The world/Земной шар», а первый уровень поддиректорий это «countries/страны». Ещё ниже идут уровни структуры директорий, содержащие вхождения для companies/компаний, organisations/организаций или мест, а ещё ниже находятся вхождения директорий для people/людей и, возможно, оборудования или документов.

Чтобы обратиться к файлу в поддиректории на жёстком диске, вы вводите что-нибудь вроде

Слэш отделяет каждое подразделение ссылки, а последовательность читается слева направо.

Эквивалентом для полной квалифицированной ссылки на файл в LDAP является «distinguished name/различительное имя», называемое просто «dn». Примером dn может быть:

cn=John Smith,ou=Accounts,o=My Company,c=US

Запятая работает как слэш, а последовательность читается справа налево. Вы можете прочитать это dn как .

country = US
organization = My Company
organizationalUnit = Accounts
commonName = John Smith

Точно так же, поскольку нет твёрдых правил организации структуры директорий на жёстком диске, directory server manager (менеждер сервера директорий) может настроить любую структуру, необходимую для осуществления поставленных задач. Однако есть некоторые соглашения, которые при этом используются: вы не можете записать код для доступа к серверу директорий, если не знаете его структуру, хотя можете использовать БД без знания того, что доступно.

Запрашиваем информацию для всех вхождений, где фамилия начинается с «S», с сервера директорий и отображаем их с именем и email-адресом.

Пример 1. Пример поиска LDAP

Вам нужно получить и скомпилировать клиентские библиотеки LDAP из пакета ldap-3.3 University of Michigan или Netscape Directory SDK 3.0. Вам нужно также перекомпилировать PHP с включённой поддержкой LDAP, прежде чем вызовы PHP к LDAP заработают.

Прежде чем начать использование вызовов LDAP, вам необходимо знать:


Имя или адрес сервера директорий, который вы будете использовать

«base dn» сервера (часть world-директории, которая содержится на этом сервере, которая может быть «o=My Company,c=US»)

Нужен ли вам пароль для доступа к этому серверу (многие серверы предоставляют доступ для чтения для «anonymous bind», но требуют пароля для других действий)

Типичная последовательность вызова LDAP в вашем приложении будет соответствовать такому патэрну:

ldap_connect() // установить соединение с сервером
|
ldap_bind() // anonymous/анонимный или аутентифицированный «login»
|
сделать что-нибудь типа поиска или обновления директории
и вывести результаты
|
ldap_close() // «logout»

Большое количество информации о LDAP можно найти на:

Netscape SDK содержит хороший Programmer’s Guide в формате .html.

Пример работы с LDAP-каталогом с помощью php API

Левинца Егор, 06 апреля 2012 года.

В порядке эксперимента, а также чтобы оказать помощь человеку в его затруднении, решил написать небольшую утилитку для отображения пользователей (а точнее, учётных записей пользователей), хранящихся в каталоге LDAP, по группам. Эксперимент состоял в том, чтобы обратиться к каталогу и получить из него данные через php API, чего я раньше не делал. Зная общие принципы взаимодействия с LDAP-каталогами и имея опыт написания подобных программ на perl API (с использованием модуля Net::LDAP), сделать это оказалось несложно. Все же я решил описать свою работу — возможно, она поможет кому-нибудь в разработке php-программ, взаимодействующих с LDAP-каталогом.

Исходные данные: имеется каталог (базовый DN dc=mycompany,dc=ru) со «стандартной» структурой для интеграции с samba: сведения об учётных записях пользователей хранятся в ветке ou=Users,dc=myconpany,dc=ru, сведения о группах пользователей — в ветке ou=Groups,dc=mycompany,dc=ru. Основная задача: отобразить нестандартную древовидную структуру: на первом уровне список групп, на втором — принадлежащие этим группам пользователи. Факультативная задача: при выборе пользователя из списка вывести некоторые сведения по нему.

Для упрощения примера подразумевается, что группы строятся на структурном объектном классе posixGroup , атрибут членства в группе — memberUid , значение которого совпадает с атрибутом uid учётной записи пользователя. Если у Вас за членство в группах и учётные записи пользователей отвечают другие атрибуты — измените код программы под Ваши настройки.

LDAP — относительно простой протокол с небольшим количеством операций. В нашем примере мы не собираемся изменять содержимое каталога (осуществляем доступ только для чтения), поэтому вся работа с каталогом будет выполнена за 4 операции: соединение с сервером каталога (connect), подключение к каталогу (bind), выполнение поиска необходимых нам данных (search) с выводом результатов, и, наконец, отключение от сервера (unbind). Все эти операции реализованы в php функциями с «говорящими» названиями: ldap_connect() , ldap_bind() , ldap_search() и ldap_unbind() . Эти и другие функции работы с LDAP в php описаны в соответствующей странице документации по php. Описаны, кстати, довольно неплохо, с хорошими примерами.

Поскольку при выполнении основной и факультативной задач осуществляются абсолютно одинаковые операции соединения, подключения и отключения от сервера, я решил вынести их в основную часть программы, а различающиеся операции поиска и отображения полученных в результате поиска данных — в отдельные функции. В первой функции get_main() производится поиск сведений о группах в ветке ou=Groups,dc=mycompany,dc=ru. Найденные группы, а также члены каждой из групп сортируются по алфавиту и выводится html-страница с древовидной структурой. Чтобы не изобретать велосипедов с отображением древовидной структуры, я воспользовался готовым модулем dhtmlxTree библиотеки компонентов dhtmlx. Вызов второй функции get_userinfo() выполняется при обращении к программе из ajax-запроса, генерируемого при нажатии на пользователя — члена группы в выведенной в браузер html-странице. В этой функции выполняется поиск в ветке ou=Users,dc=myconpany,dc=ru на совпадение имени пользователя с содержимым атрибута uid. Выбранные в результате поиска атрибуты записи пользователя оформляются в виде таблицы и загружаются в соответствующее информационное поле на html-странице.

‘; // Вывод таблицы с запрашиваемыми данными echo ‘

Parameter Description
‘; foreach($LDAP[‘Attrs’] as $attr=>$desc) < echo '

‘; > echo ‘

‘ . $desc . ‘ ‘; if(isset($entries[0][$attr])) < array_shift($entries[0][$attr]); echo join('
‘, $entries[0][$attr]); > echo ‘

‘; > ?>

Выглядит это так:

Код программы с библиотеками dhtmlx и набором иконок можно скачать одним архивом здесь (

Tutorial: searching LDAP entries¶

A more pythonic LDAP: LDAP operations look clumsy and hard-to-use because they reflect the age-old idea that time-consuming operations should be done on the client in order not to clutter and hog the server with unneeded elaboration. ldap3 includes a fully functional Abstraction Layer that lets you interact with the DIT in a modern and pythonic way. With the Abstraction Layer you don’t need to directly issue any LDAP operation at all.

Finding entries¶

To find entries in the DIT you must use the Search operation. This operation has a number of parameters, but only two of them are mandatory:

  • search_base : the location in the DIT where the search will start
  • search_filter : a string that describes what you are searching for

Search filters are based on assertions and look odd when you’re unfamiliar with their syntax. One assertion is a bracketed expression that affirms something about an attribute and its values, as (givenName=John) or (maxRetries>=10) . On the server, each assertion resolves to True, False, or Undefined (which is treated as False) for one or more entries in the DIT. Assertions can be grouped in boolean groups where all assertions (and group, specified with & ) or at least one assertion (or group, specified with | ) must be True. A single assertion can be negated (not group, specified with ! ). Each group must be bracketed, allowing for recursive filters.

Operators allowed in an assertion are = (equal), (less than or equal), >= (greater than or equal), =* (present),

= (approximate), and := (extensible). Surprisingly the less than and the greater than operators don’t exist in the LDAP filter syntax. The aproximate and the extensible operators are obscure and seldom used. In an equality filter you can use the * character as a wildcard.

For example, to search for all users named John with an email ending with ‘ @ example . org’ the filter will be (&(givenName=John)(mail=*@example.org)) , to search for all users named John or Fred with an email ending in ‘ @ example . org’ the filter will be (&(|(givenName=Fred)(givenName=John))(mail=*@example.org)) , while to search for all users that have a givenName different from Smith the filter will be (!(givenName=Smith)) .

Long search filters are difficult to understand. It may be useful to divide the text on multiple indented lines:

Let’s search all users in the FreeIPA demo LDAP server:

Here you request all the entries of >

response vs result: in ldap3 every operation has a result that is stored in the result attribute of the Connection in sync strategies. Search operations store the found entries in the response attribute of the Connection object. For asynchronous strategies you must use the get_response(id) method that returns a tuple in the form of (response, result). If you use the get_request=True parameter you ask get_response() to also return the request dictionary, so the returned tuple will be (response, result, request).

Now let’s try to request some attributes from the admin user:

When using attributes in a search filter, it’s a good habit to always request for the structural class of the objects you expect to retrieve. Why? You cannot be sure that the attribute you’re searching for is not used is some other object class. Even if you are sure that no other object class uses it, this attribute could always change in the future when the schema is extended with an object class that uses that very same attribute, thus leading your program to suddenly break for no apparent reason.

Note that the entries attribute of the Connection object is derived from the ldap3 Abstraction Layer and it’s specially crafted to be used in interactive mode at the >>> prompt. It gives a visual representation of the entry data structure and each value is, according to the schema, properly formatted (the date value in krbLastPwdChange is actually stored as b’20201009010118Z’ , but it’s shown as a Python date object). Attributes can be queried either as a > values and raw_values

Note that the entry status is Read. This is not relevant if you only need to retrieve the entries from the DIT but it’s vital if you want to take advantage of the ldap3 Abstraction Layer making it Writable and change or delete its content via the Abstraction Layer. The Abstraction Layer also records the time of the last data read operation for the entry.

In the previous search operations you specified dc=demo1,dc=freeipa,dc=org as the base of the search, but the entries you were returned were in the cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org context of the DIT. So the server has, with no apparent reason, walked down every context under the base applying the filter to each of the entries in the sub-containers. The server actually performed a whole subtree search. Other possible kinds of searches are the single level search (that searches only in the level specified in the base) and the base object search (that searches only in the attributes of the entry specified in the base). What changes in this different kinds of search is the ‘breadth’ of the portion of the DIT that is searched. This breadth is called the scope of the search and can be specified with the search_scope parameter of the search operation. It can take three different values: BASE , LEVEL and SUBTREE . The latter value is the default for the search operation, so this clarifies why you got back all the entries in the sub-containers of the base in previous searches.

You can have a LDIF representation of the response of a search with:

LDIF stands for LDAP Data Interchange Format and is a textual standard used to describe two different aspects of LDAP: the content of an entry (LDIF-CONTENT) and the changes performed on an entry with an LDAP operation (LDIF-CHANGE). LDIF-CONTENT is used to describe LDAP entries in an stream (i.e. a file or a socket), while LDIF-CHANGE is used to describe the Add, Delete, Modify and ModifyDn operations.

These two formats have different purposes and cannot be mixed in the same stream.

or you can save the response to a JSON string:

Searching for binary values¶

To search for a binary value you must use the RFC4515 ASCII escape sequence for each unicode point in the search assertion. ldap3 provides the helper function escape_bytes(byte_value) in ldap3.utils.conv to properly escape a byte sequence:

search_filter will contain (nsUnique > . The xx escaping format is specific to the LDAP protocol.

Entries Retrieval¶

Raw values for the attributes retrieved in an entry are stored in the raw_attributes dictonary in the response attribute. ldap3 prov > get_info=SCHEMA or get_info=ALL in the Server object) and the check_names parameter of the Connection object is set to True, the attributes attribute is populated with the formatted values. If the attribute is defined in the schema as multi valued, then the attribute value is returned as a list (even if only a single value is present) else it’s returned as a single value.

Custom formatters can be added to specify how attribute values are returned. A formatter must be a callable that receives a bytes value and returns an object. It should never raise exceptions but it must return the original value if it’s not able to properly format the object.

What about empty attributes?В¶

The LDAP protocol specifies that an attribute always contain a value. An attribute with no value is immediately removed by the LDAP server in the stored entry. This feature makes it harder to access the entry in your code because you must always check if an attribute key is present before accessing its value to avo > attributes parameter of the search operation. To change this behaviour, you must set the return_empty_attributes parameter to False in the Connection object.

Simple Paged search¶

The Search operation can perform a simple paged search as specified in RFC 2696. The RFC states that you can ask the server to return a specific number of entries in each response set. With each search, the server sends back a cookie that you have to prov > paged_search() function of the extend.standard namespace:

Entries are returned in a generator, which can be useful when you have very long list of entries or have memory limitations. Also, it sends the requests to the LDAP server only when entries are consumed in the generator. Remember, a generator can be used only one time, so you must elaborate the results in a sequential way. If you don’t want the entries returned in a generator, you can pass the generator=False parameter to get all the entries in a list. In this case all the paged searches are performed by the paged_search() function and the set of entries found are queued in a list.

If you want to directly use the Search operation to perform a Paged search your code should be similar to the following:

Even in this case, the ldap3 library hides the Simple Paged Control machinery, but you have to manage the cookie by yourself. The code would be much longer if you would directly manage the Simple Search Control. Also, you lose the generator feature.

After performing a traditional LDAP Search operation with a SYNC strategy, you get back a collection of Entries in the entries property of the Connection object. This collection behaves as the Entries collection of a Reader cursor. For more comprehensive information about the Search operation, see the SEARCH documentation. An Entry in the entries collection can be modified making it Writable and applying modifications to it as described in the next chapter.

© Copyright 2020 Giovanni Cannata Revision 5f019016 .

Илон Маск рекомендует:  Запись синтаксиса
Понравилась статья? Поделиться с друзьями:
Кодинг, CSS и SQL