Skip Headers

Oracle Internet Directory Application Developer's Guide
Release 9.2

Part Number A96577-01
Go To Documentation Library
Home
Go To Product List
Book List
Go To Table Of Contents
Contents
Go To Index
Index

Master Index

Feedback

Go to previous page Go to next page

3
C API for Oracle Internet Directory

This chapter introduces the Oracle Internet Directory C API and provides examples of how to use it. It contains these topics:

About the Oracle Internet Directory C API

The Oracle Internet Directory SDK C API is based on:

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

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

See Also:

"Sample C API Usage" for more details on how to use the two modes

This section contains these topics:

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:

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

SSL Interface Calls

There is only one call required to enable SSL:

int ldap_init_SSL(Sockbuf *sb, text *sslwallet, text *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, all subsequent communication happens over a secure connection.

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 non zero return value indicates an error. The error code can be decoded by using the function ldap_err2string.

See Also:

See "Sample C API Usage"

Wallet Support

To use the SSL feature, both the server and the client may require wallets, depending on which authentication mode is being used. Release 9.2 of the API supports only Oracle Wallet. You can create wallets using Oracle Wallet Manager.

C API Reference

This section contains these topics:

Summary of LDAP C API

Table 3-1 DBMS_LDAP API Subprograms
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

ldap_delete_ext

ldap_delete_ext_s

ldap_delete

ldap_delete_s

Delete an entry from the directory

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

ldap_get_dn

Get the distinguished name for an entry

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

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_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

Returns 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_set_option

Set the value of these parameters

ldap_simple_bind

ldap_simple_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_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: http://www.ietf.org/rfc/rfc1823.txt for a more detailed explanation of these calls

Functions

This section contains these topics:

Initializing an LDAP Session

ldap_init

ldap_open

ldap_init() initializes a session with an LDAP server. The server is not actually contacted until an operation is performed that requires it, allowing various options to be set after initialization.

Syntax
LDAP *ldap_init
(


const char      *hostname,
int             portno
) ;
Parameters
Table 3-2 Parameters for Initializing an LDAP Session
Parameter Description

hostname

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

Note: A suitable representation for including a literal IPv6[10] address in the hostname parameter is desired, but has not yet been determined or implemented in practice.

portno

Contains the TCP port number to connect to. The default LDAP port of 389 can be obtained by supplying the constant LDAP_PORT. If a host includes a port number then this parameter is ignored.

Usage Notes

ldap_init() and ldap_open() both return a "session handle," 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 in which case the operating system error reporting mechanism can be checked 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 can be performed.

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

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.

ldap_get_option

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 will 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 3-3 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 3-4. After the constant the actual hexadecimal value of the constant is listed in parentheses.

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.

Table 3-4 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.

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 will wait 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 or 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 reading the current setting using ldap_get_option(), a zero value means OFF and any nonzero value means ON. By default, this option is ON.

LDAP_OPT_RESTART (0x09)

void * (LDAP_OPT_ON or LDAP_OPT_OFF)

int *

Determines whether LDAP I/O operations are automatically restarted if they stop prematurely. 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 reading the current setting using ldap_get_option(), a zero value means OFF and any nonzero value means ON. This option is useful if an LDAP I/O operation can be interrupted prematurely, for example by a timer going off, or other interrupt. By default, this option is 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. It SHOULD be one of the constants 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: "Working With Controls"

LDAP_OPT_CLIENT_CONTROLS (0x13)

LDAPControl **

LDAPControl ***

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

See Also: "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 and 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 to ldap_init() for the allowed syntax.

LDAP_OPT_ERROR_NUMBER (0x31)

int *

int *

The code of the most recent LDAP error that occurred for this session.

LDAP_OPT_ERROR_STRING (0x32)

char *

char **

The message returned with the most recent LDAP error that occurred for this session.

LDAP_OPT_MATCHED_DN (0x33)

char *

char **

The matched DN value returned with the most recent LDAP error that occurred for this session.

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 implementors:

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

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 have the following meanings:

Table 3-5 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 will only be carried out if the control is recognized by the server and/or client. Note that the LDAP unbind and abandon operations have no server response, so clients SHOULD NOT mark server controls critical when used with these two operations.

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 "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 document (described in the following section). Other client controls MAY be defined in future revisions of this document or in documents that extend this API.

A Client Control That Governs Referral Processing

As described previously in "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 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 4-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 4-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.

Authenticating to the Directory

The following functions are used to authenticate an LDAP client to an LDAP directory server.

ldap_sasl_bind

ldap_sasl_bind_s

ldap_simple_bind

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 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 3-6 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 will be set to the message id of the request if the ldap_sasl_bind() call succeeds

servercredp

This result parameter will be 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(), described in "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() will return -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:

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

Closing the Session

ldap_unbind_ext

ldap_unbind

ldap_unbind_s

The following functions are used to unbind from the directory, close open connections, and dispose of the session handle.

Syntax
int ldap_unbind_ext( LDAP *ld, LDAPControl **serverctrls,
LDAPControl **clientctrls );
int ldap_unbind( LDAP *ld );
int ldap_unbind_s( LDAP *ld );
Parameters
Table 3-7 Parameters for Closing the Session
Parameter Description

ld

The session handle

serverctrls

List of LDAP server controls

clientctrls

List of client controls

Usage Notes

The 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.

Performing LDAP Operations

ldap_search_ext

ldap_search_ext_s

ldap_search

ldap_search_s

ldap_search_st

These functions are used to search the LDAP directory, returning a requested set of attributes for each entry matched.

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 3-8 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 will contain 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 will be 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.
Usage Notes

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(), described in "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(), described in "ldap_result", can be used to obtain the result of the bind. In case of error, ldap_search() will return -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(), 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 will wait for a search to complete. After the local search timeout expires, the API implementation will send an abandon operation to stop the search operation.

See Also:

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

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. attrs contains the list of attributes to return.

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. attrs contains the list of attributes to return for each child entry.

ldap_compare_ext

ldap_compare_ext_s

ldap_compare

ldap_compare_s

These routines are used to compare a given attribute value assertion against an LDAP entry.

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 3-9 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 will be set to the message id of the request if the ldap_compare_ext() call succeeds.

Usage Notes

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(), described in "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(), described in "ldap_result", can be used to obtain the result of the bind. In case of error, ldap_compare() will return -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:

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

ldap_modify_ext

ldap_modify_ext_s

ldap_modify

ldap_modify_s

These routines are used to modify an existing LDAP entry.

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 3-10 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 will be set to the message id of the request if the ldap_modify_ext() call succeeds

The fields in the LDAPMod structure have the following meanings:

Table 3-11 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 will have 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.

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(), described in "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(), described in "ldap_result", can be used to obtain the result of the modify. In case of error, ldap_modify() will return -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:

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

ldap_rename

ldap_rename_s

These routines are used to change the name of an entry.

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 3-12 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(s) is to be removed, if zero indicating that the old RDN value(s) 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 will be set to the message id of the request if the ldap_rename() call succeeds.

Usage Notes

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(), described in "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:

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

ldap_add_ext

ldap_add_ext_s

ldap_add

ldap_add_s

These functions are used to add entries to the LDAP directory.

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 3-13 Parameters for Add Operations
Parameter Description

ld

The session handle.

dn

The name of the entry to add.

attrs

The entry's 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 will be 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.

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(), described in "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(), described in "ldap_result", can be used to obtain the result of the add. In case of error, ldap_add() will return -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:

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

ldap_delete_ext

ldap_delete_ext_s

ldap_delete

ldap_delete_s

These functions are used to delete a leaf entry from the LDAP directory.

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 3-14 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 will be 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.

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(), described in "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(), described in "ldap_result", can be used to obtain the result of the delete. In case of error, ldap_delete() will return -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:

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

ldap_extended_operation

ldap_extended_operation_s

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

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 3-15 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 will be set to the message id of the request if the ldap_extended_operation() call succeeds.

retoidp

Pointer to a character string that will be 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 will be 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.

Usage Notes

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(), described in "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 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:

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

Abandoning an Operation

ldap_abandon_ext

ldap_abandon

These calls are used to abandon an operation in progress:

Syntax
int ldap_abandon_ext
(


LDAP            *ld,
int             msgid,
LDAPControl     **serverctrls,
LDAPControl     **clientctrls
); int ldap_abandon (
LDAP            *ld,
int             msgid
);
Parameters
Table 3-16 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.

Usage Notes

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.

See Also:

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

Obtaining Results and Peeking Inside LDAP Messages

ldap_result

ldap_msgfree

ldap_msgtype

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.

Once 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 will never be 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 3-17 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 will be 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 will contain the result(s) 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 will be 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 will be 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, 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 will be 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.

Handling Errors and Parsing Results

ldap_parse_result

ldap_parse_sasl_bind_result

ldap_parse_extended_result

ldap_err2string

These calls are used to extract information from results and handle errors returned by other LDAP API routines. 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.

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 use of the following routines is deprecated and more complete descriptions can be found in RFC 1823:

int ldap_result2error
(


LDAP            *ld,
LDAPMessage     *res,
int             freeit
);

void ldap_perror( LDAP *ld, const char *msg );

Parameters
Table 3-18 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 will be 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 will be 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 will be 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 will be 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 will be 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 will be 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 will be 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 will be 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

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

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.

Stepping Through a List of Results

ldap_first_message

ldap_next_message

These routines are used to step through the list of messages in a result chain returned by ldap_result(). For search operations, the result chain can actually 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 3-19 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() will return 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 will be 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().

Parsing Search Results

The following calls are used to parse the entries and references returned by ldap_search() and friends. 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.

ldap_first_entry

ldap_next_entry

ldap_first_reference

ldap_next_reference

ldap_count_entries

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 3-20 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 will be 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.

ldap_first_attribute

ldap_next_attribute

These calls are used to step through the list of attribute types returned with an entry.

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 3-21 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 that is described in more detail later in this document in the section "Encoded ASN.1 Value Manipulation".

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() will return NULL when the end of the attributes is reached, or if there is an error, in which case the error parameters in the session handle ld will be 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() will allocate and return 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.

ldap_get_values

ldap_get_values_len

ldap_count_values

ldap_count_values_len

ldap_value_free

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 3-22 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.

ldap_get_dn

ldap_explode_dn

ldap_explode_rdn

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 3-23 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() will return NULL if there is some error parsing the dn, setting 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.

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 3-24 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 will be 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).

