8 C API Reference

This chapter introduces the Oracle Internet Directory C API and provides examples of how to use it.

The chapter contains these topics:

8.1 About the Oracle Internet Directory C API

The Oracle Internet Directory SDK C API is based on LDAP Version 3 C API and Oracle extensions to support SSL.

You can use the Oracle Internet Directory API 11g Release 1 (11.1.1) in the following modes:

  • SSL—All communication secured by using SSL

  • Non-SSL—Client/server communication not secure

The API uses TCP/IP to connect to a directory 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.

See Also:

Section 8.3, "Sample C API Usage" for more details on how to use the two modes.

This section contains these topics:

8.1.1 Oracle Internet Directory SDK C API SSL Extensions

Oracle SSL extensions to the LDAP API are based on standard SSL protocol. The SSL extensions provide encryption and decryption of data over the wire and authentication.

There are three modes of authentication:

  • None—Neither client nor server is authenticated, and only SSL encryption is used

  • One-way—Only the server is authenticated by the client

  • Two-way—Both the server and the client are authenticated by each other

The type of authentication is indicated by a parameter in the SSL interface call.

8.1.1.1 SSL Interface Calls

There is only one call required to enable SSL:

int ldap_init_SSL(Sockbuf *sb, char *sslwallet, char *sslwalletpasswd, int sslauthmode)

The ldap_init_SSL call performs the necessary handshake between client and server using the standard SSL protocol. If the call is successful, then all subsequent communication happens over a secure connection.

Table 8-1 Arguments for SSL Interface Calls

Argument Description
sb

Socket buffer handle returned by the ldap_open call as part of LDAP handle.

sslwallet

Location of the user wallet.

sslwalletpasswd

Password required to use the wallet.

sslauthmode

SSL authentication mode user wants to use. Possible values are:

  • GSLC_SSL_NO_AUTH—No authentication required

  • GSLC_SSL_ONEWAY_AUTH—Only server authentication required.

  • GSLC_SSL_TWOWAY_AUTH—Both server and client authentication required.

    A return value of 0 indicates success. A nonzero return value indicates an error. The error code can be decoded by using the function ldap_err2string.




8.1.1.2 Wallet Support

depending on which authentication mode is being used, both the server and the client may require wallets to use the SSL feature. 11g Release 1 (11.1.1) of the API supports only the Oracle Wallet. You can create wallets by using Oracle Wallet Manager.

8.2 Functions in the C API

This section examines each of the functions and procedures in the C API. It explains their purpose and syntax. It also provides tips for using them.

The section contains the following topics:

8.2.1 The Functions at a Glance

Table 8-2 lists all of the functions and procedures in the C API and briefly explains their purpose.

Table 8-2 Functions and Procedures in the C API

Function or Procedure Description
ber_free

Free the memory allocated for a BerElement structure

ldap_abandon_ext
ldap_abandon

Cancel an asynchronous operation

ldap_add_ext
ldap_add_ext_s
ldap_add
ldap_add_s

Add a new entry to the directory

ldap_compare_ext
ldap_compare_ext_s
ldap_compare
ldap_compare_s

Compare entries in the directory

ldap_count_entries

Count the number of entries in a chain of search results

ldap_count_values

Count the string values of an attribute

ldap_count_values_len

Count the binary values of an attribute

ora_ldap_create_clientctx

Create a client context and returns a handle to it.

ora_ldap_create_cred_hdl

Create a credential handle.

ldap_delete_ext
ldap_delete_ext_s
ldap_delete
ldap_delete_s

Delete an entry from the directory

ora_ldap_destroy_clientctx

Destroy the client context.

ora_ldap_free_cred_hdl

Destroy the credential handle.

ldap_dn2ufn

Converts the name into a more user friendly format

ldap_err2string

Get the error message for a specific error code

ldap_explode_dn

Split up a distinguished name into its components

ldap_explode_rdn
 
ldap_first_attribute

Get the name of the first attribute in an entry

ldap_first_entry

Get the first entry in a chain of search results

ora_ldap_get_cred_props

Retrieve properties associated with credential handle.

ldap_get_dn

Get the distinguished name for an entry

ldap_get_option

Access the current value of various session-wide parameters

ldap_get_values

Get the string values of an attribute

ldap_get_values_len

Get the binary values of an attribute

ldap_init
ldap_open

Open a connection to an LDAP server

ora_ldap_init_SASL

Perform SASL authentication

ldap_memfree

Free memory allocated by an LDAP API function call

ldap_modify_ext
ldap_modify_ext_s
ldap_modify
ldap_modify_s

Modify an entry in the directory

ldap_msgfree

Free the memory allocated for search results or other LDAP operation results

ldap_first_attribute
ldap_next_attribute

Get the name of the next attribute in an entry

ldap_next_entry

Get the next entry in a chain of search results

ldap_perror

(Deprecated)

Prints the message supplied in message.

ldap_rename
ldap_rename_s

Modify the RDN of an entry in the directory

ldap_result2error

(Deprecated)

Return the error code from result message.

ldap_result
ldap_msgfree
ldap_msgtype
ldap_msgid

Check the results of an asynchronous operation

ldap_sasl_bind
ldap_sasl_bind_s

General authentication to an LDAP server

ldap_search_ext
ldap_search_ext_s
ldap_search
ldap_search_s

Search the directory

ldap_search_st

Search the directory with a timeout value

ldap_get_option
ldap_set_option

Set the value of these parameters

ldap_set_rebind_proc 

Set the callback function to be used to get bind credential to a new server when chasing referrals.

ora_ldap_set_clientctx

Add properties to the client context handle.

ora_ldap_set_cred_props

Add properties to credential handle.

ldap_simple_bind
ldap_simple_bind_s
ldap_sasl_bind
ldap_sasl_bind_s

Simple authentication to an LDAP server

ldap_unbind_ext
ldap_unbind
ldap_unbind_s

End an LDAP session

ldap_value_free

Free the memory allocated for the string values of an attribute

ldap_value_free
ldap_value_free_len

Free the memory allocated for the binary values of an attribute


This section lists all the calls available in the LDAP C API found in RFC 1823.

See Also:

The following URL for a more detailed explanation of these calls:

http://www.ietf.org

8.2.2 Initializing an LDAP Session

The calls in this section initialize a session with an LDAP server.

8.2.2.1 ldap_init and ldap_open

ldap_init() initializes a session with an LDAP server, but does not open a connection. The server is not actually contacted until an operation is performed that requires it, allowing various options to be set after initialization. ldap_open() initializes a session and opens a connection. The two fulfill the same purpose and have the same syntax, but the first is preferred.

Syntax

LDAP *ldap_init
(
    const char     *hostname,
    int            portno
)
;

Parameters

Table 8-3 Parameters for Initializing an LDAP Session

Parameter Description
hostname

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 host name in the list may include a port number. The two must be separated by a colon. The hosts are tried in the order listed until a successful connection occurs.

IPv6 addresses must be enclosed in brackets ([]). The following are examples of valid hostname values:

host1.example.com

192.168.1.10

[2002:ae5:4000:1::8c57:352]

host1.example.com:3060

192.168.1.10:3060

[2002:ae5:4000:1::8c57:352]:3060

portno

Contains the TCP port number to connect to. The default LDAP port of 3060 can be obtained by supplying the constant LDAP_PORT. If hostname includes a port number, portno is ignored.


Usage Notes

ldap_init() and ldap_open() both return a session handle. This is a pointer to an opaque structure that must be passed to subsequent calls pertaining to the session. These routines return NULL if the session cannot be initialized. If the session cannot be initialized, check the error reporting mechanism for the operating system to see why the call failed.

Note that if you connect to an LDAPv2 server, one of the LDAP bind calls described later SHOULD be completed before other operations can be performed on the session. LDAPv3 does not require that a bind operation be completed before other operations are performed.

The calling program can set various attributes of the session by calling the routines described in the next section.

8.2.3 LDAP Session Handle Options

The LDAP session handle returned by ldap_init() is a pointer to an opaque data type representing an LDAP session. In RFC 1823 this data type was a structure exposed to the caller, and various fields in the structure could be set to control aspects of the session, such as size and time limits on searches.

In the interest of insulating callers from inevitable changes to this structure, these aspects of the session are now accessed through a pair of accessor functions, described in this section.

8.2.3.1 ldap_get_option and ldap_set_option

ldap_get_option() is used to access the current value of various session-wide parameters. ldap_set_option() is used to set the value of these parameters. Note that some options are read only and cannot be set; it is an error to call ldap_set_option() and attempt to set a read only option.

Note that if automatic referral following is enabled (the default), any connections created during the course of following referrals inherit the options associated with the session that sent the original request that caused the referrals to be returned.

Syntax

int ldap_get_option
(
LDAP            *ld,
int             option,
void            *outvalue
)
;

int ldap_set_option
(
LDAP            *ld,
int             option,
const void      *invalue
)
;
#define LDAP_OPT_ON     ((void *)1)
#define LDAP_OPT_OFF    ((void *)0)

Parameters

Table 8-4 lists and describes the parameters for LDAP session handle options.

Table 8-4 Parameters for LDAP Session Handle Options

Parameters Description
ld

The session handle. If this is NULL, a set of global defaults is accessed. New LDAP session handles created with ldap_init() or ldap_open() inherit their characteristics from these global defaults.

option

The name of the option being accessed or set. This parameter should be one of the constants listed and described in Table 8-5. The hexadecimal value of the constant is listed in parentheses after the constant.

outvalue

The address of a place to put the value of the option. The actual type of this parameter depends on the setting of the option parameter. For outvalues of type char ** and LDAPControl **, a copy of the data that is associated with the LDAP session ld is returned. Callers should dispose of the memory by calling ldap_memfree() or ldap_controls_free(), depending on the type of data returned.

invalue

A pointer to the value the option is to be given. The actual type of this parameter depends on the setting of the option parameter. The data associated with invalue is copied by the API implementation to allow callers of the API to dispose of or otherwise change their copy of the data after a successful call to ldap_set_option(). If a value passed for invalue is invalid or cannot be accepted by the implementation, ldap_set_option() should return -1 to indicate an error.


Constants

Table 8-5 lists and describes the constants for LDAP session handle options.

Table 8-5 Constants

Constant Type for invalue parameter Type for outvalue parameter Description
LDAP_OPT_API_INFO(0x00)

Not applicable. Option is read only.

LDAPAPIInfo*

Used to retrieve some basic information about the LDAP API implementation at execution time. Applications need to be able to determine information about the particular API implementation they are using both at compile time and during execution. This option is read only and cannot be set.

