r26355: Eliminate global_loadparm in more places.
[kai/samba.git] / source4 / libcli / ldap / ldap_client.c
index 503016e896dd4ad481df7e2877b8074ab95d8e01..906e9c2574fdd1917d2d9b5864aff542e81071f7 100644 (file)
@@ -9,7 +9,7 @@
     
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
+   the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
    
    This program is distributed in the hope that it will be useful,
    GNU General Public License for more details.
    
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
 */
 
 #include "includes.h"
-#include "asn_1.h"
-#include "dlinklist.h"
+#include "libcli/util/asn_1.h"
+#include "lib/util/dlinklist.h"
 #include "lib/events/events.h"
 #include "lib/socket/socket.h"
-#include "lib/tls/tls.h"
 #include "libcli/ldap/ldap.h"
 #include "libcli/ldap/ldap_client.h"
 #include "libcli/composite/composite.h"
 #include "lib/stream/packet.h"
+#include "lib/tls/tls.h"
+#include "auth/gensec/gensec.h"
+#include "system/time.h"
+#include "param/param.h"
 
 
-/*
+/**
   create a new ldap_connection stucture. The event context is optional
 */
-struct ldap_connection *ldap_new_connection(TALLOC_CTX *mem_ctx, 
-                                           struct event_context *ev)
+struct ldap_connection *ldap4_new_connection(TALLOC_CTX *mem_ctx, 
+                                            struct loadparm_context *lp_ctx,
+                                            struct event_context *ev)
 {
        struct ldap_connection *conn;
 
@@ -59,13 +62,17 @@ struct ldap_connection *ldap_new_connection(TALLOC_CTX *mem_ctx,
        conn->next_messageid  = 1;
        conn->event.event_ctx = ev;
 
+       conn->lp_ctx = lp_ctx;
+
        /* set a reasonable request timeout */
        conn->timeout = 60;
 
+       /* explicitly avoid reconnections by default */
+       conn->reconnect.max_retries = 0;
+       
        return conn;
 }
 
-
 /*
   the connection is dead
 */
@@ -73,6 +80,7 @@ static void ldap_connection_dead(struct ldap_connection *conn)
 {
        struct ldap_request *req;
 
+       /* return an error for any pending request ... */
        while (conn->pending) {
                req = conn->pending;
                DLIST_REMOVE(req->conn->pending, req);
@@ -81,20 +89,28 @@ static void ldap_connection_dead(struct ldap_connection *conn)
                if (req->async.fn) {
                        req->async.fn(req);
                }
-       }       
+       }
 
-       talloc_free(conn->tls);
-       conn->tls = NULL;
+       talloc_free(conn->sock);  /* this will also free event.fde */
+       talloc_free(conn->packet);
+       conn->sock = NULL;
+       conn->event.fde = NULL;
+       conn->packet = NULL;
 }
 
+static void ldap_reconnect(struct ldap_connection *conn);
+
 /*
   handle packet errors
 */
