Что такое код ldap_parse_result

Содержание

Что такое код ldap_parse_result

#include
int ldap_parse_result( LDAP *ld, LDAPMessage *result,
int *errcodep, char **matcheddnp, char **errmsgp,
char ***referralsp, LDAPControl ***serverctrlsp,
int freeit )
int ldap_parse_sasl_bind_result( LDAP *ld, LDAPMessage *result,
struct berval **servercredp, int freeit )
int ldap_parse_extended_result( LDAP *ld, LDAPMessage *result,
char **retoidp, struct berval **retdatap, int freeit )

DESCRIPTION

These routines are used to extract information from a result message. They will operate on the first result message in a chain of search results (skipping past other message types). They take the result as returned by a call to ldap_result(3), ldap_search_s(3) or ldap_search_st(3). In addition to ldap_parse_result(), the routines ldap_parse_sasl_bind_result() and ldap_parse_extended_result() are used to get all the result information from SASL bind and extended operations.

The errcodep parameter will be filled in with the result code from the result message.

The server might supply a matched DN string in the message indicating how much of a name in a request was recognized. The matcheddnp parameter will be filled in with this string if supplied, else it will be NULL. If a string is returned, it should be freed using ldap_memfree(3).

The errmsgp parameter will be filled in with the error message field from the parsed message. This string should be freed using ldap_memfree(3).

The referralsp parameter will be filled in with an allocated array of referral strings from the parsed message. This array should be freed using ldap_memvfree(3). If no referrals were returned, *referralsp is set to NULL.

The serverctrlsp parameter will be filled in with an allocated array of controls copied from the parsed message. The array should be freed using ldap_controls_free(3). If no controls were returned, *serverctrlsp is set to NULL.

The freeit parameter determines whether the parsed message is freed or not after the extraction. Any non-zero value will make it free the message. The ldap_msgfree(3) routine can also be used to free the message later.

For SASL bind results, the servercredp parameter will be filled in with an allocated berval structure containing the credentials from the server if present. The structure should be freed using ber_bvfree(3).

For extended results, the retoidp parameter will be filled in with the dotted-OID text representation of the name of the extended operation response. The string should be freed using ldap_memfree(3). If no OID was returned, *retoidp is set to NULL.

For extended results, the retdatap parameter will be filled in with a pointer to a berval structure containing the data from the extended operation response. The structure should be freed using ber_bvfree(3). If no data were returned, *retdatap is set to NULL.

For all the above result parameters, NULL values can be used in calls in order to ignore certain fields.

ldap_parse_result

(PHP 4 >= 4.0.5, PHP 5, PHP 7)

ldap_parse_result — Extract information from result

Description

Parses an LDAP search result.

Parameters

An LDAP result resource, returned by ldap_list() or ldap_search() .

A reference to a variable that will be set to the LDAP error code in the result, or if no error occurred.

A reference to a variable that will be set to a matched DN if one was recognised within the request, otherwise it will be set to NULL .

A reference to a variable that will be set to the LDAP error message in the result, or an empty string if no error occurred.

A reference to a variable that will be set to an array set to all of the referral strings in the result, or an empty array if no referrals were returned.

Return Values

Returns TRUE on success or FALSE on failure.

Examples

Example #1 ldap_parse_result() example

Страницы справочника OS X

  • Оглавление
  • Загрузите пример кода

Unicode and ANSI names

ldap_parse_resultW (Unicode) and ldap_parse_resultA (ANSI)

LDAP.com

Lightweight Directory Access Protocol

LDAP Result Code Reference: Client-Side Result Codes

Most LDAP result codes are intended to be included in responses from the directory server to the client. However, there are also a number of possible client-side error conditions that may arise in the course of attempting to process operations, and it’s often convenient for LDAP APIs to allow developers to treat those client-side problems in the same way that they would treat an error response from the server.

There are a couple of specifications, draft-ietf-ldapext-ldap-c-api and draft-ietf-ldapext-ldap-java-api, that suggest APIs that C-based and Java-based libraries could expose to facilitate communication with an LDAP directory server. Although you can certainly debate how good the proposed APIs are (and there are many LDAP libraries that have chosen to expose different interfaces), they are at the very least useful because they define a number of result codes that can be used to represent client-side error conditions. This chapter explores these client-side result codes.

serverDown (81)