ORA_LDAP_OPT_RFRL_CACHE
void* (LDAP_OPT_ON
void* (LDAP_OPT_OFF)
int *

This option determines whether referral cache is enabled or not. If this option is set to LDAP_OPT_ON, the cache is enabled; otherwise, the cache is disabled.

ORA_LDAP_OPT_RFRL_CACHE_SZ
int *
int *

This option sets the size of referral cache. The size is maximum size in terms of number of bytes the cache can grow to. It is set to 1MB by default.

LDAP_OPT_DEREF(0x02)
int *
int *

Determines how aliases are handled during search. It should have one of the following values: LDAP_DEREF_NEVER (0x00), LDAP_DEREF SEARCHING (0x01), LDAP_DEREF_FINDING (0x02), or LDAP_DEREF_ALWAYS (0x03). The LDAP_DEREF_SEARCHING value means aliases are dereferenced during the search but not when locating the base object of the search. The LDAP_DEREF_FINDING value means aliases are dereferenced when locating the base object but not during the search. The default value for this option is LDAP_DEREF_NEVER.

LDAP_OPT_SIZELIMIT(0x03)
int *
int *

A limit on the number of entries to return from a search. A value of LDAP_NO_LIMIT (0) means no limit. The default value for this option is LDAP_NO_LIMIT.

LDAP_OPT_TIMELIMIT(0x04)
int *
int *

A limit on the number of seconds to spend on a search. A value of LDAP_NO_LIMIT (0) means no limit. This value is passed to the server in the search request only; it does not affect how long the C LDAP API implementation itself waits locally for search results. The timeout parameter passed to ldap_search_ext_s() or ldap_result()—both of which are described later in this document—can be used to specify both a local and server side time limit. The default value for this option is LDAP_NO_LIMIT.

LDAP_OPT_REFERRALS(0x08)
void *(LDAP_OPT_ON)
void *(LDAP_OPT_OFF)
int *

Determines whether the LDAP library automatically follows referrals returned by LDAP servers or not. It may be set to one of the constants LDAP_OPT_ON or LDAP_OPT_OFF. Any non-null pointer value passed to ldap_set_option() enables this option. When the current setting is read using ldap_get_option(), a zero value means off and any nonzero value means on. By default, this option is turned on.

LDAP_OPT_RESTART(0X09)
void * (LDAP_OPT_ON)
void * (LDAP_OPT_OFF)
int *

Determines whether LDAP input and output operations are automatically restarted if they stop prematurely. It may be set to either LDAP_OPT_ON or LDAP_OPT_OFF. Any non-null pointer value passed to ldap_set_option() enables this option. When the current setting is read using ldap_get_option(), a zero value means off and any nonzero value means on. This option is useful if an input or output operation can be interrupted prematurely—by a timer going off, for example. By default, this option is turned off.

LDAP_OPT_PROTOCOL_VERSION(0x11)
int *
int *

This option indicates the version of the LDAP protocol used when communicating with the primary LDAP server. The option should be either LDAP_VERSION2 (2) or LDAP_VERSION3 (3). If no version is set, the default is LDAP_VERSION2 (2).

LDAP_OPT_SERVER_CONTROLS(0x12)
LDAPControl**
LDAPControl***

A default list of LDAP server controls to be sent with each request.

See Also: Section 8.2.7, "Working With Controls."

LDAP_OPT_CLIENT_CONTROLS(0x13)
LDAPControl**
LDAPControl***

A default list of client controls that affect the LDAP session.

See Also: Section 8.2.7, "Working With Controls."

LDAP_OPT_API_FEATURE_INFO(0x15)

Not applicable. Option is read only.

LDAPAPIFeatureInfo *

Used to retrieve version information about LDAP API extended features at execution time. Applications need to be able to determine information about the particular API implementation they are using both at compile time and during execution. This option is read only. It cannot be set.

LDAP_OPT_HOST_NAME(0x30)
char *
char **

The host name (or list of hosts) for the primary LDAP server. See the definition of the hostname parameter for ldap_init() to determine the syntax.

LDAP_OPT_ERROR_NUMBER(0x31)
int *
int *

The code of the most recent LDAP error during this session.

LDAP_OPT_ERROR_STRING(0x32)
char *

-

The message returned with the most recent LDAP error during this session.

LDAP_OPT_MATCHED_DN(0x33)
char *
char **

The matched DN value returned with the most recent LDAP error during this session.

ORA_LDAP_OPT_CONNECT_TIMEOUT (0xD2)
int *
int *

This option sets the LDAP connection timeout value in seconds. The connection timeout must be set before calling ldap_open. Valid values are 0 – 300 seconds. If the value is set to 0, then the timeout defaults to TCP timeout. If this option is not set, then ldap_open() call times out in 15 sec if the host is not reachable.


Usage Notes

Both ldap_get_option() and ldap_set_option() return 0 if successful and -1 if an error occurs. If -1 is returned by either function, a specific error code may be retrieved by calling ldap_get_option() with an option value of LDAP_OPT_ERROR_NUMBER. Note that there is no way to retrieve a more specific error code if a call to ldap_get_option() with an option value of LDAP_OPT_ERROR_NUMBER fails.

When a call to ldap_get_option() succeeds, the API implementation MUST NOT change the state of the LDAP session handle or the state of the underlying implementation in a way that affects the behavior of future LDAP API calls. When a call to ldap_get_option() fails, the only session handle change permitted is setting the LDAP error code (as returned by the LDAP_OPT_ERROR_NUMBER option).

When a call to ldap_set_option() fails, it must not change the state of the LDAP session handle or the state of the underlying implementation in a way that affects the behavior of future LDAP API calls.

Standards track documents that extend this specification and specify new options should use values for option macros that are between 0x1000 and 0x3FFF inclusive. Private and experimental extensions should use values for the option macros that are between 0x4000 and 0x7FFF inclusive. All values less than 0x1000 and greater than 0x7FFF that are not defined in this document are reserved and should not be used. The following macro must be defined by C LDAP API implementations to aid extension implementers:

#define LDAP_OPT_PRIVATE_EXTENSION_BASE 0x4000  /* to 0x7FFF inclusive */

8.2.4 Getting Bind Credentials for Chasing Referrals

The functions in this section are used to get the bind credentials of a new server while chasing referrals.

8.2.4.1 ldap_set_rebind_proc

The ldap_set_rebind_proc() function is used to set the callback function that the library uses to get the bind credentials for connecting to a new server while chasing LDAP referrals. The library uses the callback function only if LDAP_OPT_REFERRALS is set using ldap_set_option(). If ldap_set_rebind_proc() is not called, then the library uses an anonymous bind to connect to the new server while chasing LDAP referrals.

Syntax

void ldap_set_rebind_proc
(
LDAP          *ld,
int(*rebindproc) (LDAP   *ld,
                 char  **dnp,
                 char  **passwdp,
                 int    *authmethodp,
                 int     freeit)
)

The reprocbind() function is the function to be called to get the bind credentials of the new server.

Table 8-6 Parameters for Callback Function and for Setting Callback Function

Parameter Description
ld

The session handle

rebindproc

The callback function to be used to get the bind credentials for connecting to a new server while chasing LDAP referrals

ld

The session handle to the new server

dnp

Pointer to bind dn for new server

passwdp

Pointer to bind password for new server

authmethodp

Pointer to authentication method for new server

freeit

0 - returns bind dn pointer, bind password pointer, and bind authentication method pointer for new server

1 - frees any memory allocated in previous call


When the freeit parameter value is 0, then rebindproc must return bind dn pointer, bind password pointer, and bind authentication method pointer. When the freeit parameter value is 1, then rebindproc must free any memory allocated in the previous call. The LDAP library call this function twice, first to get the bind credentials and second time to free the memory.

8.2.5 Authenticating to the Directory

The functions in this section are used to authenticate an LDAP client to an LDAP directory server.

8.2.5.1 ldap_sasl_bind, ldap_sasl_bind_s, ldap_simple_bind, and ldap_simple_bind_s

The ldap_sasl_bind() and ldap_sasl_bind_s() functions can be used to do general and extensible authentication over LDAP through the use of the Simple Authentication Security Layer. The routines both take the DN to bind as, the method to use, as a dotted-string representation of an object identifier (OID) identifying the method, and a struct berval holding the credentials. The special constant value LDAP_SASL_SIMPLE (NULL) can be passed to request simple authentication, or the simplified routines ldap_simple_bind() or ldap_simple_bind_s() can be used.

Syntax

int ldap_sasl_bind
(
LDAP                    *ld,
const char              *dn,
const char              *mechanism,
const struct berval     *cred,
LDAPControl             **serverctrls,
LDAPControl             **clientctrls,
int                     *msgidp
);
int ldap_sasl_bind_s(
LDAP                    *ld,
const char              *dn,
const char              *mechanism,
const struct berval     *cred,
LDAPControl             **serverctrls,
LDAPControl             **clientctrls,
struct berval           **servercredp
);
int ldap_simple_bind(
LDAP                    *ld,
const char              *dn,
const char              *passwd
);
int ldap_simple_bind_s(
LDAP                    *ld,
const char              *dn,
const char              *passwd
);

The use of the following routines is deprecated and more complete descriptions can be found in RFC 1823:

  • int ldap_bind( LDAP *ld, const char *dn, const char *cred, int method );

  • int ldap_bind_s( LDAP *ld, const char *dn, const char *cred, int method );

  • int ldap_kerberos_bind( LDAP *ld, const char *dn );

  • int ldap_kerberos_bind_s( LDAP *ld, const char *dn );

Parameters

Table 8-7 lists and describes the parameters for authenticating to the directory.

Table 8-7 Parameters for Authenticating to the Directory

Parameter Description
ld

The session handle

dn

The name of the entry to bind as

mechanism

Either LDAP_SASL_SIMPLE (NULL) to get simple authentication, or a text string identifying the SASL method

cred

The credentials with which to authenticate. Arbitrary credentials can be passed using this parameter. The format and content of the credentials depends on the setting of the mechanism parameter.

passwd

For ldap_simple_bind(), the password to compare to the entry's userPassword attribute

serverctrls

List of LDAP server controls

clientctrls

List of client controls

msgidp

This result parameter is set to the message id of the request if the ldap_sasl_bind() call succeeds

servercredp

This result parameter is filled in with the credentials passed back by the server for mutual authentication, if given. An allocated berval structure is returned that should be disposed of by calling
ber_bvfree(). NULL should be passed to ignore this field.


Usage Notes

Additional parameters for the deprecated routines are not described. Interested readers are referred to RFC 1823.

The ldap_sasl_bind() function initiates an asynchronous bind operation and returns the constant LDAP_SUCCESS if the request was successfully sent, or another LDAP error code if not. If successful, ldap_sasl_bind() places the message id of the request in *msgidp. A subsequent call to ldap_result() can be used to obtain the result of the bind.

The ldap_simple_bind() function initiates a simple asynchronous bind operation and returns the message id of the operation initiated. A subsequent call to ldap_result(), described in, can be used to obtain the result of the bind. In case of error, ldap_simple_bind() returns -1, setting the session error parameters in the LDAP structure appropriately.

The synchronous ldap_sasl_bind_s() and ldap_simple_bind_s() functions both return the result of the operation, either the constant LDAP_SUCCESS if the operation was successful, or another LDAP error code if it was not.

Note that if an LDAPv2 server is contacted, no other operations over the connection can be attempted before a bind call has successfully completed.

Subsequent bind calls can be used to re-authenticate over the same connection, and multistep SASL sequences can be accomplished through a sequence of calls to ldap_sasl_bind() or ldap_sasl_bind_s().

See Also:

Section 8.2.12, "Handling Errors and Parsing Results" for more information about possible errors and how to interpret them.

8.2.6 SASL Authentication Using Oracle Extensions

This section contains the following topics:

8.2.6.1 ora_ldap_init_SASL

The function ora_ldap_init_SASL() can be used for SASL based authentication. It performs authentication based on the mechanism specified as one of its input arguments.

This function encapsulates the SASL handshake between the client and the directory server for various standard SASL mechanisms thereby reducing the coding effort involved in establishing a SASL-based connection to the directory server.

Syntax

int ora_ldap_init_SASL
(
                OraLdapClientCtx * clientCtx,
                LDAP                    *ld,
                char                    * dn,
                char                    * mechanism,
                OraLdapHandle            cred,
                LDAPControl                     **serverctrls,
                LDAPControl                     **clientctrls
);

Parameters

Table 8-8 Parameters passed to ora_ldap_init_sasl()

Parameter Description
clientCtx

C API Client context. This can be managed using ora_ldap_init_clientctx() and ora_ldap_free_clientctx() functions.

ld

Ldap session handle.

dn

User DN to be authenticated.

mechanism

SASL mechanism.

cred

Credentials needed for SASL authentication.

serverctrls

List of LDAP server controls

clientctrls

List of client controls


The cred parameter is a SASL credential handle for the user. This handle can be managed using ora_ldap_create_cred_hdl(), ora_ldap_set_cred_props() and ora_ldap_free_cred_hdl() functions.

Supported SASL mechanisms:

  • DIGEST-MD5

    The Oracle Internet Directory SASL API supports the authentication-only mode of DIGEST-MD5. The other two authentication modes addressing data privacy and data integrity are yet to be supported.

    While authenticating against Oracle Internet Directory, the DN of the user has to be normalized before it is sent across to the server. This can be done either outside the SASL API using the ora_ldap_normalize_dn() function before the DN is passed on to the SASL API or with the SASL API by setting the ORA_LDAP_CRED_SASL_NORM_AUTHDN option in SASL credentials handle using ora_ldap_set_cred_handle().

  • EXTERNAL:

    The SASL API and SASL implementation in Oracle Internet Directory use SSL authentication as one of the external authentication mechanisms.

    Using this mechanism requires that the SSL connection (mutual authentication mode) be established to the directory server by using the ora_ldap_init_SSL() function. The ora_ldap_init_SASL() function can then be invoked with the mechanism argument as EXTERNAL. The directory server would then authenticate the user based on the user credentials in SSL connection.

8.2.6.2 ora_ldap_create_cred_hdl, ora_ldap_set_cred_props, ora_ldap_get_cred_props, and ora_ldap_free_cred_hdl

Use these functions to create and manage SASL credential handles. The ora_ldap_create_cred_hdl function should be used to create a SASL credential handle of certain type based on the type of mechanism used for SASL authentication. The ora_ldap_set_cred_props() function can be used to add relevant credentials to the handle needed for SASL authentication. The ora_ldap_get_cred_props() function can be used for retrieving the properties stored in the credential handle, and the ora_ldap_free_cred_hdl() function should be used to destroy the handle after its use.

Syntax

OraLdapHandle ora_ldap_create_cred_hdl
(
        OraLdapClientCtx * clientCtx,
        int                 credType
); 

OraLdapHandle ora_ldap_set_cred_props
(
        OraLdapClientCtx *   clientCtx,
        OraLdapHandle        cred,
        int                  String[],
        void             *   inProperty
); 
OraLdapHandle ora_ldap_get_cred_props
(
        OraLdapClientCtx *   clientCtx,
        OraLdapHandle   cred,
        int                     String[],
        void                   *   outProperty
); 

OraLdapHandle ora_ldap_free_cred_hdl 
(
        OraLdapClientCtx *   clientCtx,
        OraLdapHandle   cred
); 

Parameters

Table 8-9 Parameters for Managing SASL Credentials

Parameter Description
clientCtx

C API Client context. This can be managed using ora_ldap_init_clientctx() and ora_ldap_free_clientctx() functions.

credType

Type of credential handle specific to SASL mechanism.

cred

Credential handle containing SASL credentials needed for a specific SASL mechanism for SASL authentication.

String[]

Type of credential, which must be added to credential handle.

inProperty

One of the SASL Credentials to be stored in credential handle.

outProperty

One of the SASL credentials stored in credential handle.


8.2.7 Working With Controls

LDAPv3 operations can be extended through the use of controls. Controls can be sent to a server or returned to the client with any LDAP message. These controls are referred to as server controls.

The LDAP API also supports a client-side extension mechanism through the use of client controls. These controls affect the behavior of the LDAP API only and are never sent to a server. A common data structure is used to represent both types of controls:

typedef struct ldapcontrol 
{
char            *ldctl_oid;
struct berval   ldctl_value;
char            ldctl_iscritical;
} LDAPControl;

The fields in the ldapcontrol structure are described in Table 8-10.

Table 8-10 Fields in ldapcontrol Structure

Field Description
ldctl_oid

The control type, represented as a string.

ldctl_value

The data associated with the control (if any). To specify a zero-length value, set ldctl_value.bv_len to zero and ldctl_value.bv_val to a zero-length string. To indicate that no data is associated with the control, set ldctl_value.bv_val to NULL.

ldctl_iscritical

Indicates whether the control is critical of not. If this field is nonzero, the operation is only carried out if the control is recognized by the server or the client. Note that the LDAP unbind and abandon operations have no server response. Clients should not mark server controls critical when used with these two operations.


See Also:

Chapter 3, "Extensions to the LDAP Protocol" for more information about controls.

Some LDAP API calls allocate an ldapcontrol structure or a NULL-terminated array of ldapcontrol structures. The following routines can be used to dispose of a single control or an array of controls:

void ldap_control_free( LDAPControl *ctrl );
void ldap_controls_free( LDAPControl **ctrls );

If the ctrl or ctrls parameter is NULL, these calls do nothing.

A set of controls that affect the entire session can be set using the ldap_set_option() function described in Section 8.2.3.1, "ldap_get_option and ldap_set_option." A list of controls can also be passed directly to some LDAP API calls such as ldap_search_ext(), in which case any controls set for the session through the use of ldap_set_option() are ignored. Control lists are represented as a NULL-terminated array of pointers to ldapcontrol structures.

Server controls are defined by LDAPv3 protocol extension documents; for example, a control has been proposed to support server-side sorting of search results.

One client control is defined in this chapter (described in the following section).

Client-Controlled Referral Processing As described previously in Section 8.2.3, "LDAP Session Handle Options," applications can enable and disable automatic chasing of referrals on a session-wide basic by using the ldap_set_option() function with the LDAP_OPT_REFERRALS option. It is also useful to govern automatic referral chasing on per-request basis. A client control with an object identifier (OID) of 1.2.840.113556.1.4.616 exists to provide this functionality.

/* OID for referrals client control */
#define LDAP_CONTROL_REFERRALS              "1.2.840.113556.1.4.616"

/* Flags for referrals client control value */
#define LDAP_CHASE_SUBORDINATE_REFERRALS    0x00000020U
#define LDAP_CHASE_EXTERNAL_REFERRALS       0x00000040U

To create a referrals client control, the ldctl_oid field of an LDAPControl structure must be set to LDAP_CONTROL_REFERRALS ("1.2.840.113556.1.4.616") and the ldctl_value field must be set to a four-octet value that contains a set of flags. The ldctl_value.bv_len field must always be set to 4. The ldctl_value.bv_val field must point to a four-octet integer flags value. This flags value can be set to zero to disable automatic chasing of referrals and LDAPv3 references altogether. Alternatively, the flags value can be set to the value LDAP_CHASE_SUBORDINATE_REFERRALS (0x00000020U) to indicate that only LDAPv3 search continuation references are to be automatically chased by the API implementation, to the value LDAP_CHASE_EXTERNAL_REFERRALS (0x00000040U) to indicate that only LDAPv3 referrals are to be automatically chased, or the logical OR of the two flag values (0x00000060U) to indicate that both referrals and references are to be automatically chased.

See Also:

"Directory Schema Administration" in Oracle Fusion Middleware Administrator's Guide for Oracle Internet Directory for more information about object identifiers.

8.2.8 Closing the Session

Use the functions in this section to unbind from the directory, to close open connections, and to dispose of the session handle.

8.2.8.1 ldap_unbind, ldap_unbind_ext, and ldap_unbind_s

ldap_unbind_ext(), ldap_unbind(), and ldap_unbind_s() all work synchronously in the sense that they send an unbind request to the server, close all open connections associated with the LDAP session handle, and dispose of all resources associated with the session handle before returning. Note, however, that there is no server response to an LDAP unbind operation. All three of the unbind functions return LDAP_SUCCESS (or another LDAP error code if the request cannot be sent to the LDAP server). After a call to one of the unbind functions, the session handle ld is invalid and it is illegal to make any further LDAP API calls using ld.

The ldap_unbind() and ldap_unbind_s() functions behave identically. The ldap_unbind_ext() function allows server and client controls to be included explicitly, but note that since there is no server response to an unbind request there is no way to receive a response to a server control sent with an unbind request.

Syntax

int ldap_unbind_ext( LDAP *ld, LDAPControl **serverctrls,
LDAPControl **clientctrls );
int ldap_unbind( LDAP *ld );
int ldap_unbind_s( LDAP *ld );

Parameters

Table 8-11 Parameters for Closing the Session

Parameter Description
ld

The session handle

serverctrls

List of LDAP server controls

clientctrls

List of client controls


8.2.9 Performing LDAP Operations

Use the functions in this section to search the LDAP directory and to return a requested set of attributes for each entry matched.

8.2.9.1 ldap_search_ext, ldap_search_ext_s, ldap_search, and ldap_search_s

The ldap_search_ext() function initiates an asynchronous search operation and returns the constant LDAP_SUCCESS if the request was successfully sent, or another LDAP error code if not. If successful, ldap_search_ext() places the message id of the request in *msgidp. A subsequent call to ldap_result() can be used to obtain the results from the search. These results can be parsed using the result parsing routines described in detail later.

Similar to ldap_search_ext(), the ldap_search() function initiates an asynchronous search operation and returns the message id of the operation initiated. As for ldap_search_ext(), a subsequent call to ldap_result() can be used to obtain the result of the bind. In case of error, ldap_search() returns -1, setting the session error parameters in the LDAP structure appropriately.

The synchronous ldap_search_ext_s(), ldap_search_s(), and ldap_search_st() functions all return the result of the operation, either the constant LDAP_SUCCESS if the operation was successful, or another LDAP error code if it was not. Entries returned from the search, if any, are contained in the res parameter. This parameter is opaque to the caller. Entries, attributes, values, and so on, can be extracted by calling the parsing routines described in this section. The results contained in res should be freed when no longer in use by calling ldap_msgfree(), which is described later.

The ldap_search_ext() and ldap_search_ext_s() functions support LDAPv3 server controls, client controls, and allow varying size and time limits to be easily specified for each search operation. The ldap_search_st() function is identical to ldap_search_s() except that it takes an additional parameter specifying a local timeout for the search. The local search timeout is used to limit the amount of time the API implementation waits for a search to complete. After the local search timeout expires, the API implementation sends an abandon operation to stop the search operation.

See Also:

Section 8.2.12, "Handling Errors and Parsing Results" for more information about possible errors and how to interpret them.

Syntax

int ldap_search_ext
(
LDAP            *ld,
const char      *base,
int             scope,
const char      *filter,
char            **attrs,
int             attrsonly,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls,
struct timeval  *timeout,
int             sizelimit,
int             *msgidp
);

int ldap_search_ext_s
(
LDAP            *ld,
const char      *base,
int             scope,
const char      *filter,
char            **attrs,
int             attrsonly,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls,
struct timeval  *timeout,
int             sizelimit,
LDAPMessage     **res
);

int ldap_search
(
LDAP            *ld,
const char      *base,
int             scope,
const char      *filter,
char            **attrs,
int             attrsonly
);

int ldap_search_s
(
LDAP            *ld,
const char      *base,
int             scope,
const char      *filter,
char            **attrs,
int             attrsonly,
LDAPMessage     **res
);

int ldap_search_st
);
LDAP            *ld,
const char      *base,
int             scope,
const char      *filter,
char            **attrs,
int             attrsonly,
struct timeval  *timeout,
LDAPMessage     **res
);