-static void ldap_error_handler(void *private, NTSTATUS status)
+static void ldap_error_handler(void *private_data, NTSTATUS status)
 {
-       struct ldap_connection *conn = talloc_get_type(private, 
+       struct ldap_connection *conn = talloc_get_type(private_data
                                                       struct ldap_connection);
        ldap_connection_dead(conn);
+
+       /* but try to reconnect so that the ldb client can go on */
+       ldap_reconnect(conn);
 }
 
 
@@ -104,6 +120,7 @@ static void ldap_error_handler(void *private, NTSTATUS status)
 static void ldap_match_message(struct ldap_connection *conn, struct ldap_message *msg)
 {
        struct ldap_request *req;
+       int i;
 
        for (req=conn->pending; req; req=req->next) {
                if (req->messageid == msg->messageid) break;
@@ -120,6 +137,20 @@ static void ldap_match_message(struct ldap_connection *conn, struct ldap_message
                return;
        }
 
+       /* Check for undecoded critical extensions */
+       for (i=0; msg->controls && msg->controls[i]; i++) {
+               if (!msg->controls_decoded[i] && 
+                   msg->controls[i]->critical) {
+                       req->status = NT_STATUS_LDAP(LDAP_UNAVAILABLE_CRITICAL_EXTENSION);
+                       req->state = LDAP_REQUEST_DONE;
+                       DLIST_REMOVE(conn->pending, req);
+                       if (req->async.fn) {
+                               req->async.fn(req);
+                       }
+                       return;
+               }
+       }
+
        /* add to the list of replies received */
        talloc_steal(req, msg);
        req->replies = talloc_realloc(req, req->replies, 
@@ -152,114 +183,61 @@ static void ldap_match_message(struct ldap_connection *conn, struct ldap_message
 
 
 /*
-  check if a blob is a complete ldap packet
-  handle wrapper or unwrapped connections
+  decode/process LDAP data
 */
-NTSTATUS ldap_complete_packet(void *private, DATA_BLOB blob, size_t *size)
+static NTSTATUS ldap_recv_handler(void *private_data, DATA_BLOB blob)
 {
-       struct ldap_connection *conn = talloc_get_type(private, 
+       NTSTATUS status;
+       struct ldap_connection *conn = talloc_get_type(private_data, 
                                                       struct ldap_connection);
-       if (conn->enable_wrap) {
-               return packet_full_request_u32(private, blob, size);
-       }
-       return ldap_full_packet(private, blob, size);
-}
-
-/*
-  decode/process plain data
-*/
-static NTSTATUS ldap_decode_plain(struct ldap_connection *conn, DATA_BLOB blob)
-{
-       struct asn1_data asn1;
        struct ldap_message *msg = talloc(conn, struct ldap_message);
+       struct asn1_data *asn1 = asn1_init(conn);
 
-       if (msg == NULL) {
+       if (asn1 == NULL || msg == NULL) {
                return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
        }
 
-       if (!asn1_load(&asn1, blob)) {
+       if (!asn1_load(asn1, blob)) {
+               talloc_free(msg);
+               talloc_free(asn1);
                return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
        }
        
-       if (!ldap_decode(&asn1, msg)) {
-               return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
+       status = ldap_decode(asn1, msg);
+       if (!NT_STATUS_IS_OK(status)) {
+               asn1_free(asn1);
+               return status;
        }
 
        ldap_match_message(conn, msg);
 
        data_blob_free(&blob);
-       asn1_free(&asn1);
-       return NT_STATUS_OK;
-}
-
-/*
-  decode/process wrapped data
-*/
-static NTSTATUS ldap_decode_wrapped(struct ldap_connection *conn, DATA_BLOB blob)
-{
-       DATA_BLOB wrapped, unwrapped;
-       struct asn1_data asn1;
-       struct ldap_message *msg = talloc(conn, struct ldap_message);
-       NTSTATUS status;
-
-       if (msg == NULL) {
-               return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
-       }
-
-       wrapped = data_blob_const(blob.data+4, blob.length-4);
-
-       status = gensec_unwrap(conn->gensec, msg, &wrapped, &unwrapped);
-       if (!NT_STATUS_IS_OK(status)) {
-               return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
-       }
-
-       data_blob_free(&blob);
-
-       if (!asn1_load(&asn1, unwrapped)) {
-               return NT_STATUS_LDAP(LDAP_PROTOCOL_ERROR);
-       }
-
-       while (ldap_decode(&asn1, msg)) {
-               ldap_match_message(conn, msg);
-               msg = talloc(conn, struct ldap_message);
-       }
-               
-       talloc_free(msg);
-       asn1_free(&asn1);
-
+       asn1_free(asn1);
        return NT_STATUS_OK;
 }
 
-
-/*
-  handle ldap recv events
-*/
-static NTSTATUS ldap_recv_handler(void *private, DATA_BLOB blob)
+/* Handle read events, from the GENSEC socket callback, or real events */
+void ldap_read_io_handler(void *private_data, uint16_t flags) 
 {
-       struct ldap_connection *conn = talloc_get_type(private, 
+       struct ldap_connection *conn = talloc_get_type(private_data
                                                       struct ldap_connection);
-       if (conn->enable_wrap) {
-               return ldap_decode_wrapped(conn, blob);
-       }
-
-       return ldap_decode_plain(conn, blob);
+       packet_recv(conn->packet);
 }
 
-
 /*
   handle ldap socket events
 */
 static void ldap_io_handler(struct event_context *ev, struct fd_event *fde, 
-                           uint16_t flags, void *private)
+                           uint16_t flags, void *private_data)
 {
-       struct ldap_connection *conn = talloc_get_type(private, 
+       struct ldap_connection *conn = talloc_get_type(private_data
                                                       struct ldap_connection);
        if (flags & EVENT_FD_WRITE) {
                packet_queue_run(conn->packet);
-               if (conn->tls == NULL) return;
+               if (!tls_enabled(conn->sock)) return;
        }
        if (flags & EVENT_FD_READ) {
-               packet_recv(conn->packet);
+               ldap_read_io_handler(private_data, flags);
        }
 }
 
@@ -267,33 +245,27 @@ static void ldap_io_handler(struct event_context *ev, struct fd_event *fde,
   parse a ldap URL
 */
 static NTSTATUS ldap_parse_basic_url(TALLOC_CTX *mem_ctx, const char *url,
-                                    char **host, uint16_t *port, BOOL *ldaps)
+                                    char **host, uint16_t *port, bool *ldaps)
 {
        int tmp_port = 0;
        char protocol[11];
-       char tmp_host[255];
-       const char *p = url;
+       char tmp_host[1025];
        int ret;
 
-       /* skip leading "URL:" (if any) */
-       if (strncasecmp(p, "URL:", 4) == 0) {
-               p += 4;
-       }
-
        /* Paranoia check */
        SMB_ASSERT(sizeof(protocol)>10 && sizeof(tmp_host)>254);
                
-       ret = sscanf(p, "%10[^:]://%254[^:/]:%d", protocol, tmp_host, &tmp_port);
+       ret = sscanf(url, "%10[^:]://%254[^:/]:%d", protocol, tmp_host, &tmp_port);
        if (ret < 2) {
                return NT_STATUS_INVALID_PARAMETER;
        }
 
        if (strequal(protocol, "ldap")) {
                *port = 389;
-               *ldaps = False;
+               *ldaps = false;
        } else if (strequal(protocol, "ldaps")) {
                *port = 636;
-               *ldaps = True;
+               *ldaps = true;
        } else {
                DEBUG(0, ("unrecognised ldap protocol (%s)!\n", protocol));
                return NT_STATUS_PROTOCOL_UNREACHABLE;
@@ -317,13 +289,16 @@ struct ldap_connect_state {
        struct ldap_connection *conn;
 };
 
-static void ldap_connect_recv_conn(struct composite_context *ctx);
+static void ldap_connect_recv_unix_conn(struct composite_context *ctx);
+static void ldap_connect_recv_tcp_conn(struct composite_context *ctx);
 
 struct composite_context *ldap_connect_send(struct ldap_connection *conn,
                                            const char *url)
 {
        struct composite_context *result, *ctx;
        struct ldap_connect_state *state;
+       char protocol[11];
+       int ret;
 
        result = talloc_zero(NULL, struct composite_context);
        if (result == NULL) goto failed;
@@ -338,74 +313,162 @@ struct composite_context *ldap_connect_send(struct ldap_connection *conn,
 
        state->conn = conn;
 
-       state->ctx->status = ldap_parse_basic_url(conn, url, &conn->host,
-                                                 &conn->port, &conn->ldaps);
-       if (!NT_STATUS_IS_OK(state->ctx->status)) {
-               composite_trigger_error(state->ctx);
-               return result;
+       if (conn->reconnect.url == NULL) {
+               conn->reconnect.url = talloc_strdup(conn, url);
+               if (conn->reconnect.url == NULL) goto failed;
+       }
+
+       /* Paranoia check */
+       SMB_ASSERT(sizeof(protocol)>10);
+
+       ret = sscanf(url, "%10[^:]://", protocol);
+       if (ret < 1) {
+               return NULL;
        }
 
-       ctx = socket_connect_multi_send(state, conn->host, 1, &conn->port,
-                                       conn->event.event_ctx);
-       if (ctx == NULL) goto failed;
+       if (strequal(protocol, "ldapi")) {
+               struct socket_address *unix_addr;
+               char path[1025];
+       
+               NTSTATUS status = socket_create("unix", SOCKET_TYPE_STREAM, &conn->sock, 0);
+               if (!NT_STATUS_IS_OK(status)) {
+                       return NULL;
+               }
+               talloc_steal(conn, conn->sock);
+               SMB_ASSERT(sizeof(protocol)>10);
+               SMB_ASSERT(sizeof(path)>1024);
+       
+               /* The %c specifier doesn't null terminate :-( */
+               ZERO_STRUCT(path);
+               ret = sscanf(url, "%10[^:]://%1025c", protocol, path);
+               if (ret < 2) {
+                       composite_error(state->ctx, NT_STATUS_INVALID_PARAMETER);
+                       return result;
+               }
+
+               rfc1738_unescape(path);
+       
+               unix_addr = socket_address_from_strings(conn, conn->sock->backend_name, 
+                                                       path, 0);
+               if (!unix_addr) {
+                       return NULL;
+               }
 
-       ctx->async.fn = ldap_connect_recv_conn;
-       ctx->async.private_data = state;
-       return result;
+               ctx = socket_connect_send(conn->sock, NULL, unix_addr, 
+                                         0, lp_name_resolve_order(conn->lp_ctx), conn->event.event_ctx);
+               ctx->async.fn = ldap_connect_recv_unix_conn;
+               ctx->async.private_data = state;
+               return result;
+       } else {
+               NTSTATUS status = ldap_parse_basic_url(conn, url, &conn->host,
+                                                         &conn->port, &conn->ldaps);
+               if (!NT_STATUS_IS_OK(state->ctx->status)) {
+                       composite_error(state->ctx, status);
+                       return result;
+               }
+               
+               ctx = socket_connect_multi_send(state, conn->host, 1, &conn->port,
+                                               lp_name_resolve_order(conn->lp_ctx), conn->event.event_ctx);
+               if (ctx == NULL) goto failed;
 
+               ctx->async.fn = ldap_connect_recv_tcp_conn;
+               ctx->async.private_data = state;
+               return result;
+       }
  failed:
        talloc_free(result);
        return NULL;
 }
 
-static void ldap_connect_recv_conn(struct composite_context *ctx)
+static void ldap_connect_got_sock(struct composite_context *ctx, 
+                                 struct ldap_connection *conn) 
 {
-       struct ldap_connect_state *state =
-               talloc_get_type(ctx->async.private_data,
-                               struct ldap_connect_state);
-       struct ldap_connection *conn = state->conn;
-       uint16_t port;
-
-       state->ctx->status = socket_connect_multi_recv(ctx, state, &conn->sock,
-                                                      &port);
-       if (!composite_is_ok(state->ctx)) return;
-
        /* setup a handler for events on this socket */
        conn->event.fde = event_add_fd(conn->event.event_ctx, conn->sock, 
                                       socket_get_fd(conn->sock), 
-                                      EVENT_FD_READ, ldap_io_handler, conn);
+                                      EVENT_FD_READ | EVENT_FD_AUTOCLOSE, ldap_io_handler, conn);
        if (conn->event.fde == NULL) {
-               composite_error(state->ctx, NT_STATUS_INTERNAL_ERROR);
+               composite_error(ctx, NT_STATUS_INTERNAL_ERROR);
                return;
        }
 
-       conn->tls = tls_init_client(conn->sock, conn->event.fde, conn->ldaps);
-       if (conn->tls == NULL) {
-               talloc_free(conn->sock);
-               return;
+       socket_set_flags(conn->sock, SOCKET_FLAG_NOCLOSE);
+
+       talloc_steal(conn, conn->sock);
+       if (conn->ldaps) {
+               struct socket_context *tls_socket;
+               char *cafile = private_path(conn->sock, conn->lp_ctx, lp_tls_cafile(conn->lp_ctx));
+
+               if (!cafile || !*cafile) {
+                       talloc_free(conn->sock);
+                       return;
+               }
+
+               tls_socket = tls_init_client(conn->sock, conn->event.fde, cafile);
+               talloc_free(cafile);
+
+               if (tls_socket == NULL) {
+                       talloc_free(conn->sock);
+                       return;
+               }
+               talloc_unlink(conn, conn->sock);
+               conn->sock = tls_socket;
+               talloc_steal(conn, conn->sock);
        }
-       talloc_steal(conn, conn->tls);
-       talloc_steal(conn->tls, conn->sock);
 
        conn->packet = packet_init(conn);
        if (conn->packet == NULL) {
                talloc_free(conn->sock);
                return;
        }
+
        packet_set_private(conn->packet, conn);
-       packet_set_tls(conn->packet, conn->tls);
+       packet_set_socket(conn->packet, conn->sock);
        packet_set_callback(conn->packet, ldap_recv_handler);
-       packet_set_full_request(conn->packet, ldap_complete_packet);
+       packet_set_full_request(conn->packet, ldap_full_packet);
        packet_set_error_handler(conn->packet, ldap_error_handler);
        packet_set_event_context(conn->packet, conn->event.event_ctx);
-       packet_set_serialise(conn->packet, conn->event.fde);
+       packet_set_fde(conn->packet, conn->event.fde);
+       packet_set_serialise(conn->packet);
+
+       composite_done(ctx);
+}
+
+static void ldap_connect_recv_tcp_conn(struct composite_context *ctx)
+{
+       struct ldap_connect_state *state =
+               talloc_get_type(ctx->async.private_data,
+                               struct ldap_connect_state);
+       struct ldap_connection *conn = state->conn;
+       uint16_t port;
+       NTSTATUS status = socket_connect_multi_recv(ctx, state, &conn->sock,
+                                                      &port);
+       if (!NT_STATUS_IS_OK(status)) {
+               composite_error(state->ctx, status);
+               return;
+       }
+
+       ldap_connect_got_sock(state->ctx, conn);
+}
+
+static void ldap_connect_recv_unix_conn(struct composite_context *ctx)
+{
+       struct ldap_connect_state *state =
+               talloc_get_type(ctx->async.private_data,
+                               struct ldap_connect_state);
+       struct ldap_connection *conn = state->conn;
 
-       composite_done(state->ctx);
+       NTSTATUS status = socket_connect_recv(ctx);
 
-       return;
+       if (!NT_STATUS_IS_OK(state->ctx->status)) {
+               composite_error(state->ctx, status);
+               return;
+       }
+
+       ldap_connect_got_sock(state->ctx, conn);
 }
 
-NTSTATUS ldap_connect_recv(struct composite_context *ctx)
+_PUBLIC_ NTSTATUS ldap_connect_recv(struct composite_context *ctx)
 {
        NTSTATUS status = composite_wait(ctx);
        talloc_free(ctx);
@@ -418,10 +481,54 @@ NTSTATUS ldap_connect(struct ldap_connection *conn, const char *url)
        return ldap_connect_recv(ctx);
 }
 
+/* set reconnect parameters */
+
+void ldap_set_reconn_params(struct ldap_connection *conn, int max_retries)
+{
+       if (conn) {
+               conn->reconnect.max_retries = max_retries;
+               conn->reconnect.retries = 0;
+               conn->reconnect.previous = time(NULL);
+       }
+}
+
+/* Actually this function is NOT ASYNC safe, FIXME? */
+static void ldap_reconnect(struct ldap_connection *conn)
+{
+       NTSTATUS status;
+       time_t now = time(NULL);
+
+       /* do we have set up reconnect ? */
+       if (conn->reconnect.max_retries == 0) return;
+
+       /* is the retry time expired ? */
+       if (now > conn->reconnect.previous + 30) {
+               conn->reconnect.retries = 0;
+               conn->reconnect.previous = now;
+       }
+
+       /* are we reconnectind too often and too fast? */
+       if (conn->reconnect.retries > conn->reconnect.max_retries) return;
+
+       /* keep track of the number of reconnections */
+       conn->reconnect.retries++;
+
+       /* reconnect */
+       status = ldap_connect(conn, conn->reconnect.url);
+       if ( ! NT_STATUS_IS_OK(status)) {
+               return;
+       }
+
+       /* rebind */
+       status = ldap_rebind(conn);
+       if ( ! NT_STATUS_IS_OK(status)) {
+               ldap_connection_dead(conn);
+       }
+}
+
 /* destroy an open ldap request */
-static int ldap_request_destructor(void *ptr)
+static int ldap_request_destructor(struct ldap_request *req)
 {
-       struct ldap_request *req = talloc_get_type(ptr, struct ldap_request);
        if (req->state == LDAP_REQUEST_PENDING) {
                DLIST_REMOVE(req->conn->pending, req);
        }
@@ -432,9 +539,9 @@ static int ldap_request_destructor(void *ptr)
   called on timeout of a ldap request
 */
 static void ldap_request_timeout(struct event_context *ev, struct timed_event *te, 
-                                     struct timeval t, void *private)
+                                     struct timeval t, void *private_data)
 {
-       struct ldap_request *req = talloc_get_type(private, struct ldap_request);
+       struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
        req->status = NT_STATUS_IO_TIMEOUT;
        if (req->state == LDAP_REQUEST_PENDING) {
                DLIST_REMOVE(req->conn->pending, req);
@@ -450,9 +557,9 @@ static void ldap_request_timeout(struct event_context *ev, struct timed_event *t
   called on completion of a one-way ldap request
 */
 static void ldap_request_complete(struct event_context *ev, struct timed_event *te, 
-                                 struct timeval t, void *private)
+                                 struct timeval t, void *private_data)
 {
-       struct ldap_request *req = talloc_get_type(private, struct ldap_request);
+       struct ldap_request *req = talloc_get_type(private_data, struct ldap_request);
        if (req->async.fn) {
                req->async.fn(req);
        }
@@ -465,14 +572,15 @@ struct ldap_request *ldap_request_send(struct ldap_connection *conn,
                                       struct ldap_message *msg)
 {
        struct ldap_request *req;
-       NTSTATUS status;
-
-       if (conn->tls == NULL) {
-               return NULL;
-       }
+       NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
 
        req = talloc_zero(conn, struct ldap_request);
-       if (req == NULL) goto failed;
+       if (req == NULL) return NULL;
+
+       if (conn->sock == NULL) {
+               status = NT_STATUS_INVALID_CONNECTION;
+               goto failed;
+       }
 
        req->state       = LDAP_REQUEST_SEND;
        req->conn        = conn;
@@ -490,27 +598,10 @@ struct ldap_request *ldap_request_send(struct ldap_connection *conn,
        msg->messageid = req->messageid;
 
        if (!ldap_encode(msg, &req->data, req)) {
+               status = NT_STATUS_INTERNAL_ERROR;
                goto failed;            
        }
 
-       /* possibly encrypt/sign the request */
-       if (conn->enable_wrap) {
-               DATA_BLOB wrapped;
-
-               status = gensec_wrap(conn->gensec, req, &req->data, &wrapped);
-               if (!NT_STATUS_IS_OK(status)) {
-                       goto failed;
-               }
-               data_blob_free(&req->data);
-               req->data = data_blob_talloc(req, NULL, wrapped.length + 4);
-               if (req->data.data == NULL) {
-                       goto failed;
-               }
-               RSIVAL(req->data.data, 0, wrapped.length);
-               memcpy(req->data.data+4, wrapped.data, wrapped.length);
-               data_blob_free(&wrapped);
-       }
-
        status = packet_send(conn->packet, req->data);
        if (!NT_STATUS_IS_OK(status)) {
                goto failed;
@@ -533,15 +624,19 @@ struct ldap_request *ldap_request_send(struct ldap_connection *conn,
        DLIST_ADD(conn->pending, req);
 
        /* put a timeout on the request */
-       event_add_timed(conn->event.event_ctx, req, 
-                       timeval_current_ofs(conn->timeout, 0),
-                       ldap_request_timeout, req);
+       req->time_event = event_add_timed(conn->event.event_ctx, req, 
+                                         timeval_current_ofs(conn->timeout, 0),
+                                         ldap_request_timeout, req);
 
        return req;
 
 failed:
-       talloc_free(req);
-       return NULL;
+       req->status = status;
+       req->state = LDAP_REQUEST_ERROR;
+       event_add_timed(conn->event.event_ctx, req, timeval_zero(),
+                       ldap_request_complete, req);
+
+       return req;
 }
 
 
@@ -551,7 +646,7 @@ failed:
 */
 NTSTATUS ldap_request_wait(struct ldap_request *req)
 {
-       while (req->state != LDAP_REQUEST_DONE) {
+       while (req->state < LDAP_REQUEST_DONE) {
                if (event_loop_once(req->conn->event.event_ctx) != 0) {
                        req->status = NT_STATUS_UNEXPECTED_NETWORK_ERROR;
                        break;
@@ -595,7 +690,7 @@ static const struct {
        _LDAP_MAP_CODE(LDAP_ALIAS_DEREFERENCING_PROBLEM),
        _LDAP_MAP_CODE(LDAP_INAPPROPRIATE_AUTHENTICATION),
        _LDAP_MAP_CODE(LDAP_INVALID_CREDENTIALS),
-       _LDAP_MAP_CODE(LDAP_INSUFFICIENT_ACCESS_RIGHTs),
+       _LDAP_MAP_CODE(LDAP_INSUFFICIENT_ACCESS_RIGHTS),
        _LDAP_MAP_CODE(LDAP_BUSY),
        _LDAP_MAP_CODE(LDAP_UNAVAILABLE),
        _LDAP_MAP_CODE(LDAP_UNWILLING_TO_PERFORM),
@@ -646,12 +741,14 @@ NTSTATUS ldap_check_response(struct ldap_connection *conn, struct ldap_Result *r
 /*
   return error string representing the last error
 */
-const char *ldap_errstr(struct ldap_connection *conn, NTSTATUS status)
+const char *ldap_errstr(struct ldap_connection *conn, 
+                       TALLOC_CTX *mem_ctx, 
+                       NTSTATUS status)
 {
        if (NT_STATUS_IS_LDAP(status) && conn->last_error != NULL) {
-               return conn->last_error;
+               return talloc_strdup(mem_ctx, conn->last_error);
        }
-       return nt_errstr(status);
+       return talloc_asprintf(mem_ctx, "LDAP client internal error: %s", nt_errstr(status));
 }
 
 
@@ -664,7 +761,7 @@ NTSTATUS ldap_result_n(struct ldap_request *req, int n, struct ldap_message **ms
 
        NT_STATUS_HAVE_NO_MEMORY(req);
 
-       while (req->state != LDAP_REQUEST_DONE && n >= req->num_replies) {
+       while (req->state < LDAP_REQUEST_DONE && n >= req->num_replies) {
                if (event_loop_once(req->conn->event.event_ctx) != 0) {
                        return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
                }