ldap_parse_reference

ldap_parse_reference() is used 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 3-25 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 will be 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 will be filled in with an allocated array of controls copied out of ref. The control array SHOULD be 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).

Sample C API Usage

The following examples show how to use the API both with and without SSL. More complete examples are given in RFC 1823. The sample code for the command line tool to perform LDAP search also demonstrates use of the API in two modes.

This section contains these topics:

C API Usage with SSL

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <netdb.h>
#include <gsle.h>
#include <gslc.h>
#include <gsld.h>
#include "gslcc.h"

main()
{


LDAP          *ld;
int              ret = 0;
....
/* open a connection */
if ( (ld = ldap_open( "MyHost", 636 )) == 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.

C API Usage Without SSL

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <netdb.h>
#include <gsle.h>
#include <gslc.h>
#include <gsld.h>
#include "gslcc.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/server communication is therefore not secure.

Building Applications with the C API

This section contains these topics:

Required Header Files and Libraries

To build applications with the C API, you need:

Building a Sample Search Tool

The Oracle Internet Directory SDK Release 9.2 provides a sample command line tool, samplesearch, for demonstrating how to use the C API to build applications. You can use samplesearch to perform LDAP searches in either SSL or non-SSL mode.

You can find the source file (samplesearch.c) and the make file (demo_ldap.mk) in the following directory: ORACLE_HOME/ldap/demo.

To build the sample search tool, enter the following command:

make -f demo_ldap.mk build EXE=samplesearch OBJS=samplesearch.o

Note:

You can use this make file to build other client applications by using the C API. Replace samplesearch with the name of the binary you want to build, and samplesearch.o with your own object file.


The sample code for samplesearch is:

/*
   NAME
     s0gsldsearch.c - <one-line expansion of the name>
   DESCRIPTION
     <short description of component this file declares/defines>
   PUBLIC FUNCTION(S)
     <list of external functions declared/defined - with one-line descriptions>
   PRIVATE FUNCTION(S)
     <list of static functions defined in .c file - with one-line descriptions>
   RETURNS
     <function return values, for .c file with single function>
   NOTES
     <other useful comments, qualifications, and so on>
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <netdb.h>
#include "ldap.h"

#define DEFSEP     "="
#define LDAPSEARCH_BINDDN       NULL
#define LDAPSEARCH_BASE         DEFAULT_BASE
#define DEFAULT_BASE    "o=oracle, c=US"

#ifdef LDAP_DEBUG
extern int ldap_debug, lber_debug;
#endif /* LDAP_DEBUG */

usage( s )
char   *s;
{
    fprintf( stderr, "usage: %s [options] filter [attributes...]\nwhere:\n", s 
);
    fprintf( stderr, "    filter\tRFC-1558 compliant LDAP search filter\n" );
    fprintf( stderr, "    attributes\twhitespace-separated list of attributes to 
retrieve\n" );
    fprintf( stderr, "\t\t(if no attribute list is given, all are retrieved)\n" 
);
    fprintf( stderr, "options:\n" );
    fprintf( stderr, "    -n\t\tshow what would be done but don't actually 
search\n" );
    fprintf( stderr, "    -v\t\trun in verbose mode (diagnostics to standard 
output)\n" );
    fprintf( stderr, "    -t\t\twrite values to files in /tmp\n" );
    fprintf( stderr, "    -u\t\tinclude User Friendly entry names in the 
output\n" );
    fprintf( stderr, "    -A\t\tretrieve attribute names only (no values)\n" );
    fprintf( stderr, "    -B\t\tdo not suppress printing of non-ASCII values\n" 
);
    fprintf( stderr, "    -L\t\tprint entries in LDIF format (-B is implied)\n" 
);
#ifdef LDAP_REFERRALS
    fprintf( stderr, "    -R\t\tdo not automatically follow referrals\n" );
#endif /* LDAP_REFERRALS */
    fprintf( stderr, "    -d level\tset LDAP debugging level to `level'\n" );
    fprintf( stderr, "    -F sep\tprint `sep' instead of `=' between attribute 
names and values\n" );
    fprintf( stderr, "    -S attr\tsort the results by attribute `attr'\n" );
    fprintf( stderr, "    -f file\tperform sequence of searches listed in 
`file'\n" );
    fprintf( stderr, "    -b basedn\tbase dn for search\n" );
    fprintf( stderr, "    -s scope\tone of base, one, or sub (search scope)\n" 
);
    fprintf( stderr, "    -a deref\tone of never, always, search, or find (alias 
dereferencing)\n" );
    fprintf( stderr, "    -l time lim\ttime limit (in seconds) for search\n" );
    fprintf( stderr, "    -z size lim\tsize limit (in entries) for search\n" );
    fprintf( stderr, "    -D binddn\tbind dn\n" );
    fprintf( stderr, "    -w passwd\tbind passwd (for simple authentication)\n" 
);
#ifdef KERBEROS
    fprintf( stderr, "    -k\t\tuse Kerberos instead of Simple Password 
authentication\n" );
#endif
    fprintf( stderr, "    -h host\tldap server\n" );
    fprintf( stderr, "    -p port\tport on ldap server\n" );
    fprintf( stderr, "    -W Wallet\tWallet location\n" );
    fprintf( stderr, "    -P Wpasswd\tWallet Password\n" );
    fprintf( stderr, "    -U SSLAuth\tSSL Authentication Mode\n" );
    return;
}

static char    *binddn = LDAPSEARCH_BINDDN;
static char    *passwd = NULL;
static char    *base = LDAPSEARCH_BASE;
static char    *ldaphost = NULL;
static int ldapport = LDAP_PORT;
static char    *sep = DEFSEP;
static char    *sortattr = NULL;
static int skipsortattr = 0;
static int verbose, not, includeufn, allow_binary, vals2tmp, ldif;
/* TEMP */

main( argc, argv )
int    argc;
char   **argv;
{
    char       *infile, *filtpattern, **attrs, line[ BUFSIZ ];
    FILE       *fp;
    int            rc, i, first, scope, kerberos, deref, attrsonly;
    int            ldap_options, timelimit, sizelimit, authmethod;
    LDAP       *ld;
    extern char        *optarg;
    extern int     optind;
    char       localHostName[MAXHOSTNAMELEN + 1];
    char   *sslwrl = NULL;
    char   *sslpasswd = NULL;
   int sslauth=0,err=0;

    infile = NULL;
    deref = verbose = allow_binary = not = kerberos = vals2tmp =
       attrsonly = ldif = 0;
#ifdef LDAP_REFERRALS
    ldap_options = LDAP_OPT_REFERRALS;
#else /* LDAP_REFERRALS */
    ldap_options = 0;
#endif /* LDAP_REFERRALS */
    sizelimit = timelimit = 0;
    scope = LDAP_SCOPE_SUBTREE;

    while (( i = getopt( argc, argv,
#ifdef KERBEROS
       "KknuvtRABLD:s:f:h:b:d:p:F:a:w:l:z:S:"
#else
       "nuvtRABLD:s:f:h:b:d:p:F:a:w:l:z:S:W:P:U:"
#endif
       )) != EOF ) {
   switch( i ) {
   case 'n':   /* do Not do any searches */
       ++not;
       break;
   case 'v':   /* verbose mode */
    ++verbose;
    break;
case 'd':
#ifdef LDAP_DEBUG
    ldap_debug = lber_debug = atoi( optarg );  /* */
#else /* LDAP_DEBUG */
    fprintf( stderr, "compile with -DLDAP_DEBUG for debugging\n" );
#endif /* LDAP_DEBUG */
    break;
#ifdef KERBEROS
case 'k':  /* use kerberos bind */
    kerberos = 2;
    break;
case 'K':  /* use kerberos bind, 1st part only */
       kerberos = 1;
       break;
#endif
   case 'u':   /* include UFN */
       ++includeufn;
       break;
   case 't':   /* write attribute values to /tmp files */
       ++vals2tmp;
       break;
   case 'R':   /* don't automatically chase referrals */
#ifdef LDAP_REFERRALS
       ldap_options &= ~LDAP_OPT_REFERRALS;
#else /* LDAP_REFERRALS */
       fprintf( stderr,
           "compile with -DLDAP_REFERRALS for referral support\n" );
#endif /* LDAP_REFERRALS */
       break;
   case 'A':   /* retrieve attribute names only -- no values */
       ++attrsonly;
       break;
   case 'L':   /* print entries in LDIF format */
       ++ldif;
       /* fall through -- always allow binary when outputting LDIF */
   case 'B':   /* allow binary values to be printed */
       ++allow_binary;
       break;
   case 's':   /* search scope */
       if ( strncasecmp( optarg, "base", 4 ) == 0 ) {
       scope = LDAP_SCOPE_BASE;
       } else if ( strncasecmp( optarg, "one", 3 ) == 0 ) {
       scope = LDAP_SCOPE_ONELEVEL;
       } else if ( strncasecmp( optarg, "sub", 3 ) == 0 ) {
       scope = LDAP_SCOPE_SUBTREE;
       } else {
       fprintf( stderr, "scope should be base, one, or sub\n" );
       usage( argv[ 0 ] );
                exit(1);
       }
       break;

   case 'a':   /* set alias deref option */
       if ( strncasecmp( optarg, "never", 5 ) == 0 ) {
       deref = LDAP_DEREF_NEVER;
       } else if ( strncasecmp( optarg, "search", 5 ) == 0 ) {
       deref = LDAP_DEREF_SEARCHING;
       } else if ( strncasecmp( optarg, "find", 4 ) == 0 ) {
       deref = LDAP_DEREF_FINDING;
       } else if ( strncasecmp( optarg, "always", 6 ) == 0 ) {
       deref = LDAP_DEREF_ALWAYS;
       } else {
       fprintf( stderr, "alias deref should be never, search, find, or always\n" );
       usage( argv[ 0 ] );
                exit(1);
       }
       break;
       
   case 'F':   /* field separator */
       sep = (char *)strdup( optarg );
       break;
   case 'f':   /* input file */
       infile = (char *)strdup( optarg );
       break;
   case 'h':   /* ldap host */
       ldaphost = (char *)strdup( optarg );
       break;
   case 'b':   /* searchbase */
       base = (char *)strdup( optarg );
       break;
   case 'D':   /* bind DN */
       binddn = (char *)strdup( optarg );
       break;
   case 'p':   /* ldap port */
       ldapport = atoi( optarg );
       break;
   case 'w':   /* bind password */
       passwd = (char *)strdup( optarg );
       break;
   case 'l':   /* time limit */
       timelimit = atoi( optarg );
       break;
   case 'z':   /* size limit */
       sizelimit = atoi( optarg );
       break;
   case 'S':   /* sort attribute */
       sortattr = (char *)strdup( optarg );
       break;
   case 'W':   /* Wallet URL */
       sslwrl = (char *)strdup( optarg );
       break;
   case 'P':   /* Wallet password */
       sslpasswd = (char *)strdup( optarg );
       break;
   case 'U':   /* SSL Authentication Mode */
       sslauth = atoi( optarg );
       break;
   default:
       usage( argv[0] );
            exit(1);
            break;
   }
    }

    if ( argc - optind < 1 ) {
   usage( argv[ 0 ] );
        exit(1);
    }
    filtpattern = (char *)strdup( argv[ optind ] );
    if ( argv[ optind + 1 ] == NULL ) {
   attrs = NULL;
    } else if ( sortattr == NULL || *sortattr == '\0' ) {
        attrs = &argv[ optind + 1 ];
    } else {
   for ( i = optind + 1; i < argc; i++ ) {
       if ( strcasecmp( argv[ i ], sortattr ) == 0 ) {
       break;
       }
   }
   if ( i == argc ) {
       skipsortattr = 1;
       argv[ optind ] = sortattr;
   } else {
       optind++;
   }
        attrs = &argv[ optind ];
    }

    if ( infile != NULL ) {
   if ( infile[0] == '-' && infile[1] == '\0' ) {
       fp = stdin;
   } else if (( fp = fopen( infile, "r" )) == NULL ) {
       perror( infile );
       exit( 1 );
   }
    }

    if (ldaphost == NULL) {
        if (gethostname(localHostName, MAXHOSTNAMELEN) != 0) {
                perror("gethostname");
                exit(1);
        }
        ldaphost = localHostName;
    }

    if ( verbose ) {
   printf( "ldap_open( %s, %d )\n", ldaphost, ldapport );
    }

    if (( ld = ldap_open( ldaphost, ldapport )) == NULL ) {
   perror( ldaphost );
   exit( 1 );
    }

    if (sslauth > 1)
    {
       if (!sslwrl || !sslpasswd)
      {
          printf ("Null Wallet or password given\n");
          exit (0);
       }
    }
    if (sslauth > 0)
    {
        if (sslauth == 1)
            sslauth = GSLC_SSL_NO_AUTH;
        else if (sslauth == 2)
            sslauth = GSLC_SSL_ONEWAY_AUTH;
        else if (sslauth == 3)
            sslauth = GSLC_SSL_TWOWAY_AUTH; 
        else
        {
           printf(" Wrong SSL Authenication Mode Value\n");
           exit(0); 
        }

       err = ldap_init_SSL(&ld->ld_sb,sslwrl,sslpasswd,sslauth);
       if(err != 0) 
       {
           printf(" %s\n", ldap_err2string(err));
           exit(0); 
       }
    }

    ld->ld_deref = deref;
    ld->ld_timelimit = timelimit;
    ld->ld_sizelimit = sizelimit;
    ld->ld_options = ldap_options;

    if ( !kerberos ) {
   authmethod = LDAP_AUTH_SIMPLE;
    } else if ( kerberos == 1 ) {
   authmethod = LDAP_AUTH_KRBV41;
    } else {
   authmethod =  LDAP_AUTH_KRBV4;
    }
    if ( ldap_bind_s( ld, binddn, passwd, authmethod ) != LDAP_SUCCESS ) {
   ldap_perror( ld, "ldap_bind" );
   exit( 1 );
    }

    if ( verbose ) {
   printf( "filter pattern: %s\nreturning: ", filtpattern );
   if ( attrs == NULL ) {
       printf( "ALL" );
   } else {
       for ( i = 0; attrs[ i ] != NULL; ++i ) {
       printf( "%s ", attrs[ i ] );
       }
   }
   putchar( '\n' );
    }

    if ( infile == NULL ) {
   rc = dosearch( ld, base, scope, attrs, attrsonly, filtpattern, "" );
    } else {
   rc = 0;
   first = 1;
   while ( rc == 0 && fgets( line, sizeof( line ), fp ) != NULL ) {
       line[ strlen( line ) - 1 ] = '\0';
       if ( !first ) {
       putchar( '\n' );
       } else {
       first = 0;
       }
       rc = dosearch( ld, base, scope, attrs, attrsonly, filtpattern,
           line );
   }
   if ( fp != stdin ) {
       fclose( fp );
   }
    }

    ldap_unbind( ld );
    exit( rc );
}

dosearch( ld, base, scope, attrs, attrsonly, filtpatt, value )
    LDAP   *ld;
    char   *base;
    int        scope;
    char   **attrs;
    int        attrsonly;
    char   *filtpatt;
    char   *value;
{
    char       filter[ BUFSIZ ], **val;
    int            rc, first, matches;
    LDAPMessage        *res, *e;

    sprintf( filter, filtpatt, value );

    if ( verbose ) {
   printf( "filter is: (%s)\n", filter );
    }

    if ( not ) {
   return( LDAP_SUCCESS );
    }

    if ( ldap_search( ld, base, scope, filter, attrs, attrsonly ) == -1 ) {
   ldap_perror( ld, "ldap_search" );
   return( ld->ld_errno );
    }

    matches = 0;
    first = 1;
    while ( (rc = ldap_result( ld, LDAP_RES_ANY, sortattr ? 1 : 0, NULL, &res ))
       == LDAP_RES_SEARCH_ENTRY ) {
   matches++;
   e = ldap_first_entry( ld, res );
   if ( !first ) {
       putchar( '\n' );
   } else {
       first = 0;
   }
   print_entry( ld, e, attrsonly );
   ldap_msgfree( res );
    }
    if ( rc == -1 ) {
   ldap_perror( ld, "ldap_result" );
   return( rc );
    }
    if (( rc = ldap_result2error( ld, res, 0 )) != LDAP_SUCCESS ) {
        ldap_perror( ld, "ldap_search" );
    }
    if ( sortattr != NULL ) {
       extern int  strcasecmp();

       (void) ldap_sort_entries( ld, &res,
           ( *sortattr == '\0' ) ? NULL : sortattr, strcasecmp );
       matches = 0;
       first = 1;
       for ( e = ldap_first_entry( ld, res ); e != NULLMSG;
           e = ldap_next_entry( ld, e ) ) {
       matches++;
       if ( !first ) {
           putchar( '\n' );
       } else {
           first = 0;
       }
       print_entry( ld, e, attrsonly );
       }
    }

    if ( verbose ) {
        printf( "%d matches\n", matches );
    }

    ldap_msgfree( res );
    return( rc );
}


print_entry( ld, entry, attrsonly )
    LDAP   *ld;
    LDAPMessage    *entry;
    int        attrsonly;
{
    char       *a, *dn, *ufn, tmpfname[ 64 ];
    int            i, j, notascii;
    BerElement     *ber;
    struct berval  **bvals;
    FILE       *tmpfp;
    extern char        *mktemp();

    dn = ldap_get_dn( ld, entry );
    if ( ldif ) {
   write_ldif_value( "dn", dn, strlen( dn ));
    } else {
   printf( "%s\n", dn );
    }
    if ( includeufn ) {
   ufn = ldap_dn2ufn( dn );
   if ( ldif ) {
       write_ldif_value( "ufn", ufn, strlen( ufn ));
   } else {
       printf( "%s\n", ufn );
   }
   free( ufn );
    }
    free( dn );

    for ( a = ldap_first_attribute( ld, entry, &ber ); a != NULL;
       a = ldap_next_attribute( ld, entry, ber ) ) {
   if ( skipsortattr && strcasecmp( a, sortattr ) == 0 ) {
       continue;
   }
   if ( attrsonly ) {
       if ( ldif ) {
       write_ldif_value( a, "", 0 );
       } else {
       printf( "%s\n", a );
       }
   } else if (( bvals = ldap_get_values_len( ld, entry, a )) != NULL ) {
       for ( i = 0; bvals[i] != NULL; i++ ) {
       if ( vals2tmp ) {
           sprintf( tmpfname, "/tmp/ldapsearch-%s-XXXXXX", a );
           tmpfp = NULL;

           if ( mktemp( tmpfname ) == NULL ) {
           perror( tmpfname );
           } else if (( tmpfp = fopen( tmpfname, "w")) == NULL ) {
           perror( tmpfname );
           } else if ( fwrite( bvals[ i ]->bv_val,
               bvals[ i ]->bv_len, 1, tmpfp ) == 0 ) {
           perror( tmpfname );
           } else if ( ldif ) {
           write_ldif_value( a, tmpfname, strlen( tmpfname ));
           } else {
           printf( "%s%s%s\n", a, sep, tmpfname );
           }

           if ( tmpfp != NULL ) {
           fclose( tmpfp );
           }
       } else {
           notascii = 0;
           if ( !allow_binary ) {
           for ( j = 0; j < bvals[ i ]->bv_len; ++j ) {
               if ( !isascii( bvals[ i ]->bv_val[ j ] )) {
               notascii = 1;
               break;
               }
           }
           }

           if ( ldif ) {
           write_ldif_value( a, bvals[ i ]->bv_val,
               bvals[ i ]->bv_len );
           } else 
{
           printf( "%s%s%s\n", a, sep,
               notascii ? "NOT ASCII" : (char *)bvals[ i ]->bv_val );
           }
       }
       }
       gsledePBerBvecfree( bvals );
   }
    }
}


int
write_ldif_value( char *type, char *value, unsigned long vallen )
{
    char *ldif;

    if (( ldif = gsldlDLdifTypeAndValue( type, value, (int)vallen )) == NULL ) 
    {
    return( -1 );
    }

    fputs( ldif, stdout );
    free( ldif );

    return( 0 );
}

Dependencies and Limitations

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 Internet Directory Administrator's Guide for details on 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:

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).


Go to previous page Go to next page
Oracle
Copyright © 1999, 2002 Oracle Corporation.

All Rights Reserved.
Go To Documentation Library
Home
Go To Product List
Book List
Go To Table Of Contents
Contents
Go To Index
Index

Master Index

Feedback