Parameters

Table 8-12 lists and describes the parameters for search operations.

Table 8-12 Parameters for Search Operations

Parameter Description
ld

The session handle.

base

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

scope

One of LDAP_SCOPE_BASE (0x00), LDAP_SCOPE_ONELEVEL (0x01), or LDAP_SCOPE_SUBTREE (0x02), indicating the scope of the search.

filter

A character string representing the search filter. The value NULL can be passed to indicate that the filter "(objectclass=*)" which matches all entries is to be used. Note that if the caller of the API is using LDAPv2, only a subset of the filter functionality can be successfully used.

attrs

A NULL-terminated array 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 LDAP_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 LDAP_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.

attrsonly

A boolean value that must be zero if both attribute types and values are to be returned, and nonzero if only types are wanted.

timeout

For the ldap_search_st() function, this specifies the local search timeout value (if it is NULL, the timeout is infinite). If a zero timeout (where tv_sec and tv_usec are both zero) is passed, API implementations should return LDAP_PARAM_ERROR. For the ldap_search_ext() and ldap_search_ext_s() functions, the timeout parameter specifies both the local search timeout value and the operation time limit that is sent to the server within the search request. Passing a NULL value for timeout causes the global default timeout stored in the LDAP session handle (set by using ldap_set_option() with the LDAP_OPT_TIMELIMIT parameter) to be sent to the server with the request but an infinite local search timeout to be used. If a zero timeout (where tv_sec and tv_usec are both zero) is passed in, API implementations should return LDAP_PARAM_ERROR. If a zero value for tv_sec is used but tv_usec is nonzero, an operation time limit of 1 should be passed to the LDAP server as the operation time limit. For other values of tv_sec, the tv_sec value itself should be passed to the LDAP server.