The serverDown result code doesn’t necessarily mean that the directory server has gone down. It merely indicates that an existing connection to the server is no longer valid. Some of the possible reasons for this result code include:

  • The directory server (or the system, virtual machine, or container on which it was running) crashed or was shut down.
  • The server closed the connection (for example, because the connection remained idle for too long).
  • An administrator caused the connection to be terminated.
  • A networking problem interfered with the communication between the client and the server, or a piece of networking hardware is configured to drop connections after they are idle for too long.
  • The client attempted to negotiate a security layer (for example, with a StartTLS extended request), but a problem was encountered.

Regardless of the cause of the connection closure, the client will need to re-establish the connection, or establish a connection to a different server, before it can submit additional requests.

In the event that the directory server software closed the connection to the client (whether because it was being shut down or for some other reason), it may send a notice of disconnection unsolicited notification with a reason for the closure. Clients should watch for unsolicited notifications because if the server does send a notice of disconnection, it can help the client detect and react to certain connection closures more quickly.

localError (82)

The localError result code indicates that a problem occurred in the client for which none of the other client-side result codes is more appropriate. It’s the client-side equivalent of the other (80) result code, and it often means that an unexpected error has occurred in the library that the client is using to perform LDAP communication.

encodingError (83)

The encodingError result code indicates that a problem occurred while the client was attempting to encode a request to send to the directory server. This is not a commonly-used result code, since there are other result codes that are more appropriate for many of the conditions that can lead to encoding failures (for example, paramError (89) if there is a problem with one of the request parameters, or noMemory (90) if a problem occurs while attempting to allocate memory to hold the request).

decodingError (84)

The decodingError result code indicates that a problem occurred while the client was trying to decode a response received from the directory server. This generally means that either the server sent a malformed response or that the LDAP client library has a bug in it that prevents it from parsing a valid response.

timeout (85)

The timeout result code indicates that the client did not receive an expected response to a request after waiting for some maximum length of time. Clients often provide some mechanism for configuring the maximum request time limit (whether global, connection-wide, or operation-specific), and if that time limit is reached without receiving a response, then the client will stop waiting for the response and report an error with this result code.

Optionally, the client may also send an abandon or cancel request to the directory server to indicate that it should stop processing the operation, but the client should not assume that the server will not complete the associated processing. If the request was for a write operation, then the requested change may still eventually be applied.

authUnknown (86)

The authUnknown result code indicates that the client attempted to process some kind of authentication (presumably, a SASL mechanism) that the LDAP library does not recognize or support.

filterError (87)

The filterError result code indicates that the LDAP client encountered an error related to a search filter. This usually means that the client encountered a problem while trying to parse a string as a search filter, but there may be other cases in which it may be used. For example, the matched values request control (described in RFC 3876) may be used to indicate that the server should only return values for a specified attribute that match a given filter, but not all filter types may be used in conjunction with this filter, and an attempt to include an unsupported filter type may trigger the filterError result code.

userCanceled (88)

The userCanceled result code indicates that the operation was canceled by the client. It may have been interactively canceled (for example, by pressing Ctrl+C on a command-line tool, or clicking a cancel button in a graphical interface), or it may have been automatically generated by the client for some reason (for example, because another thread using the same connection sent an abandon request for the operation).

paramError (89)

The paramError result code indicates that the client application or end user provided an inappropriate value for some parameter. This may be an invalid argument for a function or method, an invalid value provided for a command-line argument, illegal input into some form field, or any other area in which the LDAP client API may encounter and reject invalid data.

noMemory (90)

The noMemory result code indicates that the client encountered a memory-related problem during processing. It usually means that the client failed to allocate memory or its memory consumption would have exceeded some maximum allowed amount.

connectError (91)

The connectError result code indicates that the client encountered a problem while attempting to establish a connection to the directory server. There are a number of potential reasons for this result code, including:

  • The directory server is currently down or not accepting new connections.
  • A networking problem prevents the client from reaching the directory server.
  • There was a problem negotiating a security layer between the client and the server (for example, the server’s certificate is expired of the client doesn’t trust it).
  • The client encounters a connection timeout before the connection can be established.

The connectError result code is different from the serverDown (81) result code in that connectError applies when trying to establish a new connection, while serverDown applies when the client detects that an already-established connection is no longer valid.

notSupported (92)

The notSupported result code indicates that the client attempted to perform some operation that is not supported by the LDAP client library. This result code should only be used if there isn’t another result code that is more specific to the condition at hand. For example, if the client is trying to use an unsupported SASL mechanism, then the authUnknown (86) result code is more appropriate. Or if the client doesn’t support StartTLS, then the tlsNotSupported (112) result code is more appropriate.

