tldap talloc_realloc
[metze/samba/wip.git] / source3 / lib / tldap.c
index 2033b4fa593da44dc989d0fd5e928cb145dca5f5..d039f9548af8f83958694fc165a61509609011f7 100644 (file)
 */
 
 #include "includes.h"
+#include "tldap.h"
+#include "../lib/util/asn1.h"
+#include "../lib/tsocket/tsocket.h"
+#include "../lib/util/tevent_unix.h"
+
+static int tldap_simple_recv(struct tevent_req *req);
 
 bool tevent_req_is_ldap_error(struct tevent_req *req, int *perr)
 {
@@ -54,17 +60,14 @@ struct tldap_context {
        int ld_deref;
        int ld_sizelimit;
        int ld_timelimit;
-       int fd;
+       struct tstream_context *conn;
+       bool server_down;
        int msgid;
        struct tevent_queue *outgoing;
        struct tevent_req **pending;
 
        /* For the sync wrappers we need something like get_last_error... */
-       int lderr;
-       char *res_matcheddn;
-       char *res_diagnosticmessage;
-       char *res_referral;
-       struct tldap_control *res_sctrls;
+       struct tldap_message *last_msg;
 
        /* debug */
        void (*log_fn)(void *context, enum tldap_debug_level level,
@@ -83,6 +86,16 @@ struct tldap_message {
        /* RESULT_ENTRY */
        char *dn;
        struct tldap_attribute *attribs;
+
+       /* Error data sent by the server */
+       int lderr;
+       char *res_matcheddn;
+       char *res_diagnosticmessage;
+       char *res_referral;
+       struct tldap_control *res_sctrls;
+
+       /* Controls sent by the server */
+       struct tldap_control *ctrls;
 };
 
 void tldap_set_debug(struct tldap_context *ld,
@@ -126,12 +139,17 @@ static int tldap_next_msgid(struct tldap_context *ld)
 struct tldap_context *tldap_context_create(TALLOC_CTX *mem_ctx, int fd)
 {
        struct tldap_context *ctx;
+       int ret;
 
        ctx = talloc_zero(mem_ctx, struct tldap_context);
        if (ctx == NULL) {
                return NULL;
        }
-       ctx->fd = fd;
+       ret = tstream_bsd_existing_socket(ctx, fd, &ctx->conn);
+       if (ret == -1) {
+               TALLOC_FREE(ctx);
+               return NULL;
+       }
        ctx->msgid = 1;
        ctx->ld_version = 3;
        ctx->outgoing = tevent_queue_create(ctx, "tldap_outgoing");
@@ -142,6 +160,14 @@ struct tldap_context *tldap_context_create(TALLOC_CTX *mem_ctx, int fd)
        return ctx;
 }
 
+bool tldap_connection_ok(struct tldap_context *ld)
+{
+       if (ld == NULL) {
+               return false;
+       }
+       return !ld->server_down;
+}
+
 static struct tldap_ctx_attribute *tldap_context_findattr(
        struct tldap_context *ld, const char *name)
 {
@@ -163,7 +189,7 @@ bool tldap_context_setattr(struct tldap_context *ld,
        struct tldap_ctx_attribute *tmp, *attr;
        char *tmpname;
        int num_attrs;
-       void **pptr = (void **)_pptr;
+       void **pptr = (void **)discard_const_p(void,_pptr);
 
        attr = tldap_context_findattr(ld, name);
        if (attr != NULL) {
@@ -218,6 +244,31 @@ struct read_ldap_state {
        bool done;
 };
 
+static ssize_t read_ldap_more(uint8_t *buf, size_t buflen, void *private_data);
+static void read_ldap_done(struct tevent_req *subreq);
+
+static struct tevent_req *read_ldap_send(TALLOC_CTX *mem_ctx,
+                                        struct tevent_context *ev,
+                                        struct tstream_context *conn)
+{
+       struct tevent_req *req, *subreq;
+       struct read_ldap_state *state;
+
+       req = tevent_req_create(mem_ctx, &state, struct read_ldap_state);
+       if (req == NULL) {
+               return NULL;
+       }
+       state->done = false;
+
+       subreq = tstream_read_packet_send(state, ev, conn, 2, read_ldap_more,
+                                         state);
+       if (tevent_req_nomem(subreq, req)) {
+               return tevent_req_post(req, ev);
+       }
+       tevent_req_set_callback(subreq, read_ldap_done, req);
+       return req;
+}
+
 static ssize_t read_ldap_more(uint8_t *buf, size_t buflen, void *private_data)
 {
        struct read_ldap_state *state = talloc_get_type_abort(
@@ -264,29 +315,6 @@ static ssize_t read_ldap_more(uint8_t *buf, size_t buflen, void *private_data)
        return len;
 }
 
-static void read_ldap_done(struct tevent_req *subreq);
-
-static struct tevent_req *read_ldap_send(TALLOC_CTX *mem_ctx,
-                                        struct tevent_context *ev,
-                                        int fd)
-{
-       struct tevent_req *req, *subreq;
-       struct read_ldap_state *state;
-
-       req = tevent_req_create(mem_ctx, &state, struct read_ldap_state);
-       if (req == NULL) {
-               return NULL;
-       }
-       state->done = false;
-
-       subreq = read_packet_send(state, ev, fd, 2, read_ldap_more, state);
-       if (tevent_req_nomem(subreq, req)) {
-               return tevent_req_post(req, ev);
-       }
-       tevent_req_set_callback(subreq, read_ldap_done, req);
-       return req;
-}
-
 static void read_ldap_done(struct tevent_req *subreq)
 {
        struct tevent_req *req = tevent_req_callback_data(
@@ -296,7 +324,7 @@ static void read_ldap_done(struct tevent_req *subreq)
        ssize_t nread;
        int err;
 
-       nread = read_packet_recv(subreq, state, &state->buf, &err);
+       nread = tstream_read_packet_recv(subreq, state, &state->buf, &err);
        TALLOC_FREE(subreq);
        if (nread == -1) {
                tevent_req_error(req, err);
@@ -382,6 +410,11 @@ static struct tevent_req *tldap_msg_send(TALLOC_CTX *mem_ctx,
        state->ev = ev;
        state->id = id;
 
+       if (state->ld->server_down) {
+               tevent_req_error(req, TLDAP_SERVER_DOWN);
+               return tevent_req_post(req, ev);
+       }
+
        tldap_push_controls(data, sctrls, num_sctrls);
 
        asn1_pop_tag(data);
@@ -391,11 +424,11 @@ static struct tevent_req *tldap_msg_send(TALLOC_CTX *mem_ctx,
                return tevent_req_post(req, ev);
        }
 
-       state->iov.iov_base = blob.data;
+       state->iov.iov_base = (void *)blob.data;
        state->iov.iov_len = blob.length;
 
-       subreq = writev_send(state, ev, ld->outgoing, ld->fd, false,
-                            &state->iov, 1);
+       subreq = tstream_writev_queue_send(state, ev, ld->conn, ld->outgoing,
+                                          &state->iov, 1);
        if (tevent_req_nomem(subreq, req)) {
                return tevent_req_post(req, ev);
        }
@@ -441,7 +474,7 @@ static void tldap_msg_unset_pending(struct tevent_req *req)
         * No NULL check here, we're shrinking by sizeof(void *), and
         * talloc_realloc just adjusts the size for this.
         */
-       ld->pending = talloc_realloc(NULL, ld->pending, struct tevent_req *,
+       ld->pending = talloc_realloc(ld, ld->pending, struct tevent_req *,
                                     num_pending - 1);
        return;
 }
@@ -478,10 +511,10 @@ static bool tldap_msg_set_pending(struct tevent_req *req)
        }
 
        /*
-        * We're the first ones, add the read_ldap request that waits for the
+        * We're the first one, add the read_ldap request that waits for the
         * answer from the server
         */
-       subreq = read_ldap_send(ld->pending, state->ev, ld->fd);
+       subreq = read_ldap_send(ld->pending, state->ev, ld->conn);
        if (subreq == NULL) {
                tldap_msg_unset_pending(req);
                return false;
@@ -494,18 +527,21 @@ static void tldap_msg_sent(struct tevent_req *subreq)
 {
        struct tevent_req *req = tevent_req_callback_data(
                subreq, struct tevent_req);
+       struct tldap_msg_state *state = tevent_req_data(
+               req, struct tldap_msg_state);
        ssize_t nwritten;
        int err;
 
-       nwritten = writev_recv(subreq, &err);
+       nwritten = tstream_writev_queue_recv(subreq, &err);
        TALLOC_FREE(subreq);
        if (nwritten == -1) {
+               state->ld->server_down = true;
                tevent_req_error(req, TLDAP_SERVER_DOWN);
                return;
        }
 
        if (!tldap_msg_set_pending(req)) {
-               tevent_req_nomem(NULL, req);
+               tevent_req_oom(req);
                return;
        }
 }
@@ -524,7 +560,6 @@ static void tldap_msg_received(struct tevent_req *subreq)
                subreq, struct tldap_context);
        struct tevent_req *req;
        struct tldap_msg_state *state;
-       struct tevent_context *ev;
        struct asn1_data *data;
        uint8_t *inbuf;
        ssize_t received;
@@ -572,6 +607,7 @@ static void tldap_msg_received(struct tevent_req *subreq)
                /* Dump unexpected reply */
                tldap_debug(ld, TLDAP_DEBUG_WARNING, "tldap_msg_received: "
                            "No request pending for msg %d\n", id);
+               TALLOC_FREE(data);
                TALLOC_FREE(inbuf);
                goto done;
        }
@@ -582,23 +618,33 @@ static void tldap_msg_received(struct tevent_req *subreq)
        state->inbuf = talloc_move(state, &inbuf);
        state->data = talloc_move(state, &data);
 
-       ev = state->ev;
-
        talloc_set_destructor(req, NULL);
-       tldap_msg_destructor(req);
+       tldap_msg_unset_pending(req);
+       num_pending = talloc_array_length(ld->pending);
+
        tevent_req_done(req);
 
  done:
-       if (talloc_array_length(ld->pending) > 0) {
-               state = tevent_req_data(ld->pending[0],
-                                       struct tldap_msg_state);
-               subreq = read_ldap_send(ld->pending, state->ev, ld->fd);
-               if (subreq == NULL) {
-                       status = TLDAP_NO_MEMORY;
-                       goto fail;
-               }
-               tevent_req_set_callback(subreq, tldap_msg_received, ld);
+       if (num_pending == 0) {
+               return;
+       }
+       if (talloc_array_length(ld->pending) > num_pending) {
+               /*
+                * The callback functions called from tevent_req_done() above
+                * have put something on the pending queue. We don't have to
+                * trigger the read_ldap_send(), tldap_msg_set_pending() has
+                * done it for us already.
+                */
+               return;
+       }
+
+       state = tevent_req_data(ld->pending[0], struct tldap_msg_state);
+       subreq = read_ldap_send(ld->pending, state->ev, ld->conn);
+       if (subreq == NULL) {
+               status = TLDAP_NO_MEMORY;
+               goto fail;
        }
+       tevent_req_set_callback(subreq, tldap_msg_received, ld);
        return;
 
  fail:
@@ -649,12 +695,6 @@ struct tldap_req_state {
        int id;
        struct asn1_data *out;
        struct tldap_message *result;
-
-       int lderr;
-       char *res_matcheddn;
-       char *res_diagnosticmessage;
-       char *res_referral;
-       struct tldap_control *res_sctrls;
 };
 
 static struct tevent_req *tldap_req_create(TALLOC_CTX *mem_ctx,
@@ -684,28 +724,23 @@ static struct tevent_req *tldap_req_create(TALLOC_CTX *mem_ctx,
        return req;
 }
 
-static void tldap_save_errors(struct tldap_context *ctx,
-                             struct tevent_req *req)
+static void tldap_save_msg(struct tldap_context *ld, struct tevent_req *req)
 {
        struct tldap_req_state *state = tevent_req_data(
                req, struct tldap_req_state);
 
-       TALLOC_FREE(ctx->res_matcheddn);
-       TALLOC_FREE(ctx->res_diagnosticmessage);
-       TALLOC_FREE(ctx->res_referral);
-       TALLOC_FREE(ctx->res_sctrls);
-
-       ctx->lderr = state->lderr;
-       ctx->res_matcheddn = talloc_move(ctx, &state->res_matcheddn);
-       ctx->res_diagnosticmessage = talloc_move(
-               ctx, &state->res_diagnosticmessage);
-       ctx->res_referral = talloc_move(ctx, &state->res_referral);
-       ctx->res_sctrls = talloc_move(ctx, &state->res_sctrls);
+       TALLOC_FREE(ld->last_msg);
+       ld->last_msg = talloc_move(ld, &state->result);
 }
 
 static char *blob2string_talloc(TALLOC_CTX *mem_ctx, DATA_BLOB blob)
 {
        char *result = talloc_array(mem_ctx, char, blob.length+1);
+
+       if (result == NULL) {
+               return NULL;
+       }
+
        memcpy(result, blob.data, blob.length);
        result[blob.length] = '\0';
        return result;
@@ -713,32 +748,43 @@ static char *blob2string_talloc(TALLOC_CTX *mem_ctx, DATA_BLOB blob)
 
 static bool asn1_read_OctetString_talloc(TALLOC_CTX *mem_ctx,
                                         struct asn1_data *data,
-                                        char **result)
+                                        char **presult)
 {
        DATA_BLOB string;
+       char *result;
        if (!asn1_read_OctetString(data, mem_ctx, &string))
                return false;
-       *result = blob2string_talloc(mem_ctx, string);
+
+       result = blob2string_talloc(mem_ctx, string);
+
        data_blob_free(&string);
+
+       if (result == NULL) {
+               return false;
+       }
+       *presult = result;
        return true;
 }
 
+static bool tldap_decode_controls(struct tldap_req_state *state);
+
 static bool tldap_decode_response(struct tldap_req_state *state)
 {
        struct asn1_data *data = state->result->data;
+       struct tldap_message *msg = state->result;
        bool ok = true;
 
-       ok &= asn1_read_enumerated(data, &state->lderr);
-       ok &= asn1_read_OctetString_talloc(state, data, &state->res_matcheddn);
-       ok &= asn1_read_OctetString_talloc(state, data,
-                                          &state->res_diagnosticmessage);
+       ok &= asn1_read_enumerated(data, &msg->lderr);
+       ok &= asn1_read_OctetString_talloc(msg, data, &msg->res_matcheddn);
+       ok &= asn1_read_OctetString_talloc(msg, data,
+                                          &msg->res_diagnosticmessage);
        if (asn1_peek_tag(data, ASN1_CONTEXT(3))) {
                ok &= asn1_start_tag(data, ASN1_CONTEXT(3));
-               ok &= asn1_read_OctetString_talloc(
-                       state, data, &state->res_referral);
+               ok &= asn1_read_OctetString_talloc(msg, data,
+                                                  &msg->res_referral);
                ok &= asn1_end_tag(data);
        } else {
-               state->res_referral = NULL;
+               msg->res_referral = NULL;
        }
 
        return ok;
@@ -829,8 +875,8 @@ static void tldap_sasl_bind_done(struct tevent_req *subreq)
        /*
         * TODO: pull the reply blob
         */
-       if (state->lderr != TLDAP_SUCCESS) {
-               tevent_req_error(req, state->lderr);
+       if (state->result->lderr != TLDAP_SUCCESS) {
+               tevent_req_error(req, state->result->lderr);
                return;
        }
        tevent_req_done(req);
@@ -838,12 +884,7 @@ static void tldap_sasl_bind_done(struct tevent_req *subreq)
 
 int tldap_sasl_bind_recv(struct tevent_req *req)
 {
-       int err;
-
-       if (tevent_req_is_ldap_error(req, &err)) {
-               return err;
-       }
-       return TLDAP_SUCCESS;
+       return tldap_simple_recv(req);
 }
 
 int tldap_sasl_bind(struct tldap_context *ld,
@@ -879,7 +920,7 @@ int tldap_sasl_bind(struct tldap_context *ld,
        }
 
        result = tldap_sasl_bind_recv(req);
-       tldap_save_errors(ld, req);
+       tldap_save_msg(ld, req);
  fail:
        TALLOC_FREE(frame);
        return result;
@@ -894,10 +935,10 @@ struct tevent_req *tldap_simple_bind_send(TALLOC_CTX *mem_ctx,
        DATA_BLOB cred;
 
        if (passwd != NULL) {
-               cred.data = (uint8_t *)passwd;
+               cred.data = discard_const_p(uint8_t, passwd);
                cred.length = strlen(passwd);
        } else {
-               cred.data = (uint8_t *)"";
+               cred.data = discard_const_p(uint8_t, "");
                cred.length = 0;
        }
        return tldap_sasl_bind_send(mem_ctx, ev, ld, dn, NULL, &cred, NULL, 0,
@@ -915,10 +956,10 @@ int tldap_simple_bind(struct tldap_context *ld, const char *dn,
        DATA_BLOB cred;
 
        if (passwd != NULL) {
-               cred.data = (uint8_t *)passwd;
+               cred.data = discard_const_p(uint8_t, passwd);
                cred.length = strlen(passwd);
        } else {
-               cred.data = (uint8_t *)"";
+               cred.data = discard_const_p(uint8_t, "");
                cred.length = 0;
        }
        return tldap_sasl_bind(ld, dn, NULL, &cred, NULL, 0, NULL, 0);
@@ -926,175 +967,661 @@ int tldap_simple_bind(struct tldap_context *ld, const char *dn,
 
 /*****************************************************************************/
 
-/*
- * This piece has a dependency on ldb, the ldb_parse_tree() function is used.
- * In case we want to separate out tldap, we need to copy or rewrite it.
- */
+/* can't use isalpha() as only a strict set is valid for LDAP */
+
+static bool tldap_is_alpha(char c)
+{
+       return (((c >= 'a') && (c <= 'z')) || \
+               ((c >= 'A') && (c <= 'Z')));
+}
+
+static bool tldap_is_adh(char c)
+{
+       return tldap_is_alpha(c) || isdigit(c) || (c == '-');
+}
+
+#define TLDAP_FILTER_AND  ASN1_CONTEXT(0)
+#define TLDAP_FILTER_OR   ASN1_CONTEXT(1)
+#define TLDAP_FILTER_NOT  ASN1_CONTEXT(2)
+#define TLDAP_FILTER_EQ   ASN1_CONTEXT(3)
+#define TLDAP_FILTER_SUB  ASN1_CONTEXT(4)
+#define TLDAP_FILTER_LE   ASN1_CONTEXT(5)
+#define TLDAP_FILTER_GE   ASN1_CONTEXT(6)
+#define TLDAP_FILTER_PRES ASN1_CONTEXT_SIMPLE(7)
+#define TLDAP_FILTER_APX  ASN1_CONTEXT(8)
+#define TLDAP_FILTER_EXT  ASN1_CONTEXT(9)
 
-#include "lib/ldb/include/ldb.h"
-#include "lib/ldb/include/ldb_errors.h"
+#define TLDAP_SUB_INI ASN1_CONTEXT_SIMPLE(0)
+#define TLDAP_SUB_ANY ASN1_CONTEXT_SIMPLE(1)
+#define TLDAP_SUB_FIN ASN1_CONTEXT_SIMPLE(2)
 
-static bool ldap_push_filter(struct asn1_data *data,
-                            struct ldb_parse_tree *tree)
+
+/* oid's should be numerical only in theory,
+ * but apparently some broken servers may have alphanum aliases instead.
+ * Do like openldap libraries and allow alphanum aliases for oids, but
+ * do not allow Tagging options in that case.
+ */
+static bool tldap_is_attrdesc(const char *s, int len, bool no_tagopts)
 {
+       bool is_oid = false;
+       bool dot = false;
        int i;
 
-       switch (tree->operation) {
-       case LDB_OP_AND:
-       case LDB_OP_OR:
-               asn1_push_tag(data,
-                             ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1));
-               for (i=0; i<tree->u.list.num_elements; i++) {
-                       if (!ldap_push_filter(data,
-                                             tree->u.list.elements[i])) {
+       /* first char has stricter rules */
+       if (isdigit(*s)) {
+               is_oid = true;
+       } else if (!tldap_is_alpha(*s)) {
+               /* bad first char */
+               return false;
+       }
+
+       for (i = 1; i < len; i++) {
+
+               if (is_oid) {
+                       if (isdigit(s[i])) {
+                               dot = false;
+                               continue;
+                       }
+                       if (s[i] == '.') {
+                               if (dot) {
+                                       /* malformed */
+                                       return false;
+                               }
+                               dot = true;
+                               continue;
+                       }
+               } else {
+                       if (tldap_is_adh(s[i])) {
+                               continue;
+                       }
+               }
+
+               if (s[i] == ';') {
+                       if (no_tagopts) {
+                               /* no tagging options */
+                               return false;
+                       }
+                       if (dot) {
+                               /* malformed */
+                               return false;
+                       }
+                       if ((i + 1) == len) {
+                               /* malformed */
                                return false;
                        }
+
+                       is_oid = false;
+                       continue;
                }
-               asn1_pop_tag(data);
-               break;
+       }
 
-       case LDB_OP_NOT:
-               asn1_push_tag(data, ASN1_CONTEXT(2));
-               if (!ldap_push_filter(data, tree->u.isnot.child)) {
-                       return false;
+       if (dot) {
+               /* malformed */
+               return false;
+       }
+
+       return true;
+}
+
+/* this function copies the value until the closing parenthesis is found. */
+static char *tldap_get_val(TALLOC_CTX *memctx,
+                          const char *value, const char **_s)
+{
+       const char *s = value;
+
+       /* find terminator */
+       while (*s) {
+               s = strchr(s, ')');
+               if (s && (*(s - 1) == '\\')) {
+                       continue;
                }
-               asn1_pop_tag(data);
                break;
+       }
+       if (!s || !(*s == ')')) {
+               /* malformed filter */
+               return NULL;
+       }
 
-       case LDB_OP_EQUALITY:
-               /* equality test */
-               asn1_push_tag(data, ASN1_CONTEXT(3));
-               asn1_write_OctetString(data, tree->u.equality.attr,
-                                     strlen(tree->u.equality.attr));
-               asn1_write_OctetString(data, tree->u.equality.value.data,
-                                     tree->u.equality.value.length);
-               asn1_pop_tag(data);
-               break;
+       *_s = s;
 
-       case LDB_OP_SUBSTRING:
-               /*
-                 SubstringFilter ::= SEQUENCE {
-                         type            AttributeDescription,
-                         -- at least one must be present
-                         substrings      SEQUENCE OF CHOICE {
-                                 initial [0] LDAPString,
-                                 any     [1] LDAPString,
-                                 final   [2] LDAPString } }
-               */
-               asn1_push_tag(data, ASN1_CONTEXT(4));
-               asn1_write_OctetString(data, tree->u.substring.attr,
-                                      strlen(tree->u.substring.attr));
-               asn1_push_tag(data, ASN1_SEQUENCE(0));
-               i = 0;
-               if (!tree->u.substring.start_with_wildcard) {
-                       asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0));
-                       asn1_write_DATA_BLOB_LDAPString(
-                               data, tree->u.substring.chunks[i]);
-                       asn1_pop_tag(data);
-                       i++;
+       return talloc_strndup(memctx, value, s - value);
+}
+
+static int tldap_hex2char(const char *x)
+{
+       if (isxdigit(x[0]) && isxdigit(x[1])) {
+               const char h1 = x[0], h2 = x[1];
+               int c = 0;
+
+               if (h1 >= 'a') c = h1 - (int)'a' + 10;
+               else if (h1 >= 'A') c = h1 - (int)'A' + 10;
+               else if (h1 >= '0') c = h1 - (int)'0';
+               c = c << 4;
+               if (h2 >= 'a') c += h2 - (int)'a' + 10;
+               else if (h2 >= 'A') c += h2 - (int)'A' + 10;
+               else if (h2 >= '0') c += h2 - (int)'0';
+
+               return c;
+       }
+
+       return -1;
+}
+
+static bool tldap_find_first_star(const char *val, const char **star)
+{
+       const char *s;
+
+       for (s = val; *s; s++) {
+               switch (*s) {
+               case '\\':
+                       if (isxdigit(s[1]) && isxdigit(s[2])) {
+                               s += 2;
+                               break;
+                       }
+                       /* not hex based escape, check older syntax */
+                       switch (s[1]) {
+                       case '(':
+                       case ')':
+                       case '*':
+                       case '\\':
+                               s++;
+                               break;
+                       default:
+                               /* invalid escape sequence */
+                               return false;
+                       }
+                       break;
+               case ')':
+                       /* end of val, nothing found */
+                       *star = s;
+                       return true;
+
+               case '*':
+                       *star = s;
+                       return true;
                }
-               while (tree->u.substring.chunks[i]) {
-                       int ctx;
+       }
 
-                       if ((!tree->u.substring.chunks[i + 1]) &&
-                           (tree->u.substring.end_with_wildcard == 0)) {
-                               ctx = 2;
-                       } else {
-                               ctx = 1;
+       /* string ended without closing parenthesis, filter is malformed */
+       return false;
+}
+
+static bool tldap_unescape_inplace(char *value, size_t *val_len)
+{
+       int c, i, p;
+
+       for (i = 0,p = 0; i < *val_len; i++) {
+
+               switch (value[i]) {
+               case '(':
+               case ')':
+               case '*':
+                       /* these must be escaped */
+                       return false;
+
+               case '\\':
+                       if (!value[i + 1]) {
+                               /* invalid EOL */
+                               return false;
                        }
-                       asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx));
-                       asn1_write_DATA_BLOB_LDAPString(
-                               data, tree->u.substring.chunks[i]);
-                       asn1_pop_tag(data);
                        i++;
+
+                       c = tldap_hex2char(&value[i]);
+                       if (c >= 0 && c < 256) {
+                               value[p] = c;
+                               i++;
+                               p++;
+                               break;
+                       }
+
+                       switch (value[i]) {
+                       case '(':
+                       case ')':
+                       case '*':
+                       case '\\':
+                               value[p] = value[i];
+                               p++;
+                       default:
+                               /* invalid */
+                               return false;
+                       }
+                       break;
+
+               default:
+                       value[p] = value[i];
+                       p++;
                }
-               asn1_pop_tag(data);
-               asn1_pop_tag(data);
-               break;
+       }
+       value[p] = '\0';
+       *val_len = p;
+       return true;
+}
 
-       case LDB_OP_GREATER:
-               /* greaterOrEqual test */
-               asn1_push_tag(data, ASN1_CONTEXT(5));
-               asn1_write_OctetString(data, tree->u.comparison.attr,
-                                     strlen(tree->u.comparison.attr));
-               asn1_write_OctetString(data, tree->u.comparison.value.data,
-                                     tree->u.comparison.value.length);
-               asn1_pop_tag(data);
+static bool tldap_push_filter_basic(struct tldap_context *ld,
+                                   struct asn1_data *data,
+                                   const char **_s);
+static bool tldap_push_filter_substring(struct tldap_context *ld,
+                                       struct asn1_data *data,
+                                       const char *val,
+                                       const char **_s);
+static bool tldap_push_filter_int(struct tldap_context *ld,
+                                 struct asn1_data *data,
+                                 const char **_s)
+{
+       const char *s = *_s;
+       bool ret;
+
+       if (*s != '(') {
+               tldap_debug(ld, TLDAP_DEBUG_ERROR,
+                           "Incomplete or malformed filter\n");
+               return false;
+       }
+       s++;
+
+       /* we are right after a parenthesis,
+        * find out what op we have at hand */
+       switch (*s) {
+       case '&':
+               tldap_debug(ld, TLDAP_DEBUG_TRACE, "Filter op: AND\n");
+               asn1_push_tag(data, TLDAP_FILTER_AND);
+               s++;
                break;
 
-       case LDB_OP_LESS:
-               /* lessOrEqual test */
-               asn1_push_tag(data, ASN1_CONTEXT(6));
-               asn1_write_OctetString(data, tree->u.comparison.attr,
-                                     strlen(tree->u.comparison.attr));
-               asn1_write_OctetString(data, tree->u.comparison.value.data,
-                                     tree->u.comparison.value.length);
-               asn1_pop_tag(data);
+       case '|':
+               tldap_debug(ld, TLDAP_DEBUG_TRACE, "Filter op: OR\n");
+               asn1_push_tag(data, TLDAP_FILTER_OR);
+               s++;
                break;
 
-       case LDB_OP_PRESENT:
-               /* present test */
-               asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7));
-               asn1_write_LDAPString(data, tree->u.present.attr);
+       case '!':
+               tldap_debug(ld, TLDAP_DEBUG_TRACE, "Filter op: NOT\n");
+               asn1_push_tag(data, TLDAP_FILTER_NOT);
+               s++;
+               ret = tldap_push_filter_int(ld, data, &s);
+               if (!ret) {
+                       return false;
+               }
                asn1_pop_tag(data);
-               return !data->has_error;
-
-       case LDB_OP_APPROX:
-               /* approx test */
-               asn1_push_tag(data, ASN1_CONTEXT(8));
-               asn1_write_OctetString(data, tree->u.comparison.attr,
-                                     strlen(tree->u.comparison.attr));
-               asn1_write_OctetString(data, tree->u.comparison.value.data,
-                                     tree->u.comparison.value.length);
+               goto done;
+
+       case '(':
+       case ')':
+               tldap_debug(ld, TLDAP_DEBUG_ERROR,
+                           "Invalid parenthesis '%c'\n", *s);
+               return false;
+
+       case '\0':
+               tldap_debug(ld, TLDAP_DEBUG_ERROR,
+                           "Invalid filter termination\n");
+               return false;
+
+       default:
+               ret = tldap_push_filter_basic(ld, data, &s);
+               if (!ret) {
+                       return false;
+               }
+               goto done;
+       }
+
+       /* only and/or filters get here.
+        * go through the list of filters */
+
+       if (*s == ')') {
+               /* RFC 4526: empty and/or */
                asn1_pop_tag(data);
+               goto done;
+       }
+
+       while (*s) {
+               ret = tldap_push_filter_int(ld, data, &s);
+               if (!ret) {
+                       return false;
+               }
+
+               if (*s == ')') {
+                       /* end of list, return */
+                       asn1_pop_tag(data);
+                       break;
+               }
+       }
+
+done:
+       if (*s != ')') {
+               tldap_debug(ld, TLDAP_DEBUG_ERROR,
+                           "Incomplete or malformed filter\n");
+               return false;
+       }
+       s++;
+
+       if (data->has_error) {
+               return false;
+       }
+
+       *_s = s;
+       return true;
+}
+
+
+static bool tldap_push_filter_basic(struct tldap_context *ld,
+                                   struct asn1_data *data,
+                                   const char **_s)
+{
+       TALLOC_CTX *tmpctx = talloc_tos();
+       const char *s = *_s;
+       const char *e;
+       const char *eq;
+       const char *val;
+       const char *type;
+       const char *dn;
+       const char *rule;
+       const char *star;
+       size_t type_len = 0;
+       char *uval;
+       size_t uval_len;
+       bool write_octect = true;
+       bool ret;
+
+       eq = strchr(s, '=');
+       if (!eq) {
+               tldap_debug(ld, TLDAP_DEBUG_ERROR,
+                           "Invalid filter, missing equal sign\n");
+               return false;
+       }
+
+       val = eq + 1;
+       e = eq - 1;
+
+       switch (*e) {
+       case '<':
+               asn1_push_tag(data, TLDAP_FILTER_LE);
                break;
 
-       case LDB_OP_EXTENDED:
+       case '>':
+               asn1_push_tag(data, TLDAP_FILTER_GE);
+               break;
+
+       case '~':
+               asn1_push_tag(data, TLDAP_FILTER_APX);
+               break;
+
+       case ':':
+               asn1_push_tag(data, TLDAP_FILTER_EXT);
+               write_octect = false;
+
+               type = NULL;
+               dn = NULL;
+               rule = NULL;
+
+               if (*s == ':') { /* [:dn]:rule:= value */
+                       if (s == e) {
+                               /* malformed filter */
+                               return false;
+                       }
+                       dn = s;
+               } else { /* type[:dn][:rule]:= value */
+                       type = s;
+                       dn = strchr(s, ':');
+                       type_len = dn - type;
+                       if (dn == e) { /* type:= value */
+                               dn = NULL;
+                       }
+               }
+               if (dn) {
+                       dn++;
+
+                       rule = strchr(dn, ':');
+                       if ((rule == dn + 1) || rule + 1 == e) {
+                               /* malformed filter, contains "::" */
+                               return false;
+                       }
+
+                       if (strncasecmp_m(dn, "dn:", 3) != 0) {
+                               if (rule == e) {
+                                       rule = dn;
+                                       dn = NULL;
+                               } else {
+                                       /* malformed filter. With two
+                                        * optionals, the first must be "dn"
+                                        */
+                                       return false;
+                               }
+                       } else {
+                               if (rule == e) {
+                                       rule = NULL;
+                               } else {
+                                       rule++;
+                               }
+                       }
+               }
+
+               if (!type && !dn && !rule) {
+                       /* malformed filter, there must be at least one */
+                       return false;
+               }
+
                /*
                  MatchingRuleAssertion ::= SEQUENCE {
                  matchingRule    [1] MatchingRuleID OPTIONAL,
-                 type            [2] AttributeDescription OPTIONAL,
+                 type      [2] AttributeDescription OPTIONAL,
                  matchValue      [3] AssertionValue,
                  dnAttributes    [4] BOOLEAN DEFAULT FALSE
                  }
                */
-               asn1_push_tag(data, ASN1_CONTEXT(9));
-               if (tree->u.extended.rule_id) {
+
+               /* check and add rule */
+               if (rule) {
+                       ret = tldap_is_attrdesc(rule, e - rule, true);
+                       if (!ret) {
+                               return false;
+                       }
                        asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1));
-                       asn1_write_LDAPString(data, tree->u.extended.rule_id);
+                       asn1_write(data, rule, e - rule);
                        asn1_pop_tag(data);
                }
-               if (tree->u.extended.attr) {
+
+               /* check and add type */
+               if (type) {
+                       ret = tldap_is_attrdesc(type, type_len, false);
+                       if (!ret) {
+                               return false;
+                       }
                        asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2));
-                       asn1_write_LDAPString(data, tree->u.extended.attr);
+                       asn1_write(data, type, type_len);
                        asn1_pop_tag(data);
                }
+
+               uval = tldap_get_val(tmpctx, val, _s);
+               if (!uval) {
+                       return false;
+               }
+               uval_len = *_s - val;
+               ret = tldap_unescape_inplace(uval, &uval_len);
+               if (!ret) {
+                       return false;
+               }
+
                asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3));
-               asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value);
+               asn1_write(data, uval, uval_len);
                asn1_pop_tag(data);
+
                asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4));
-               asn1_write_uint8(data, tree->u.extended.dnAttributes);
-               asn1_pop_tag(data);
+               asn1_write_uint8(data, dn?1:0);
                asn1_pop_tag(data);
                break;
 
        default:
+               e = eq;
+
+               ret = tldap_is_attrdesc(s, e - s, false);
+               if (!ret) {
+                       return false;
+               }
+
+               if (strncmp(val, "*)", 2) == 0) {
+                       /* presence */
+                       asn1_push_tag(data, TLDAP_FILTER_PRES);
+                       asn1_write(data, s, e - s);
+                       *_s = val + 1;
+                       write_octect = false;
+                       break;
+               }
+
+               ret = tldap_find_first_star(val, &star);
+               if (!ret) {
+                       return false;
+               }
+               if (*star == '*') {
+                       /* substring */
+                       asn1_push_tag(data, TLDAP_FILTER_SUB);
+                       asn1_write_OctetString(data, s, e - s);
+                       ret = tldap_push_filter_substring(ld, data, val, &s);
+                       if (!ret) {
+                               return false;
+                       }
+                       *_s = s;
+                       write_octect = false;
+                       break;
+               }
+
+               /* if nothing else, then it is just equality */
+               asn1_push_tag(data, TLDAP_FILTER_EQ);
+               write_octect = true;
+               break;
+       }
+
+       if (write_octect) {
+               uval = tldap_get_val(tmpctx, val, _s);
+               if (!uval) {
+                       return false;
+               }
+               uval_len = *_s - val;
+               ret = tldap_unescape_inplace(uval, &uval_len);
+               if (!ret) {
+                       return false;
+               }
+
+               asn1_write_OctetString(data, s, e - s);
+               asn1_write_OctetString(data, uval, uval_len);
+       }
+
+       if (data->has_error) {
                return false;
        }
-       return !data->has_error;
+       asn1_pop_tag(data);
+       return true;
 }
 
-static bool tldap_push_filter(struct asn1_data *data, const char *filter)
+static bool tldap_push_filter_substring(struct tldap_context *ld,
+                                       struct asn1_data *data,
+                                       const char *val,
+                                       const char **_s)
 {
-       struct ldb_parse_tree *tree;
+       TALLOC_CTX *tmpctx = talloc_tos();
+       bool initial = true;
+       const char *star;
+       char *chunk;
+       size_t chunk_len;
        bool ret;
 
-       tree = ldb_parse_tree(talloc_tos(), filter);
-       if (tree == NULL) {
+       /*
+         SubstringFilter ::= SEQUENCE {
+                 type      AttributeDescription,
+                 -- at least one must be present
+                 substrings      SEQUENCE OF CHOICE {
+                         initial [0] LDAPString,
+                         any     [1] LDAPString,
+                         final   [2] LDAPString } }
+       */
+       asn1_push_tag(data, ASN1_SEQUENCE(0));
+
+       do {
+               ret = tldap_find_first_star(val, &star);
+               if (!ret) {
+                       return false;
+               }
+               chunk_len = star - val;
+
+               switch (*star) {
+               case '*':
+                       if (!initial && chunk_len == 0) {
+                               /* found '**', which is illegal */
+                               return false;
+                       }
+                       break;
+               case ')':
+                       if (initial) {
+                               /* no stars ?? */
+                               return false;
+                       }
+                       /* we are done */
+                       break;
+               default:
+                       /* ?? */
+                       return false;
+               }
+
+               if (initial && chunk_len == 0) {
+                       val = star + 1;
+                       initial = false;
+                       continue;
+               }
+
+               chunk = talloc_strndup(tmpctx, val, chunk_len);
+               if (!chunk) {
+                       return false;
+               }
+               ret = tldap_unescape_inplace(chunk, &chunk_len);
+               if (!ret) {
+                       return false;
+               }
+               switch (*star) {
+               case '*':
+                       if (initial) {
+                               asn1_push_tag(data, TLDAP_SUB_INI);
+                               initial = false;
+                       } else {
+                               asn1_push_tag(data, TLDAP_SUB_ANY);
+                       }
+                       break;
+               case ')':
+                       asn1_push_tag(data, TLDAP_SUB_FIN);
+                       break;
+               default:
+                       /* ?? */
+                       return false;
+               }
+               asn1_write(data, chunk, chunk_len);
+               asn1_pop_tag(data);
+
+               val = star + 1;
+
+       } while (*star == '*');
+
+       *_s = star;
+
+       /* end of sequence */
+       asn1_pop_tag(data);
+       return true;
+}
+
+/* NOTE: although openldap libraries allow for spaces in some places, mosly
+ * around parenthesis, we do not allow any spaces (except in values of
+ * course) as I couldn't fine any place in RFC 4512 or RFC 4515 where
+ * leading or trailing spaces where allowed.
+ */
+static bool tldap_push_filter(struct tldap_context *ld,
+                             struct asn1_data *data,
+                             const char *filter)
+{
+       const char *s = filter;
+       bool ret;
+
+       ret = tldap_push_filter_int(ld, data, &s);
+       if (ret && *s) {
+               tldap_debug(ld, TLDAP_DEBUG_ERROR,
+                           "Incomplete or malformed filter\n");
                return false;
        }
-       ret = ldap_push_filter(data, tree);
-       TALLOC_FREE(tree);
        return ret;
 }
 
@@ -1135,7 +1662,7 @@ struct tevent_req *tldap_search_send(TALLOC_CTX *mem_ctx,
        asn1_write_Integer(state->out, timelimit);
        asn1_write_BOOLEAN(state->out, attrsonly);
 
-       if (!tldap_push_filter(state->out, filter)) {
+       if (!tldap_push_filter(ld, state->out, filter)) {
                goto encoding_error;
        }
 
@@ -1175,18 +1702,19 @@ static void tldap_search_done(struct tevent_req *subreq)
        switch (state->result->type) {
        case TLDAP_RES_SEARCH_ENTRY:
        case TLDAP_RES_SEARCH_REFERENCE:
-               tevent_req_notify_callback(req);
                if (!tldap_msg_set_pending(subreq)) {
-                       tevent_req_nomem(NULL, req);
+                       tevent_req_oom(req);
                        return;
                }
+               tevent_req_notify_callback(req);
                break;
        case TLDAP_RES_SEARCH_RESULT:
                TALLOC_FREE(subreq);
                if (!asn1_start_tag(state->result->data,
                                    state->result->type) ||
                    !tldap_decode_response(state) ||
-                   !asn1_end_tag(state->result->data)) {
+                   !asn1_end_tag(state->result->data) ||
+                   !tldap_decode_controls(state)) {
                        tevent_req_error(req, TLDAP_DECODING_ERROR);
                        return;
                }
@@ -1313,6 +1841,13 @@ int tldap_search(struct tldap_context *ld,
 
        tevent_req_set_callback(req, tldap_search_cb, &state);
 
+       if (!tevent_req_is_in_progress(req)) {
+               /* an error happend before sending */
+               if (tevent_req_is_ldap_error(req, &state.rc)) {
+                       goto fail;
+               }
+       }
+
        while (tevent_req_is_in_progress(req)
               && (state.rc == TLDAP_SUCCESS)) {
                if (tevent_loop_once(ev) == -1) {
@@ -1334,7 +1869,7 @@ int tldap_search(struct tldap_context *ld,
        } else {
                TALLOC_FREE(state.refs);
        }
-       tldap_save_errors(ld, req);
+       tldap_save_msg(ld, req);
 fail:
        TALLOC_FREE(frame);
        return state.rc;
@@ -1423,8 +1958,9 @@ bool tldap_entry_dn(struct tldap_message *msg, char **dn)
        return true;
 }
 
-bool tldap_entry_attributes(struct tldap_message *msg, int *num_attributes,
-                           struct tldap_attribute **attributes)
+bool tldap_entry_attributes(struct tldap_message *msg,
+                           struct tldap_attribute **attributes,
+                           int *num_attributes)
 {
        if ((msg->dn == NULL) && (!tldap_parse_search_entry(msg))) {
                return false;
@@ -1436,11 +1972,12 @@ bool tldap_entry_attributes(struct tldap_message *msg, int *num_attributes,
 
 static bool tldap_decode_controls(struct tldap_req_state *state)
 {
-       struct asn1_data *data = state->result->data;
+       struct tldap_message *msg = state->result;
+       struct asn1_data *data = msg->data;
        struct tldap_control *sctrls = NULL;
        int num_controls = 0;
 
-       state->res_sctrls = NULL;
+       msg->res_sctrls = NULL;
 
        if (!asn1_peek_tag(data, ASN1_CONTEXT(0))) {
                return true;
@@ -1452,7 +1989,7 @@ static bool tldap_decode_controls(struct tldap_req_state *state)
                struct tldap_control *c;
                char *oid = NULL;
 
-               sctrls = talloc_realloc(state, sctrls, struct tldap_control,
+               sctrls = talloc_realloc(msg, sctrls, struct tldap_control,
                                        num_controls + 1);
                if (sctrls == NULL) {
                        return false;
@@ -1460,7 +1997,7 @@ static bool tldap_decode_controls(struct tldap_req_state *state)
                c = &sctrls[num_controls];
 
                asn1_start_tag(data, ASN1_SEQUENCE(0));
-               asn1_read_OctetString_talloc(state, data, &oid);
+               asn1_read_OctetString_talloc(msg, data, &oid);
                if ((data->has_error) || (oid == NULL)) {
                        return false;
                }
@@ -1472,7 +2009,7 @@ static bool tldap_decode_controls(struct tldap_req_state *state)
                }
                c->value = data_blob_null;
                if (asn1_peek_tag(data, ASN1_OCTET_STRING) &&
-                   !asn1_read_OctetString(data, state, &c->value)) {
+                   !asn1_read_OctetString(data, msg, &c->value)) {
                        return false;
                }
                asn1_end_tag(data); /* ASN1_SEQUENCE(0) */
@@ -1486,7 +2023,7 @@ static bool tldap_decode_controls(struct tldap_req_state *state)
                TALLOC_FREE(sctrls);
                return false;
        }
-       state->res_sctrls = sctrls;
+       msg->res_sctrls = sctrls;
        return true;
 }
 
@@ -1515,8 +2052,8 @@ static void tldap_simple_done(struct tevent_req *subreq, int type)
                tevent_req_error(req, TLDAP_DECODING_ERROR);
                return;
        }
-       if (state->lderr != TLDAP_SUCCESS) {
-               tevent_req_error(req, state->lderr);
+       if (state->result->lderr != TLDAP_SUCCESS) {
+               tevent_req_error(req, state->result->lderr);
                return;
        }
        tevent_req_done(req);
@@ -1586,7 +2123,7 @@ struct tevent_req *tldap_add_send(TALLOC_CTX *mem_ctx,
 
 static void tldap_add_done(struct tevent_req *subreq)
 {
-       return tldap_simple_done(subreq, TLDAP_RES_ADD);
+       tldap_simple_done(subreq, TLDAP_RES_ADD);
 }
 
 int tldap_add_recv(struct tevent_req *req)
@@ -1595,7 +2132,7 @@ int tldap_add_recv(struct tevent_req *req)
 }
 
 int tldap_add(struct tldap_context *ld, const char *dn,
-             int num_attributes, struct tldap_mod *attributes,
+             struct tldap_mod *attributes, int num_attributes,
              struct tldap_control *sctrls, int num_sctrls,
              struct tldap_control *cctrls, int num_cctrls)
 {
@@ -1623,7 +2160,7 @@ int tldap_add(struct tldap_context *ld, const char *dn,
        }
 
        result = tldap_add_recv(req);
-       tldap_save_errors(ld, req);
+       tldap_save_msg(ld, req);
  fail:
        TALLOC_FREE(frame);
        return result;
@@ -1635,7 +2172,7 @@ struct tevent_req *tldap_modify_send(TALLOC_CTX *mem_ctx,
                                     struct tevent_context *ev,
                                     struct tldap_context *ld,
                                     const char *dn,
-                                    int num_mods, struct tldap_mod *mods,
+                                    struct tldap_mod *mods, int num_mods,
                                     struct tldap_control *sctrls,
                                     int num_sctrls,
                                     struct tldap_control *cctrls,
@@ -1686,7 +2223,7 @@ struct tevent_req *tldap_modify_send(TALLOC_CTX *mem_ctx,
 
 static void tldap_modify_done(struct tevent_req *subreq)
 {
-       return tldap_simple_done(subreq, TLDAP_RES_MODIFY);
+       tldap_simple_done(subreq, TLDAP_RES_MODIFY);
 }
 
 int tldap_modify_recv(struct tevent_req *req)
@@ -1695,7 +2232,7 @@ int tldap_modify_recv(struct tevent_req *req)
 }
 
 int tldap_modify(struct tldap_context *ld, const char *dn,
-                int num_mods, struct tldap_mod *mods,
+                struct tldap_mod *mods, int num_mods,
                 struct tldap_control *sctrls, int num_sctrls,
                 struct tldap_control *cctrls, int num_cctrls)
  {
@@ -1710,7 +2247,7 @@ int tldap_modify(struct tldap_context *ld, const char *dn,
                goto fail;
        }
 
-       req = tldap_modify_send(frame, ev, ld, dn, num_mods, mods,
+       req = tldap_modify_send(frame, ev, ld, dn, mods, num_mods,
                                sctrls, num_sctrls, cctrls, num_cctrls);
        if (req == NULL) {
                result = TLDAP_NO_MEMORY;
@@ -1723,7 +2260,7 @@ int tldap_modify(struct tldap_context *ld, const char *dn,
        }
 
        result = tldap_modify_recv(req);
-       tldap_save_errors(ld, req);
+       tldap_save_msg(ld, req);
  fail:
        TALLOC_FREE(frame);
        return result;
@@ -1763,7 +2300,7 @@ struct tevent_req *tldap_delete_send(TALLOC_CTX *mem_ctx,
 
 static void tldap_delete_done(struct tevent_req *subreq)
 {
-       return tldap_simple_done(subreq, TLDAP_RES_DELETE);
+       tldap_simple_done(subreq, TLDAP_RES_DELETE);
 }
 
 int tldap_delete_recv(struct tevent_req *req)
@@ -1799,7 +2336,7 @@ int tldap_delete(struct tldap_context *ld, const char *dn,
        }
 
        result = tldap_delete_recv(req);
-       tldap_save_errors(ld, req);
+       tldap_save_msg(ld, req);
  fail:
        TALLOC_FREE(frame);
        return result;
@@ -1815,56 +2352,45 @@ int tldap_msg_type(const struct tldap_message *msg)
        return msg->type;
 }
 
-const char *tldap_req_matcheddn(struct tevent_req *req)
+const char *tldap_msg_matcheddn(struct tldap_message *msg)
 {
-       struct tldap_req_state *state = tevent_req_data(
-               req, struct tldap_req_state);
-       return state->res_matcheddn;
+       if (msg == NULL) {
+               return NULL;
+       }
+       return msg->res_matcheddn;
 }
 
-const char *tldap_req_diagnosticmessage(struct tevent_req *req)
+const char *tldap_msg_diagnosticmessage(struct tldap_message *msg)
 {
-       struct tldap_req_state *state = tevent_req_data(
-               req, struct tldap_req_state);
-       return state->res_diagnosticmessage;
+       if (msg == NULL) {
+               return NULL;
+       }
+       return msg->res_diagnosticmessage;
 }
 
-const char *tldap_req_referral(struct tevent_req *req)
+const char *tldap_msg_referral(struct tldap_message *msg)
 {
-       struct tldap_req_state *state = tevent_req_data(
-               req, struct tldap_req_state);
-       return state->res_referral;
+       if (msg == NULL) {
+               return NULL;
+       }
+       return msg->res_referral;
 }
 
-void tldap_req_sctrls(struct tevent_req *req, int *num_sctrls,
+void tldap_msg_sctrls(struct tldap_message *msg, int *num_sctrls,
                      struct tldap_control **sctrls)
 {
-       struct tldap_req_state *state = tevent_req_data(
-               req, struct tldap_req_state);
-       *sctrls = state->res_sctrls;
-       *num_sctrls = talloc_array_length(state->res_sctrls);
-}
-
-const char *tldap_ctx_matcheddn(struct tldap_context *ctx)
-{
-       return ctx->res_matcheddn;
-}
-
-const char *tldap_ctx_diagnosticmessage(struct tldap_context *ctx)
-{
-       return ctx->res_diagnosticmessage;
-}
-
-const char *tldap_ctx_referral(struct tldap_context *ctx)
-{
-       return ctx->res_referral;
+       if (msg == NULL) {
+               *sctrls = NULL;
+               *num_sctrls = 0;
+               return;
+       }
+       *sctrls = msg->res_sctrls;
+       *num_sctrls = talloc_array_length(msg->res_sctrls);
 }
 
-void tldap_ctx_sctrls(struct tldap_context *ctx, int *num_sctrls,
-                     struct tldap_control **sctrls)
+struct tldap_message *tldap_ctx_lastmsg(struct tldap_context *ld)
 {
-       *sctrls = ctx->res_sctrls;
-       *num_sctrls = talloc_array_length(ctx->res_sctrls);
+       return ld->last_msg;
 }
 
 const char *tldap_err2string(int rc)