sizelimit

For the ldap_search_ext() and ldap_search_ext_s() calls, this is a limit on the number of entries to return from the search. A value of LDAP_NO_LIMIT (0) means no limit.

res

For the synchronous calls, this is a result parameter which contains the results of the search upon completion of the call. If no results are returned, *res is set to NULL.

serverctrls

List of LDAP server controls.

clientctrls

List of client controls.

msgidp

This result parameter is set to the message id of the request if the ldap_search_ext() call succeeds.There are three options in the session handle ld which potentially affect how the search is performed. They are:

  • LDAP_OPT_SIZELIMIT—A limit on the number of entries to return from the search. A value of LDAP_NO_LIMIT (0) means no limit. Note that the value from the session handle is ignored when using the ldap_search_ext() or ldap_search_ext_s() functions.

  • LDAP_OPT_TIMELIMIT—A limit on the number of seconds to spend on the search. A value of LDAP_NO_LIMIT (0) means no limit. Note that the value from the session handle is ignored when using the ldap_search_ext() or ldap_search_ext_s() functions.

  • LDAP_OPT_DEREF—One of LDAP_DEREF_NEVER (0x00), LDAP_DEREF_SEARCHING (0x01), LDAP_DEREF_FINDING (0x02), or LDAP_DEREF_ALWAYS (0x03), specifying how aliases are handled during the search. The LDAP_DEREF_SEARCHING value means aliases are dereferenced during the search but not when locating the base object of the search. The LDAP_DEREF_FINDING value means aliases are dereferenced when locating the base object but not during the search.


8.2.9.2 Reading an Entry

LDAP does not support a read operation directly. Instead, this operation is emulated by a search with base set to the DN of the entry to read, scope set to LDAP_SCOPE_BASE, and filter set to "(objectclass=*)" or NULL. The attrs parameter contains the list of attributes to return.

8.2.9.3 Listing the Children of an Entry

LDAP does not support a list operation directly. Instead, this operation is emulated by a search with base set to the DN of the entry to list, scope set to LDAP_SCOPE_ONELEVEL, and filter set to "(objectclass=*)" or NULL. The parameter attrs contains the list of attributes to return for each child entry.

8.2.9.4 ldap_compare_ext, ldap_compare_ext_s, ldap_compare, and ldap_compare_s

Use these routines to compare an attribute value assertion against an LDAP entry.

The ldap_compare_ext() function initiates an asynchronous compare operation and returns the constant LDAP_SUCCESS if the request was successfully sent, or another LDAP error code if not. If successful, ldap_compare_ext() places the message id of the request in *msgidp. A subsequent call to ldap_result() can be used to obtain the result of the compare.

Similar to ldap_compare_ext(), the ldap_compare() function initiates an asynchronous compare operation and returns the message id of the operation initiated. As for ldap_compare_ext(), a subsequent call to ldap_result() can be used to obtain the result of the bind. In case of error, ldap_compare() returns -1, setting the session error parameters in the LDAP structure appropriately.

The synchronous ldap_compare_ext_s() and ldap_compare_s() functions both return the result of the operation, either the constant LDAP_SUCCESS if the operation was successful, or another LDAP error code if it was not.

The ldap_compare_ext() and ldap_compare_ext_s() functions support LDAPv3 server controls and client controls.

See Also:

Section 8.2.12, "Handling Errors and Parsing Results" for more information about possible errors and how to interpret them.

Syntax

int ldap_compare_ext
(
LDAP                    *ld,
const char              *dn,
const char              *attr,
const struct berval     *bvalue,
LDAPControl             **serverctrls,
LDAPControl             **clientctrls,
int                     *msgidp
);

int ldap_compare_ext_s
(
LDAP                    *ld,
const char              *dn,
const char              *attr,
const struct berval     *bvalue,
LDAPControl             **serverctrls,
LDAPControl             **clientctrls
);

int ldap_compare
(
LDAP                    *ld,
const char              *dn,
const char              *attr,
const char              *value
);
int ldap_compare_s
(
LDAP                    *ld,
const char              *dn,
const char              *attr,
const char              *value
);

Parameters

Table 8-13 lists and describes the parameters for compare operations.

Table 8-13 Parameters for Compare Operations

Parameter Description
ld

The session handle.

dn

The name of the entry to compare against.

attr

The attribute to compare against.

bvalue

The attribute value to compare against those found in the given entry. This parameter is used in the extended routines and is a pointer to a struct berval so it is possible to compare binary values.

value

A string attribute value to compare against, used by the ldap_compare() and ldap_compare_s() functions. Use ldap_compare_ext() or ldap_compare_ext_s() if you need to compare binary values.

serverctrls

List of LDAP server controls.

clientctrls

List of client controls.

msgidp

This result parameter is set to the message id of the request if the ldap_compare_ext() call succeeds.


8.2.9.5 ldap_modify_ext, ldap_modify_ext_s, ldap_modify, and ldap_modify_s

Use these routines to modify an existing LDAP entry.

The ldap_modify_ext() function initiates an asynchronous modify operation and returns the constant LDAP_SUCCESS if the request was successfully sent, or another LDAP error code if not. If successful, ldap_modify_ext() places the message id of the request in *msgidp. A subsequent call to ldap_result() can be used to obtain the result of the modify.

Similar to ldap_modify_ext(), the ldap_modify() function initiates an asynchronous modify operation and returns the message id of the operation initiated. As for ldap_modify_ext(), a subsequent call to ldap_result() can be used to obtain the result of the modify. In case of error, ldap_modify() returns -1, setting the session error parameters in the LDAP structure appropriately.

The synchronous ldap_modify_ext_s() and ldap_modify_s() functions both return the result of the operation, either the constant LDAP_SUCCESS if the operation was successful, or another LDAP error code if it was not.

The ldap_modify_ext() and ldap_modify_ext_s() functions support LDAPv3 server controls and client controls.

See Also:

Section 8.2.12, "Handling Errors and Parsing Results" for more information about possible errors and how to interpret them.

Syntax

typedef struct ldapmod 
{
int             mod_op;
char            *mod_type;
union mod_vals_u
  {
  char            **modv_strvals;
  struct berval   **modv_bvals;
  } mod_vals;
} LDAPMod;
#define mod_values      mod_vals.modv_strvals
#define mod_bvalues     mod_vals.modv_bvals
int ldap_modify_ext
(
LDAP            *ld,
const char      *dn,
LDAPMod         **mods,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls,
int             *msgidp
);

int ldap_modify_ext_s
(
LDAP            *ld,
const char      *dn,
LDAPMod         **mods,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls
);

int ldap_modify
(
LDAP            *ld,
const char      *dn,
LDAPMod         **mods
);
int ldap_modify_s
(
LDAP            *ld,
const char      *dn,
LDAPMod         **mods
);

Parameters

Table 8-14 lists and describes the parameters for modify operations.

Table 8-14 Parameters for Modify Operations

Parameter Description
ld

The session handle

dn

The name of the entry to modify

mods

A NULL-terminated array of modifications to make to the entry

serverctrls

List of LDAP server controls

clientctrls

List of client controls

msgidp

This result parameter is set to the message id of the request if the ldap_modify_ext() call succeeds



Table 8-15 lists and describes the fields in the LDAPMod structure.

Table 8-15 Fields in LDAPMod Structure

Field Description
mod_op

The modification operation to perform. It must be one of LDAP_MOD_ADD (0x00), LDAP_MOD_DELETE (0x01), or LDAP_MOD_REPLACE (0x02). This field also indicates the type of values included in the mod_vals union. It is logically ORed with LDAP_MOD_BVALUES (0x80) to select the
mod_bvalues form. Otherwise, the mod_values form is used.

mod_type

The type of the attribute to modify.

mod_vals