controlNotFound (93)

The controlNotFound result code indicates that a response received from the directory server did not include an expected response control. There are a number of request controls that, if successfully processed, should cause the result to include a corresponding response control. This result code may be used if the client expected a particular response control to be returned, but it wasn’t found in the response.

noResultsReturned (94)

The noResultsReturned result code indicates that the client didn’t receive any expected response messages (in addition to the final response indicating that the operation has completed). This usually means that the client expected the server to return one or more entries in response to a search operation, but it could also apply to search result references or intermediate responses.

moreResultsToReturn (95)

The moreResultsToReturn result code indicates that the client has received some of the responses for an operation, but that it also expects there are more responses available to be retrieved. The most likely use for this result code would be for the case in which the client attempts to retrieve only a portion of search results with the simple paged results control (RFC 2696) or the virtual list view request control (draft-ietf-ldapext-ldapv3-vlv). If the server returns all of the entries in the page of results, but the response indicates that there may be more pages that can be returned, the client may use this result code to indicate that. However, there may also be other uses for this result code involving a case in which the client expects that there may be search result entries, search result references, or intermediate responses.

clientLoop (96)

The clientLoop result code indicates that the client has detected some kind of loop while processing results from the server. It usually applies when the client is trying to follow a referral (or a search result reference) and encounters a referral URL that it has already tried to follow.

referralLimitExceeded (97)

The referralLimitExceeded result code indicates that the client has reached some limit when trying to follow referrals returned during processing. The two most likely reasons for this result code include:

  • While trying to follow referral returned by the server, the client has encountered additional referrals. Most clients have a limit on the maximum number of hops they will make while trying to follow a referral, and this result code may be used if that hop limit would have been exceeded.
  • The client may impose a limit on the maximum number of search result references it can handle when processing a search operation. The client may use this result code if that limit would have been exceeded.

invalidResponse (100)

The invalidResponse result code indicates that the client has received some kind of invalid response. It’s like a client-side version of the protocolError (2) result code, and can be used to indicate a couple of possible problems:

  • The client received a malformed response from the server that can’t be parsed as a valid LDAP message.
  • The client received a response message that isn’t appropriate for the request that it sent. For example, if it sent a search request but got back an add response.

ambiguousResponse (101)

The ambiguousResponse result code indicates that the client received more than one final response message for the same request. You will probably never encounter this result code because it depends on two highly unlikely events: the server would have to send multiple final responses for the same request, and the client would have to recognize that it received multiple final responses for the same request. Even if the server were to incorrectly return multiple final responses to the same request, the client would probably just take the first one and ignore any subsequent final responses for that request.

tlsNotSupported (112)

The tlsNotSupported result code indicates that the client indicated a desire to begin TLS (Transport Layer Security, formerly known as the Secure Sockets Layer, or SSL) negotiation on a connection, but the client library does not support (or is not configured properly to handle) TLS encryption. This may be used when trying to establish a connection that is secured with TLS from the beginning, or when trying to use the StartTLS extended operation to add TLS security to an existing insecure connection.

intermediateResponse (113)

The intermediateResponse result code indicates that the client received an intermediate response message from the server. Intermediate response messages were introduced in RFC 3771 and can be used to convey additional information in messages before the final response. This result code could be useful for client APIs that don’t provide some other means of handling intermediate responses (like an intermediate response listener) but still want to make them available to the client application.

unknownType (114)

The unknownType result code indicates that the client received a response with an unrecognized BER type. Every LDAP message has a message ID, a protocol operation, and an optional set of controls. The protocol operation element contains the bulk of the response, but it also has a BER type, which indicates what kind of response it is. The unknownType result code may be used if the client receives a response message with a protocol operation that has an unknown BER type.

Что такое код ldap_parse_result

(PHP 4 >= 4.0.5, PHP 5)

ldap_parse_result — Extract information from result

Description bool ldap_parse_result ( resource link, resource result, int &errcode [, string &matcheddn [, string &errmsg [, array &referrals]]] )

Эта страница руководства является частью версии 5.0 Инструментов XCode

Получить эти инструменты:

Установите Инструменты XCode от developer.apple.com.

Если Вы выполняете версию Инструментов XCode кроме 5,0, просматриваете документацию локально:

В Терминале, с помощью человека (1) команда

Читать страницы руководства

Страницы руководства предназначаются как справочник для людей, уже понимающих технологию.

Чтобы изучить, как руководство организовано или узнать о синтаксисе команды, прочитайте страницу руководства для страниц справочника (5).

Для получения дополнительной информации об этой технологии, ищите другую документацию в Библиотеке Разработчика Apple.

Для получения общей информации о записи сценариев оболочки, считайте Shell, Пишущий сценарий Учебника для начинающих.

Сообщение о проблемах

Способ сообщить о проблеме с этой страницей руководства зависит от типа проблемы:

Ошибки содержания Ошибки отчета в содержании этой документации со ссылками на отзыв ниже. Отчеты об ошибках Сообщите об ошибках в функциональности описанного инструмента или API через Генератор отчетов Ошибки. Форматирование проблем Отчет, форматирующий ошибки в интерактивной версии этих страниц со ссылками на отзыв ниже.

ldap_parse_extended_resultA function

The ldap_parse_extended_result parses the results of an LDAP extended operation.

Syntax

Parameters

The session handle.

A pointer to an LDAPMessage structure as returned by ldap_result in response to an extended operation request.

A pointer to a null-terminated string that contains the dotted object identifier (OID) text string of the server’s response message. This is normally the same OID as the one naming the request that was originally passed to the server by ldap_extended_operation.

The arbitrary data returned by the extended operation (if NULL, no data is returned by the server).

Determines whether the ResultMessage parameter is freed. You can pass any nonzero value to the Freeit parameter to free the ResultMessage pointer when it is no longer needed, or you can call ldap_msgfree to free the result later.

Return Value

If the function succeeds, the return value is LDAP_SUCCESS.

If the function fails, it returns an error code. See Return Values for more information.

Remarks

When a server processes an extended operation request generated by ldap_extended_operation, it returns an LDAP message along with an LDAP_RES_EXTENDED return code. Use ldap_parse_extended_result to parse this result message, which returns both the text OID of the originating message in ResultOID and any arbitrary data generated by the extended operation in ResultData.

When they are no longer needed, free the ResultOID string and the ResultData buffer by calling ldap_memfree.

Поиск OpenLDAP API

Я пытаюсь выполнить поиск LDAP с использованием API OpenLDAP. Я уже успешно подключен и привязан к серверу. Я выполнил поиск с помощью ldap_search_ext_s () и проанализировал результат с помощью ldap_parse_result (). Тем не менее, я не могу понять, как получить реальные результаты поиска. К сожалению, API OpenLDAP C недавно изменился, и многие из существующих примеров в Интернете не используют текущий API.

Я уже пытался использовать ldap_first_attribute (), ldap_next_attribute () и ldap_get_values ​​(), как показано на http://www-archive.mozilla.org/directory/csdk-docs/search.htm (Пример 6-13). Однако, похоже, что ldap_get_values ​​() теперь устарела и что ldap_get_values_len () является ближайшей заменой. Вместо того, чтобы возвращать char **, новая функция возвращает berval **. Я попытался настроить этот пример кода, создав berval * со значением barval ** [i]. Это приводит к успешной компиляции, но дамп ядра в ber_scanf ().

Кто-нибудь знает, как получить результаты поиска LDAP с помощью OpenLDAP C API?

ОБНОВИТЬ:

В частности, я спрашиваю, как получить атрибуты, запрошенные из поискового сообщения.

Решение

Результат поискового запроса всегда содержит серию SearchResultEntry или же SeachResultReference сообщения, эта серия заканчивается SearchResultDone сообщение. призвание getNextAttribute (на любом языке и в любом API) не имеет никакого смысла, потому что результаты поиска представляют собой список сообщений. API должен упаковать массив записей или ссылок таким образом, чтобы вызывающая сторона могла просто получить список записей или ссылок. Ищите метод, который делает это.

Другие решения

Взглянув на исходный код API OpenLDAP и увидев, как использовалось значение berval, я в конце концов наткнулся на то, как получить его значение.

Во-первых, вы должны получить первую запись с ldap_first_entry() , Затем вам нужно получить первый атрибут в этой записи с помощью ldap_first_attribute() , Затем поместите значения в массив Berval ** с ldap_get_values_len() , К возвращенным значениям атрибута можно получить доступ с помощью berval[i]->bv_val ,