The values (if any) to add, delete, or replace. Only one of the mod_values or mod_bvalues variants can be used, selected by ORing the mod_op field with the constant LDAP_MOD_BVALUES. mod_values is a NULL-terminated array of zero-terminated strings and mod_bvalues is a NULL-terminated array of berval structures that can be used to pass binary values such as images.


Usage Notes

For LDAP_MOD_ADD modifications, the given values are added to the entry, creating the attribute if necessary.

For LDAP_MOD_DELETE modifications, the given values are deleted from the entry, removing the attribute if no values remain. If the entire attribute is to be deleted, the mod_vals field can be set to NULL.

For LDAP_MOD_REPLACE modifications, the attribute has the listed values after the modification, having been created if necessary, or removed if the mod_vals field is NULL. All modifications are performed in the order in which they are listed.

8.2.9.6 ldap_rename and ldap_rename_s

Use these routines to change the name of an entry.

The ldap_rename() function initiates an asynchronous modify DN operation and returns the constant LDAP_SUCCESS if the request was successfully sent, or another LDAP error code if not. If successful, ldap_rename() places the DN message id of the request in *msgidp. A subsequent call to ldap_result() can be used to obtain the result of the rename.

The synchronous ldap_rename_s() returns the result of the operation, either the constant LDAP_SUCCESS if the operation was successful, or another LDAP error code if it was not.

The ldap_rename() and ldap_rename_s() functions both support LDAPv3 server controls and client controls.

See Also:

Section 8.2.12, "Handling Errors and Parsing Results" for more information about possible errors and how to interpret them.

Syntax

int ldap_rename
(
LDAP            *ld,
const char      *dn,
const char      *newrdn,
const char      *newparent,
int             deleteoldrdn,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls,
int             *msgidp
);

int ldap_rename_s
(
LDAP            *ld,
const char      *dn,
const char      *newrdn,
const char      *newparent,
int             deleteoldrdn,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls
);

The use of the following routines is deprecated and more complete descriptions can be found in RFC 1823:

int ldap_modrdn
(
LDAP            *ld,
const char      *dn,
const char      *newrdn
);

int ldap_modrdn_s
(
LDAP            *ld,
const char      *dn,
const char      *newrdn
);

int ldap_modrdn2
(
LDAP            *ld,
const char      *dn,
const char      *newrdn,
int             deleteoldrdn
);

int ldap_modrdn2_s
(
LDAP            *ld,
const char      *dn,
const char      *newrdn,
int             deleteoldrdn
);

Parameters

Table 8-16 lists and describes the parameters for rename operations.

Table 8-16 Parameters for Rename Operations

Parameter Description
ld

The session handle.

dn

The name of the entry whose DN is to be changed.

newrdn

The new RDN to give the entry.

newparent

The new parent, or superior entry. If this parameter is NULL, only the RDN of the entry is changed. The root DN should be specified by passing a zero length string, "". The newparent parameter should always be NULL when using version 2 of the LDAP protocol; otherwise the server's behavior is undefined.

deleteoldrdn

This parameter only has meaning on the rename routines if newrdn is different than the old RDN. It is a boolean value, if nonzero indicating that the old RDN value is to be removed, if zero indicating that the old RDN value is to be retained as non-distinguished values of the entry.

serverctrls

List of LDAP server controls.

clientctrls

List of client controls.

msgidp

This result parameter is set to the message id of the request if the ldap_rename() call succeeds.


8.2.9.7 ldap_add_ext, ldap_add_ext_s, ldap_add, and ldap_add_s

Use these functions to add entries to the LDAP directory.

The ldap_add_ext() function initiates an asynchronous add operation and returns the constant LDAP_SUCCESS if the request was successfully sent, or another LDAP error code if not. If successful, ldap_add_ext() places the message id of the request in *msgidp. A subsequent call to ldap_result() can be used to obtain the result of the add.

Similar to ldap_add_ext(), the ldap_add() function initiates an asynchronous add operation and returns the message id of the operation initiated. As for ldap_add_ext(), a subsequent call to ldap_result() can be used to obtain the result of the add. In case of error, ldap_add() returns -1, setting the session error parameters in the LDAP structure appropriately.

The synchronous ldap_add_ext_s() and ldap_add_s() functions both return the result of the operation, either the constant LDAP_SUCCESS if the operation was successful, or another LDAP error code if it was not.

The ldap_add_ext() and ldap_add_ext_s() functions support LDAPv3 server controls and client controls.

See Also:

Section 8.2.12, "Handling Errors and Parsing Results" for more information about possible errors and how to interpret them.

Syntax

int ldap_add_ext
(
LDAP            *ld,
const char      *dn,
LDAPMod         **attrs,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls,
int             *msgidp
);

int ldap_add_ext_s
(
LDAP            *ld,
const char      *dn,
LDAPMod         **attrs,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls
);

int ldap_add
(
LDAP            *ld,
const char      *dn,
LDAPMod         **attrs
);

int ldap_add_s
(
LDAP            *ld,
const char      *dn,
LDAPMod         **attrs
);

Parameters

Table 8-17 lists and describes the parameters for add operations.

Table 8-17 Parameters for Add Operations

Parameter Description
ld

The session handle.

dn

The name of the entry to add.

attrs

The entry attributes, specified using the LDAPMod structure defined for ldap_modify(). The mod_type and mod_vals fields must be filled in. The mod_op field is ignored unless ORed with the constant LDAP_MOD_BVALUES, used to select the mod_bvalues case of the mod_vals union.

serverctrls

List of LDAP server controls.

clientctrls

List of client controls.

msgidp

This result parameter is set to the message id of the request if the ldap_add_ext() call succeeds.


Usage Notes

Note that the parent of the entry being added must already exist or the parent must be empty—that is, equal to the root DN—for an add to succeed.

8.2.9.8 ldap_delete_ext, ldap_delete_ext_s, ldap_delete, and ldap_delete_s

Use these functions to delete a leaf entry from the LDAP directory.

The ldap_delete_ext() function initiates an asynchronous delete operation and returns the constant LDAP_SUCCESS if the request was successfully sent, or another LDAP error code if not. If successful, ldap_delete_ext() places the message id of the request in *msgidp. A subsequent call to ldap_result() can be used to obtain the result of the delete.

Similar to ldap_delete_ext(), the ldap_delete() function initiates an asynchronous delete operation and returns the message id of the operation initiated. As for ldap_delete_ext(), a subsequent call to ldap_result() can be used to obtain the result of the delete. In case of error, ldap_delete() returns -1, setting the session error parameters in the LDAP structure appropriately.

The synchronous ldap_delete_ext_s() and ldap_delete_s() functions both return the result of the operation, either the constant LDAP_SUCCESS if the operation was successful, or another LDAP error code if it was not.

The ldap_delete_ext() and ldap_delete_ext_s() functions support LDAPv3 server controls and client controls.

See Also:

Section 8.2.12, "Handling Errors and Parsing Results" for more information about possible errors and how to interpret them.

Syntax

int ldap_delete_ext
(
LDAP            *ld,
const char      *dn,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls,
int             *msgidp
);

int ldap_delete_ext_s
(
LDAP            *ld,
const char      *dn,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls
);

int ldap_delete

(
LDAP            *ld,
const char      *dn
);

int ldap_delete_s
(
LDAP            *ld,
const char      *dn
);

Parameters

Table 8-18 lists and describes the parameters for delete operations.

Table 8-18 Parameters for Delete Operations

Parameter Description
ld

The session handle.

dn

The name of the entry to delete.

serverctrls

List of LDAP server controls.

clientctrls

List of client controls.

msgidp

This result parameter is set to the message id of the request if the ldap_delete_ext() call succeeds.


Usage Notes

Note that the entry to delete must be a leaf entry—that is, it must have no children. Deletion of entire subtrees in a single operation is not supported by LDAP.

8.2.9.9 ldap_extended_operation and ldap_extended_operation_s

These routines enable extended LDAP operations to be passed to the server, providing a general protocol extensibility mechanism.

The ldap_extended_operation()function initiates an asynchronous extended operation and returns the constant LDAP_SUCCESS if the request was successfully sent, or another LDAP error code if not. If successful, ldap_extended_operation() places the message id of the request in *msgidp. A subsequent call to ldap_result() can be used to obtain the result of the extended operation which can be passed to ldap_parse_extended_result() to obtain the object identifier (OID) and data contained in the response.

The synchronous ldap_extended_operation_s() function returns the result of the operation, either the constant LDAP_SUCCESS if the operation was successful, or another LDAP error code if it was not. The retoid and retdata parameters are filled in with the OID and data from the response. If no OID or data was returned, these parameters are set to NULL.

The ldap_extended_operation() and ldap_extended_operation_s() functions both support LDAPv3 server controls and client controls.

See Also:

Section 8.2.12, "Handling Errors and Parsing Results" for more information about possible errors and how to interpret them.

Syntax

int ldap_extended_operation
(
LDAP                    *ld,
const char              *requestoid,
const struct berval     *requestdata,
LDAPControl             **serverctrls,
LDAPControl             **clientctrls,
int                     *msgidp
);

int ldap_extended_operation_s
(
LDAP                    *ld,
const char              *requestoid,
const struct berval     *requestdata,
LDAPControl             **serverctrls,
LDAPControl             **clientctrls,
char                    **retoidp,
struct berval           **retdatap
);

Parameters

Table 8-19 lists and describes the parameters for extended operations.

Table 8-19 Parameters for Extended Operations

Parameter Description
ld

The session handle

requestoid

The dotted-OID text string naming the request

requestdata

The arbitrary data needed by the operation (if NULL, no data is sent to the server)

serverctrls

List of LDAP server controls

clientctrls

List of client controls

msgidp

This result parameter is set to the message id of the request if the ldap_extended_operation() call succeeds.

retoidp

Pointer to a character string that is set to an allocated, dotted-OID text string returned by the server. This string should be disposed of using the ldap_memfree() function. If no OID was returned, *retoidp is set to NULL.

retdatap

Pointer to a berval structure pointer that is set an allocated copy of the data returned by the server. This struct berval should be disposed of using ber_bvfree(). If no data is returned, *retdatap is set to NULL.


8.2.10 Abandoning an Operation

Use the functions in this section to abandon an operation in progress:

8.2.10.1 ldap_abandon_ext and ldap_abandon

ldap_abandon_ext() abandons the operation with message id msgid and returns the constant LDAP_SUCCESS if the abandon was successful or another LDAP error code if not.

ldap_abandon() is identical to ldap_abandon_ext() except that it does not accept client or server controls and it returns zero if the abandon was successful, -1 otherwise.

After a successful call to ldap_abandon() or ldap_abandon_ext(), results with the given message id are never returned from a subsequent call to ldap_result(). There is no server response to LDAP abandon operations.

Syntax

int ldap_abandon_ext
(
LDAP            *ld,
int             msgid,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls
);

int ldap_abandon
(
LDAP            *ld,
int             msgid
);

Parameters

Table 8-20 lists and describes the parameters for abandoning an operation.

Table 8-20 Parameters for Abandoning an Operation

Parameter Description
ld

The session handle.

msgid

The message id of the request to be abandoned.

serverctrls

List of LDAP server controls.

clientctrls

List of client controls.


See Also:

Section 8.2.12, "Handling Errors and Parsing Results" for more information about possible errors and how to interpret them.

8.2.11 Obtaining Results and Peeking Inside LDAP Messages

Use the functions in this section to return the result of an operation initiated asynchronously. They identify messages by type and by ID.

8.2.11.1 ldap_result, ldap_msgtype, and ldap_msgid

ldap_result() is used to obtain the result of a previous asynchronously initiated operation. Note that depending on how it is called, ldap_result() can actually return a list or "chain" of result messages. The ldap_result() function only returns messages for a single request, so for all LDAP operations other than search only one result message is expected; that is, the only time the "result chain" can contain more than one message is if results from a search operation are returned.

After a chain of messages has been returned to the caller, it is no longer tied in any caller-visible way to the LDAP request that produced it. Therefore, a chain of messages returned by calling ldap_result() or by calling a synchronous search routine is never affected by subsequent LDAP API calls (except for ldap_msgfree() which is used to dispose of a chain of messages).

ldap_msgfree() frees the result messages (possibly an entire chain of messages) obtained from a previous call to ldap_result() or from a call to a synchronous search routine.

ldap_msgtype() returns the type of an LDAP message. ldap_msgid() returns the message ID of an LDAP message.

Syntax

int ldap_result
(
LDAP            *ld,
int             msgid,
int             all,
struct timeval  *timeout,
LDAPMessage     **res
);
int ldap_msgfree( LDAPMessage *res );
int ldap_msgtype( LDAPMessage *res );
int ldap_msgid( LDAPMessage *res );

Parameters

Table 8-21 lists and describes the parameters for obtaining results and peeling inside LDAP messages.

Table 8-21 Parameters for Obtaining Results and Peeking Inside LDAP Messages

Parameter Description
ld

The session handle.

msgid

The message id of the operation whose results are to be returned, the constant LDAP_RES_UNSOLICITED (0) if an unsolicited result is desired, or the constant LDAP_RES_ANY (-1) if any result is desired.

all

Specifies how many messages is retrieved in a single call to ldap_result(). This parameter only has meaning for search results. Pass the constant LDAP_MSG_ONE (0x00) to retrieve one message at a time. Pass LDAP_MSG_ALL (0x01) to request that all results of a search be received before returning all results in a single chain. Pass LDAP_MSG_RECEIVED (0x02) to indicate that all messages retrieved so far are to be returned in the result chain.

timeout

A timeout specifying how long to wait for results to be returned. A NULL value causes ldap_result() to block until results are available. A timeout value of zero seconds specifies a polling behavior.

res

For ldap_result(), a result parameter that contains the result of the operation. If no results are returned, *res is set to NULL. For ldap_msgfree(), the result chain to be freed, obtained from a previous call to ldap_result(), ldap_search_s(), or ldap_search_st(). If res is NULL, nothing is done and ldap_msgfree() returns zero.


Usage Notes

Upon successful completion, ldap_result() returns the type of the first result returned in the res parameter. This is one of the following constants.

LDAP_RES_BIND (0x61)

LDAP_RES_SEARCH_ENTRY (0x64)

LDAP_RES_SEARCH_REFERENCE (0x73)-- new in LDAPv3

LDAP_RES_SEARCH_RESULT (0x65)

LDAP_RES_MODIFY (0x67)

LDAP_RES_ADD (0x69)

LDAP_RES_DELETE (0x6B)

LDAP_RES_MODDN (0x6D)

LDAP_RES_COMPARE (0x6F)

LDAP_RES_EXTENDED (0x78) -- new in LDAPv3

ldap_result() returns 0 if the timeout expired and -1 if an error occurs, in which case the error parameters of the LDAP session handle is set accordingly.

ldap_msgfree() frees each message in the result chain pointed to by res and returns the type of the last message in the chain. If res is NULL, then nothing is done and the value zero is returned.

ldap_msgtype() returns the type of the LDAP message it is passed as a parameter. The type is one of the types listed previously, or -1 on error.

ldap_msgid() returns the message ID associated with the LDAP message passed as a parameter, or -1 on error.

8.2.12 Handling Errors and Parsing Results

Use the functions in this section to extract information from results and to handle errors returned by other LDAP API routines.

8.2.12.1 ldap_parse_result, ldap_parse_sasl_bind_result, ldap_parse_extended_result, and ldap_err2string

Note that ldap_parse_sasl_bind_result() and ldap_parse_extended_result() must typically be used in addition to ldap_parse_result() to retrieve all the result information from SASL Bind and Extended Operations respectively.

The ldap_parse_result(), ldap_parse_sasl_bind_result(), and ldap_parse_extended_result() functions all skip over messages of type LDAP_RES_SEARCH_ENTRY and LDAP_RES_SEARCH_REFERENCE when looking for a result message to parse. They return the constant LDAP_SUCCESS if the result was successfully parsed and another LDAP error code if not. Note that the LDAP error code that indicates the outcome of the operation performed by the server is placed in the errcodep ldap_parse_result() parameter. If a chain of messages that contains more than one result message is passed to these routines they always operate on the first result in the chain.

ldap_err2string() is used to convert a numeric LDAP error code, as returned by ldap_parse_result(), ldap_parse_sasl_bind_result(), ldap_parse_extended_result() or one of the synchronous API operation calls, into an informative zero-terminated character string message describing the error. It returns a pointer to static data.

Syntax

int ldap_parse_result
(
LDAP            *ld,
LDAPMessage     *res,
int             *errcodep,
char            **matcheddnp,
char            **errmsgp,
char            ***referralsp,
LDAPControl     ***serverctrlsp,
int             freeit
);
int ldap_parse_sasl_bind_result
(
LDAP            *ld,
LDAPMessage     *res,
struct berval   **servercredp,
int             freeit
);
int ldap_parse_extended_result
(
LDAP            *ld,
LDAPMessage     *res,
char            **retoidp,
struct berval   **retdatap,
int             freeit
);
#define LDAP_NOTICE_OF_DISCONNECTION    "1.3.6.1.4.1.1466.20036"
char *ldap_err2string( int err );

The routines immediately following are deprecated. To learn more about them, see RFC 1823.

int ldap_result2error
(
LDAP            *ld,
LDAPMessage     *res,
int             freeit
);
void ldap_perror( LDAP *ld, const char *msg );

Parameters

Table 8-22 lists and describes parameters for handling errors and parsing results.

Table 8-22 Parameters for Handling Errors and Parsing Results

Parameter Description
ld

The session handle.

res

The result of an LDAP operation as returned by ldap_result() or one of the synchronous API operation calls.

errcodep

This result parameter is filled in with the LDAP error code field from the LDAPMessage message. This is the indication from the server of the outcome of the operation. NULL should be passed to ignore this field.

matcheddnp

In the case of a return of LDAP_NO_SUCH_OBJECT, this result parameter is filled in with a DN indicating how much of the name in the request was recognized. NULL should be passed to ignore this field. The matched DN string should be freed by calling ldap_memfree() which is described later in this document.

errmsgp

This result parameter is filled in with the contents of the error message field from the LDAPMessage message. The error message string should be freed by calling ldap_memfree() which is described later in this document. NULL should be passed to ignore this field.

referralsp

This result parameter is filled in with the contents of the referrals field from the LDAPMessage message, indicating zero or more alternate LDAP servers where the request is to be retried. The referrals array should be freed by calling ldap_value_free() which is described later in this document. NULL should be passed to ignore this field.

serverctrlsp

This result parameter is filled in with an allocated array of controls copied out of the LDAPMessage message. The control array should be freed by calling ldap_controls_free() which was described earlier.

freeit

A Boolean that determines whether the res parameter is disposed of or not. Pass any nonzero value to have these routines free res after extracting the requested information. This is provided as a convenience; you can also use ldap_msgfree() to free the result later. If freeit is nonzero, the entire chain of messages represented by res is disposed of.

servercredp

For SASL bind results, this result parameter is filled in with the credentials passed back by the server for mutual authentication, if given. An allocated berval structure is returned that should be disposed of by calling ber_bvfree(). NULL should be passed to ignore this field.

retoidp

For extended results, this result parameter is filled in with the dotted-OID text representation of the name of the extended operation response. This string should be disposed of by calling ldap_memfree(). NULL should be passed to ignore this field. The LDAP_NOTICE_OF_DISCONNECTION macro is defined as a convenience for clients that wish to check an OID to see if it matches the one used for the unsolicited Notice of Disconnection (defined in RFC 2251[2] section 4.4.1).

retdatap

For extended results, this result parameter is filled in with a pointer to a struct berval containing the data in the extended operation response. It should be disposed of by calling ber_bvfree(). NULL should be passed to ignore this field.

err

For ldap_err2string(), an LDAP error code, as returned by ldap_parse_result() or another LDAP API call.


Usage Notes

See RFC 1823 for a description of parameters peculiar to the deprecated routines.

8.2.13 Stepping Through a List of Results

Use the routines in this section to step through the list of messages in a result chain returned by ldap_result().

8.2.13.1 ldap_first_message and ldap_next_message

The result chain for search operations can include referral messages, entry messages, and result messages.

ldap_count_messages() is used to count the number of messages returned. The ldap_msgtype() function, described previously, can be used to distinguish between the different message types.

LDAPMessage *ldap_first_message( LDAP *ld, LDAPMessage *res );
LDAPMessage *ldap_next_message( LDAP *ld, LDAPMessage *msg );
int ldap_count_messages( LDAP *ld, LDAPMessage *res );

Parameters

Table 8-23 lists and describes the parameters for stepping through a list of results.

Table 8-23 Parameters for Stepping Through a List of Results

Parameter Description
ld

The session handle.

res

The result chain, as obtained by a call to one of the synchronous search routines or ldap_result().

msg

The message returned by a previous call to ldap_first_message() or ldap_next_message().


Usage Notes

ldap_first_message() and ldap_next_message() returns NULL when no more messages exist in the result set to be returned. NULL is also returned if an error occurs while stepping through the entries, in which case the error parameters in the session handle ld is set to indicate the error.

If successful, ldap_count_messages() returns the number of messages contained in a chain of results; if an error occurs such as the res parameter being invalid, -1 is returned. The ldap_count_messages() call can also be used to count the number of messages that remain in a chain if called with a message, entry, or reference returned by ldap_first_message(), ldap_next_message(), ldap_first_entry(), ldap_next_entry(), ldap_first_reference(), ldap_next_reference().

8.2.14 Parsing Search Results

Use the functions in this section to parse the entries and references returned by ldap_search functions. These results are returned in an opaque structure that may be accessed by calling the routines described in this section. Routines are provided to step through the entries and references returned, step through the attributes of an entry, retrieve the name of an entry, and retrieve the values associated with a given attribute in an entry.

8.2.14.1 ldap_first_entry, ldap_next_entry, ldap_first_reference, ldap_next_reference, ldap_count_entries, and ldap_count_references