Вы можете получить следующие записи и атрибуты с ldap_next_entry() а также ldap_next_attribute() соответственно.

Я надеюсь, что это помогает любому, у кого есть подобная проблема.

надеюсь, что ниже функция может помочь вам,

Что такое код ldap_parse_result

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 **resultoidp , struct berval **resultdata , int freeit );

DESCRIPTION

The ldap_parse_extended_result() , ldap_parse_result() and ldap_parse_sasl_bind_result() routines search for a message to parse. These functions skip messages of type LDAP_RES_SEARCH_ENTRY and LDAP_RES_SEARCH_REFERENCE.

RETURN VALUES

They return LDAP_SUCCESS if the result was successfully parsed or an LDAP error code if not (see ldap_error(3LDAP)).

ATTRIBUTES

See attributes(5) for a description of the following attributes:

Что такое код ldap_parse_result

The ldap_parse_result function parses responses from the server and returns the appropriate fields.

Syntax

Parameters

The session handle.

The result of an LDAP operation as returned by one of the synchronous operation calls or by ldap_result for an asynchronous operation.

ReturnCode [out, optional]

Indicates the outcome of the server operation that generated the original result message. Pass NULL to ignore this field.

MatchedDNs [out, optional]

A pointer to a wide, null-terminated string. In the case of a return of LDAP_NO_SUCH_OBJECT, this result parameter is filled in with a distinguished name indicating how much of the name in the request was recognized. Pass NULL to ignore this field.

ErrorMessage [out, optional]

A pointer to a wide, null-terminated string that contains the contents of the error message field from the ResultMessage parameter. Pass NULL to ignore this field.

Referrals [out, optional]

A pointer to a wide, null-terminated string that contains the contents of the referrals field from the ResultMessage parameter, indicating zero or more alternate LDAP servers where the request should be retried. Pass NULL to ignore this field.

ServerControls [out, optional]

This result parameter is filled in with an allocated array of controls copied from the ResultMessage parameter.

Determines whether the ResultMessage parameter is freed. You can pass any nonzero value to the Freeit parameter to free the ResultMessage pointer when it is no longer needed, or you can call ldap_msgfree to free the result later.

Return value

If the function succeeds, the return value is LDAP_SUCCESS.

If the function fails, it returns an error code. See Return Values for more information.

Remarks

The ldap_parse_result function traverses a chain of server responses looking for result messages to parse. Use this function if you want to access the referrals, matching distinguished names, or server controls returned. The function skips over messages of type LDAP_RES_SEARCH_ENTRY and LDAP_RES_SEARCH_REFERENCE.

When they are no longer needed, free the ErrorMessage and MatchedDNs strings by calling ldap_memfree. Free the Referrals array by calling ldap_value_free. Free the ServerControls by calling ldap_controls_free.

Requirements

Minimum supported client

Minimum supported server

Windows Server 2008

Wldap32.lib
Wldap32.dll

К настоящему времени эта функция еще не была документирована; для ознакомления доступен только список аргументов.

Внимание
Пред. Начало След.
ldap_parse_reference Уровень выше ldap_read

Если Вы не нашли что искали, то рекомендую воспользоваться поиском по сайту:

Страницы справочника OS X

  • Оглавление
  • Загрузите пример кода

Эта страница руководства является частью версии 5.0 Инструментов XCode

Получить эти инструменты:

Установите Инструменты XCode от developer.apple.com.

Если Вы выполняете версию Инструментов XCode кроме 5,0, просматриваете документацию локально:

В Терминале, с помощью человека (1) команда

Читать страницы руководства

Страницы руководства предназначаются как справочник для людей, уже понимающих технологию.

Чтобы изучить, как руководство организовано или узнать о синтаксисе команды, прочитайте страницу руководства для страниц справочника (5).

Для получения дополнительной информации об этой технологии, ищите другую документацию в Библиотеке Разработчика Apple.

Для получения общей информации о записи сценариев оболочки, считайте Shell, Пишущий сценарий Учебника для начинающих.

Сообщение о проблемах

Способ сообщить о проблеме с этой страницей руководства зависит от типа проблемы:

Ошибки содержания Ошибки отчета в содержании этой документации со ссылками на отзыв ниже. Отчеты об ошибках Сообщите об ошибках в функциональности описанного инструмента или API через Генератор отчетов Ошибки. Форматирование проблем Отчет, форматирующий ошибки в интерактивной версии этих страниц со ссылками на отзыв ниже.

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