The ldap_first_entry() and ldap_next_entry() routines are used to step through and retrieve the list of entries from a search result chain. The ldap_first_reference() and ldap_next_reference() routines are used to step through and retrieve the list of continuation references from a search result chain. ldap_count_entries() is used to count the number of entries returned. ldap_count_references() is used to count the number of references returned.

LDAPMessage *ldap_first_entry( LDAP *ld, LDAPMessage *res );
LDAPMessage *ldap_next_entry( LDAP *ld, LDAPMessage *entry );
LDAPMessage *ldap_first_reference( LDAP *ld, LDAPMessage *res );
LDAPMessage *ldap_next_reference( LDAP *ld, LDAPMessage *ref );
int ldap_count_entries( LDAP *ld, LDAPMessage *res );
int ldap_count_references( LDAP *ld, LDAPMessage *res );

Parameters

Table 8-24 lists and describes the parameters or retrieving entries and continuation references from a search result chain, and for counting entries returned.

Table 8-24 Parameters for Retrieving Entries and Continuation References from a Search Result Chain, and for Counting Entries Returned

Parameter Description
ld

The session handle.

res

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

entry

The entry returned by a previous call to ldap_first_entry() or ldap_next_entry().

ref

The reference returned by a previous call to ldap_first_reference() or ldap_next_reference().


Usage Notes

ldap_first_entry(), ldap_next_entry(), ldap_first_reference(), and ldap_next_reference() all return NULL when no more entries or references exist in the result set to be returned. NULL is also returned if an error occurs while stepping through the entries or references, in which case the error parameters in the session handle ld is set to indicate the error.

ldap_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 ldap_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 ldap_first_message(), ldap_next_message(), ldap_first_entry(), ldap_next_entry(), ldap_first_reference(), ldap_next_reference().

ldap_count_references() returns the number of references contained in a chain of search results; if an error occurs such as the res parameter being invalid, -1 is returned. The ldap_count_references() call can also be used to count the number of references that remain in a chain.

8.2.14.2 ldap_first_attribute and ldap_next_attribute

Use the functions in this section to step through the list of attribute types returned with an entry.

Syntax

char *ldap_first_attribute
(
LDAP            *ld,
LDAPMessage     *entry,
BerElement      **ptr
);

char *ldap_next_attribute
(
LDAP            *ld,
LDAPMessage     *entry,
BerElement      *ptr
);
void ldap_memfree( char *mem );

Parameters

Table 8-25 lists and describes the parameters for stepping through attribute types returned with an entry.

Table 8-25 Parameters for Stepping Through Attribute Types Returned with an Entry

Parameter Description
ld

The session handle.

entry

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

ptr

In ldap_first_attribute(), the address of a pointer used internally to keep track of the current position in the entry. In ldap_next_attribute(), the pointer returned by a previous call to ldap_first_attribute(). The BerElement type itself is an opaque structure.

mem

A pointer to memory allocated by the LDAP library, such as the attribute type names returned by ldap_first_attribute() and ldap_next_attribute, or the DN returned by ldap_get_dn(). If mem is NULL, the ldap_memfree() call does nothing.


Usage Notes

ldap_first_attribute() and ldap_next_attribute() returns NULL when the end of the attributes is reached, or if there is an error. In the latter case, the error parameters in the session handle ld are set to indicate the error.

Both routines return a pointer to an allocated buffer containing the current attribute name. This should be freed when no longer in use by calling ldap_memfree().

ldap_first_attribute() allocates and returns in ptr a pointer to a BerElement used to keep track of the current position. This pointer may be passed in subsequent calls to ldap_next_attribute() to step through the entry's attributes. After a set of calls to ldap_first_attribute() and ldap_next_attribute(), if ptr is non-null, it should be freed by calling ber_free(ptr, 0). Note that it is very important to pass the second parameter as 0 (zero) in this call, since the buffer associated with the BerElement does not point to separately allocated memory.

The attribute type names returned are suitable for passing in a call to ldap_get_values() and friends to retrieve the associated values.

8.2.14.3 ldap_get_values, ldap_get_values_len, ldap_count_values, ldap_count_values_len, ldap_value_free, and ldap_value_free_len

ldap_get_values() and ldap_get_values_len() are used to retrieve the values of a given attribute from an entry. ldap_count_values() and ldap_count_values_len() are used to count the returned values.

ldap_value_free() and ldap_value_free_len() are used to free the values.

Syntax

char **ldap_get_values
(
LDAP            *ld,
LDAPMessage     *entry,
const char      *attr
);

struct berval **ldap_get_values_len
(
LDAP            *ld,
LDAPMessage     *entry,
const char      *attr
);

int ldap_count_values( char **vals );
int ldap_count_values_len( struct berval **vals );
void ldap_value_free( char **vals );
void ldap_value_free_len( struct berval **vals );

Parameters

Table 8-26 lists and describes the parameters for retrieving and counting attribute values.

Table 8-26 Parameters for Retrieving and Counting Attribute Values

Parameter Description
ld

The session handle.

entry

The entry from which to retrieve values, as returned by ldap_first_entry() or ldap_next_entry().

attr

The attribute whose values are to be retrieved, as returned by ldap_first_attribute() or ldap_next_attribute(), or a caller-supplied string (for example, "mail").

vals

The values returned by a previous call to ldap_get_values() or ldap_get_values_len().


Usage Notes

Two forms of the various calls are provided. The first form is only suitable for use with non-binary character string data. The second _len form is used with any kind of data.

ldap_get_values() and ldap_get_values_len() return NULL if no values are found for attr or if an error occurs.

ldap_count_values() and ldap_count_values_len() return -1 if an error occurs such as the vals parameter being invalid.

If a NULL vals parameter is passed to ldap_value_free() or ldap_value_free_len(), nothing is done.

Note that the values returned are dynamically allocated and should be freed by calling either ldap_value_free() or ldap_value_free_len() when no longer in use.

8.2.14.4 ldap_get_dn, ldap_explode_dn, ldap_explode_rdn, and ldap_dn2ufn

ldap_get_dn() is used to retrieve the name of an entry. ldap_explode_dn() and ldap_explode_rdn() are used to break up a name into its component parts. ldap_dn2ufn() is used to convert the name into a more user friendly format.

Syntax

char *ldap_get_dn( LDAP *ld, LDAPMessage *entry );
char **ldap_explode_dn( const char *dn, int notypes );
char **ldap_explode_rdn( const char *rdn, int notypes );
char *ldap_dn2ufn( const char *dn );

Parameters

Table 8-27 lists and describes the parameters for retrieving, exploding, and converting entry names.

Table 8-27 Parameters for Retrieving, Exploding, and Converting Entry Names

Parameter Description
ld

The session handle.

entry

The entry whose name is to be retrieved, as returned by ldap_first_entry() or ldap_next_entry().

dn

The DN to explode, such as returned by ldap_get_dn().

rdn

The RDN to explode, such as returned in the components of the array returned by ldap_explode_dn().

notypes

A Boolean parameter, if nonzero indicating that the DN or RDN components are to have their type information stripped off: cn=Babs would become Babs.


Usage Notes

ldap_get_dn() returns NULL if a DN parsing error occurs. The function sets error parameters in the session handle ld to indicate the error. It returns a pointer to newly allocated space that the caller should free by calling ldap_memfree() when it is no longer in use.

ldap_explode_dn() returns a NULL-terminated char * array containing the RDN components of the DN supplied, with or without types as indicated by the notypes parameter. The components are returned in the order they appear in the DN. The array returned should be freed when it is no longer in use by calling ldap_value_free().

ldap_explode_rdn() returns a NULL-terminated char * array containing the components of the RDN supplied, with or without types as indicated by the notypes parameter. The components are returned in the order they appear in the rdn. The array returned should be freed when it is no longer in use by calling ldap_value_free().

ldap_dn2ufn() converts the DN into a user friendly format. The UFN returned is newly allocated space that should be freed by a call to ldap_memfree() when no longer in use.

8.2.14.5 ldap_get_entry_controls

ldap_get_entry_controls() is used to extract LDAP controls from an entry.

Syntax

int ldap_get_entry_controls
(
LDAP            *ld,
LDAPMessage     *entry,
LDAPControl     ***serverctrlsp
);

Parameters

Table 8-28 lists and describes the parameters for extracting LDAP control from an entry.

Table 8-28 Parameters for Extracting LDAP Controls from an Entry

Parameters Description
ld

The session handle.

entry

The entry to extract controls from, as returned by ldap_first_entry() or ldap_next_entry().

serverctrlsp

This result parameter is filled in with an allocated array of controls copied out of entry. The control array should be freed by calling ldap_controls_free(). If serverctrlsp is NULL, no controls are returned.


Usage Notes

ldap_get_entry_controls() returns an LDAP error code that indicates whether the reference could be successfully parsed (LDAP_SUCCESS if all goes well).

8.2.14.6 ldap_parse_reference

Use ldap_parse_reference() to extract referrals and controls from a SearchResultReference message.

Syntax

int ldap_parse_reference
(
LDAP            *ld,
LDAPMessage     *ref,
char            ***referralsp,
LDAPControl     ***serverctrlsp,
int             freeit
);

Parameters

Table 8-29 lists and describes parameters for extracting referrals and controls from a SearchResultReference message.

Table 8-29 Parameters for Extracting Referrals and Controls from a SearchResultReference Message

Parameter Description
ld

The session handle.

ref

The reference to parse, as returned by ldap_result(), ldap_first_reference(), or ldap_next_reference().

referralsp

This result parameter is filled in with an allocated array of character strings. The elements of the array are the referrals (typically LDAP URLs) contained in ref. The array should be freed when no longer in used by calling ldap_value_free(). If referralsp is NULL, the referral URLs are not returned.

serverctrlsp

This result parameter is filled in with an allocated array of controls copied out of ref. The control array shouldbe freed by calling ldap_controls_free(). If serverctrlsp is NULL, no controls are returned.

freeit

A Boolean that determines whether the ref parameter is disposed of or not. Pass any nonzero value to have this routine free ref after extracting the requested information. This is provided as a convenience. You can also use ldap_msgfree() to free the result later.


Usage Notes

ldap_parse_reference() returns an LDAP error code that indicates whether the reference could be successfully parsed (LDAP_SUCCESS if all goes well).

8.3 Sample C API Usage

The first three examples show how to use the C API both with and without SSL and for SASL authentication. More complete examples are given in RFC 1823. The sample code for the command-line tool to perform an LDAP search also demonstrates use of the API in both the SSL and the non-SSL mode.

This section contains these topics:

8.3.1 C API Usage with SSL

#include <stdio.h>
#include <ldap.h>

main()
{
LDAP          *ld;
int               ret = 0;
….
/* open a connection */
if ((ld = ldap_open("MyHost", 3131)) == NULL)
     exit( 1 );

/* SSL initialization */  
ret = ldap_init_SSL(&ld->ld_sb, "file:/sslwallet", "welcome", 
                                        GSLC_SSL_ONEWAY_AUTH );
if(ret != 0) 
{
printf(" %s \n", ldap_err2string(ret));
exit(1); 
}

/* authenticate as nobody */
if ( ldap_bind_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
     ldap_perror( ld, "ldap_bind_s" );
     exit( 1 );
}

.
.
.
}

Because the user is making the ldap_init_SSL call, the client/server communication in the previous example is secured by using SSL.

8.3.2 C API Usage Without SSL

#include <stdio.h>
#include <ldap.h>

main()
{
LDAP          *ld;
int           ret = 0;
.
.
.
/* open a connection */
if ( (ld = ldap_open( "MyHost", LDAP_PORT )) == NULL )
     exit( 1 );

/* authenticate as nobody */
if ( ldap_bind_s( ld, NULL, NULL ) != LDAP_SUCCESS ) {
     ldap_perror( ld, "ldap_bind_s" );
      exit( 1 );
}
.
.
.
}

In the previous example, the user is not making the ldap_init_SSL call, and the client-to-server communication is therefore not secure.

8.3.3 C API Usage for SASL-Based DIGEST-MD5 Authentication

This sample program illustrates the usage of LDAP SASL C-API for SASL-based DIGEST-MD5 authentication to a directory server.

/*
   EXPORT FUNCTION(S)
     NONE

   INTERNAL FUNCTION(S)
     NONE

   STATIC FUNCTION(S)
     NONE

   NOTES
     Usage:
      saslbind -h ldap_host -p ldap_port -D authentication_identity_dn \
               -w password  
      options 
       -h     LDAP host
       -p     LDAP port
       -D     DN of the identity for authentication
       -p     Password

       Default SASL authentication parameters used by the demo program
       SASL Security Property :    Currently only "auth" security property 
                                   is supported by the C-API. This demo
                                   program uses this security property.
       SASL Mechanism         :    Supported mechanisms by OID
                                   "DIGEST-MD5" - This demo program 
                                                  illustrates it's usage.
                                   "EXTERNAL" - SSL authentication is used.
                                                (This demo program does 
                                                 not illustrate it's usage.)
       Authorization identity :    This demo program does not use any
                                    authorization identity.

   MODIFIED   (MM/DD/YY)
   ******      06/12/03 - Creation

*/

/*---------------------------------------------------------------------------
                     PRIVATE TYPES AND CONSTANTS
  ---------------------------------------------------------------------------*/
                
/*---------------------------------------------------------------------------
                     STATIC FUNCTION DECLARATIONS 
  ---------------------------------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <ldap.h>


static int ldap_version = LDAP_VERSION3;

main (int argc, char **argv)
{
  LDAP*           ld;
  extern char*    optarg;
  char*           ldap_host = NULL;
  char*           ldap_bind_dn = NULL;
  char*           ldap_bind_pw = NULL;
  int             authmethod = 0;
  char            ldap_local_host[256] = "localhost";
  int             ldap_port = 3060;
  char*           authcid = (char *)NULL;
  char*           mech = "DIGEST-MD5"; /* SASL mechanism */
  char*           authzid = (char *)NULL;
  char*           sasl_secprops = "auth";
  char*           realm = (char *)NULL;
  int             status = LDAP_SUCCESS;
  OraLdapHandle   sasl_cred = (OraLdapHandle )NULL;
  OraLdapClientCtx *cctx = (OraLdapClientCtx *)NULL;
  int              i = 0;


    while (( i = getopt( argc, argv,
            "D:h:p:w:E:P:U:V:W:O:R:X:Y:Z"
            )) != EOF ) {
        switch( i ) {

        case 'h':       /* ldap host */
            ldap_host = (char *)strdup( optarg );
            break;
        case 'D':       /* bind DN */
            authcid = (char *)strdup( optarg );
            break;
            
        case 'p':       /* ldap port */
            ldap_port = atoi( optarg );
            break;
        case 'w':       /* Password */
            ldap_bind_pw = (char *)strdup( optarg );
            break;

    default:
            printf("Invalid Arguments passed\n" );
        }
    }


  /* Get the connection to the LDAP server */
  if (ldap_host == NULL)
    ldap_host = ldap_local_host;

  if ((ld = ldap_open (ldap_host, ldap_port)) == NULL)
  {
    ldap_perror (ld, "ldap_init");
    exit (1);
  }

  /* Create the client context needed by LDAP C-API Oracle Extension functions*/
  status = ora_ldap_init_clientctx(&cctx);

  if(LDAP_SUCCESS != status) {
     printf("Failed during creation of client context \n");
     exit(1);
  }

  /* Create SASL credentials */
  sasl_cred = ora_ldap_create_cred_hdl(cctx, ORA_LDAP_CRED_HANDLE_SASL_MD5);

  ora_ldap_set_cred_props(cctx, sasl_cred, ORA_LDAP_CRED_SASL_REALM, 
      (void *)realm);
  ora_ldap_set_cred_props(cctx, sasl_cred, ORA_LDAP_CRED_SASL_AUTH_PASSWORD, 
      (void *)ldap_bind_pw);
  ora_ldap_set_cred_props(cctx, sasl_cred, ORA_LDAP_CRED_SASL_AUTHORIZATION_ID,
      (void *)authzid);
  ora_ldap_set_cred_props(cctx, sasl_cred, ORA_LDAP_CRED_SASL_SECURITY_PROPERTIES, 
      (void *)sasl_secprops);

  /* If connecting to the directory using SASL DIGEST-MD5, the Authentication ID 
     has to be normalized before it's sent to the server,
     the LDAP C-API does this normalization based on the following flag set in
     SASL credential properties */
  ora_ldap_set_cred_props(cctx, sasl_cred, ORA_LDAP_CRED_SASL_NORM_AUTHDN, (void *)NULL);
  
  /* SASL Authetication to LDAP Server */
  status = (int)ora_ldap_init_SASL(cctx, ld, (char *)authcid, (char *)ORA_LDAP_SASL_MECH_DIGEST_MD5,
                                     sasl_cred, NULL, NULL);

  if(LDAP_SUCCESS == status) {
     printf("SASL bind successful \n" );
  }else {
     printf("SASL bind failed with status :  %d\n", status);
  }

  /* Free SASL Credentials */
  ora_ldap_free_cred_hdl(cctx, sasl_cred);

  status = ora_ldap_free_clientctx(cctx);

  /* Unbind from LDAP server */
  ldap_unbind (ld);

  return (0);
}


/* end of file saslbind.c */

8.3.4 Setting and Using a Callback Function to Get Credentials When Chasing Referrals

To set the callback function, you use ldap_set_rebind_proc(). The callback function is used only if LDAP_OPT_REFERRALS is set using ldap_set_option(). If ldap_set_rebind_proc() is not called, then the library uses anonymous bind to connect to a new server while chasing LDAP referrals.

/* referralsample.c - Sample program to demonstrate the usage of ldap_set_rebind_proc() for referrals */
 
#include <stdio.h>
#include <stdlib.h>
#include <ldap.h>
 
 
/*
* Prints the Entry DNs of the search result
*/
void print_entry_dns( LDAP *ld, LDAPMessage *result )
{
   LDAPMessage     *e;
   char            *dn;
 
   for ( e = ldap_first_entry( ld, result ); e != NULL;
      e = ldap_next_entry(ld, e ) )
   {
       if ( (dn = ldap_get_dn( ld, e )) != NULL ) {
           printf( "dn: %s\n\n", dn );
           ldap_memfree( dn );
       }
       else {
           ldap_perror( ld, "ldap_get_dn" );
       }
   }
}
 
/*
* Rebind function for providing the credentials to bind referral servers
*/
int getbindcredentials(LDAP *ld, char **binddn, char **bindpwd, int *authmethod, int freeit)
{
   if (freeit == 0) {
   /* In this example bind credentials are static.  Typically, Bind credentials are fetched from wallet or
some other means for the server information in input session handle */
 
       *binddn = "cn=orcladmin";
       *bindpwd = "xyz";
       *authmethod = LDAP_AUTH_SIMPLE;
   }
   else {
   /* In this example there is no memory allocation.
      If the memory is allocated for binddn/bindpwd/authmehod, they should be freed here */
 
       *binddn = NULL;
       *bindpwd = NULL;
       *authmethod = 0;
   }
 
   return 0;
}
 
main()
{
   char            ldaphost[] = "localhost";
   char            binddn[] = "cn=orcladmin";
   char            bindpwd[] = "password";
   int             ldapport = 3060;
   char            searchbase[] = "dc=oracle,dc=com";
   char            filter[] = "objectclass=*";
   int             scope = LDAP_SCOPE_SUBTREE;
 
   LDAP           *ld;
   LDAPMessage    *result;
   int             ret = 0;
 
 
   if ( (ld = ldap_open( ldaphost, ldapport )) == NULL) {
       printf( "ldap_open: Connection failed\n" );
       exit( 1 );
   }
 
   if ( ldap_simple_bind_s(ld, binddn, bindpwd) != LDAP_SUCCESS ) {
       ldap_perror(ld, "ldap_simple_bind_s");
       exit( 1 );
   }
 
   /* Set this option to connect to the referrals */
   ldap_set_option (ld, LDAP_OPT_REFERRALS, (void *)1);
 
   /* set the function pointer which provides the bind credentials for referral server */
   ldap_set_rebind_proc(ld,  (int (*)(LDAP*, char**, char**, int*, int))getbindcredentials);
 
 
   ret = ldap_search_s( ld, searchbase, scope, filter, NULL, 0, &result );
   if(LDAP_SUCCESS != ret) {
     ldap_perror(ld, "ldap_search_s");
     exit( 1 );
   }
 
   print_entry_dns(ld, result);
 
  ldap_unbind(ld);
  return(0);
}

8.4 Required Header Files and Libraries for the C API

To build applications with the C API, you need to:

  • Include the header file located at $ORACLE_HOME/ldap/public/ldap.h.

  • Dynamically link to the library located at

    • $ORACLE_HOME/lib/libclntsh.so.10.1 on UNIX operating systems

    • %ORACLE_HOME%\bin\oraldapclnt10.dll on Windows operating systems

8.5 Dependencies and Limitations of the C API

This API can work against any release of Oracle Internet Directory. It requires either an Oracle environment or, at minimum, globalization support and other core libraries.

To use the different authentication modes in SSL, the directory server requires corresponding configuration settings.

See Also:

Oracle Fusion Middleware Administrator's Guide for Oracle Internet Directory for details about how to set the directory server in various SSL authentication modes.

Oracle Wallet Manager is required for creating wallets if you are using the C API in SSL mode.

TCP/IP Socket Library is required.

The following Oracle libraries are required:

  • Oracle SSL-related libraries

  • Oracle system libraries

Sample libraries are included in the release for the sample command line tool. You should replace these libraries with your own versions of the libraries.

The product supports only those authentication mechanisms described in LDAP SDK specifications (RFC 1823).

All strings input to the C API must be in UTF-8 format. If the strings are not in the UTF-8 format, you can use the OCI function OCINlsCharSetConvert to perform the conversion. Please see the Oracle Call Interface Programmer's Guide in the Oracle Database Library at http://www.oracle.com/technology/documentation.