s3:lib/tldap: make use of tevent_req_defer_callback()
[samba.git] / source3 / lib / tldap.c
1 /*
2    Unix SMB/CIFS implementation.
3    Infrastructure for async ldap client requests
4    Copyright (C) Volker Lendecke 2009
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "tldap.h"
22 #include "../lib/util/asn1.h"
23 #include "../lib/tsocket/tsocket.h"
24 #include "../lib/util/tevent_unix.h"
25
26 static int tldap_simple_recv(struct tevent_req *req);
27
28 bool tevent_req_is_ldap_error(struct tevent_req *req, int *perr)
29 {
30         enum tevent_req_state state;
31         uint64_t err;
32
33         if (!tevent_req_is_error(req, &state, &err)) {
34                 return false;
35         }
36         switch (state) {
37         case TEVENT_REQ_TIMED_OUT:
38                 *perr = TLDAP_TIMEOUT;
39                 break;
40         case TEVENT_REQ_NO_MEMORY:
41                 *perr = TLDAP_NO_MEMORY;
42                 break;
43         case TEVENT_REQ_USER_ERROR:
44                 *perr = err;
45                 break;
46         default:
47                 *perr = TLDAP_OPERATIONS_ERROR;
48                 break;
49         }
50         return true;
51 }
52
53 struct tldap_ctx_attribute {
54         char *name;
55         void *ptr;
56 };
57
58 struct tldap_context {
59         int ld_version;
60         int ld_deref;
61         int ld_sizelimit;
62         int ld_timelimit;
63         struct tstream_context *conn;
64         bool server_down;
65         int msgid;
66         struct tevent_queue *outgoing;
67         struct tevent_req **pending;
68
69         /* For the sync wrappers we need something like get_last_error... */
70         struct tldap_message *last_msg;
71
72         /* debug */
73         void (*log_fn)(void *context, enum tldap_debug_level level,
74                        const char *fmt, va_list ap);
75         void *log_private;
76
77         struct tldap_ctx_attribute *ctx_attrs;
78 };
79
80 struct tldap_message {
81         struct asn1_data *data;
82         uint8_t *inbuf;
83         int type;
84         int id;
85
86         /* RESULT_ENTRY */
87         char *dn;
88         struct tldap_attribute *attribs;
89
90         /* Error data sent by the server */
91         int lderr;
92         char *res_matcheddn;
93         char *res_diagnosticmessage;
94         char *res_referral;
95         struct tldap_control *res_sctrls;
96
97         /* Controls sent by the server */
98         struct tldap_control *ctrls;
99 };
100
101 void tldap_set_debug(struct tldap_context *ld,
102                      void (*log_fn)(void *log_private,
103                                     enum tldap_debug_level level,
104                                     const char *fmt,
105                                     va_list ap) PRINTF_ATTRIBUTE(3,0),
106                      void *log_private)
107 {
108         ld->log_fn = log_fn;
109         ld->log_private = log_private;
110 }
111
112 static void tldap_debug(struct tldap_context *ld,
113                          enum tldap_debug_level level,
114                          const char *fmt, ...)
115 {
116         va_list ap;
117         if (!ld) {
118                 return;
119         }
120         if (ld->log_fn == NULL) {
121                 return;
122         }
123         va_start(ap, fmt);
124         ld->log_fn(ld->log_private, level, fmt, ap);
125         va_end(ap);
126 }
127
128 static int tldap_next_msgid(struct tldap_context *ld)
129 {
130         int result;
131
132         result = ld->msgid++;
133         if (ld->msgid == 2147483647) {
134                 ld->msgid = 1;
135         }
136         return result;
137 }
138
139 struct tldap_context *tldap_context_create(TALLOC_CTX *mem_ctx, int fd)
140 {
141         struct tldap_context *ctx;
142         int ret;
143
144         ctx = talloc_zero(mem_ctx, struct tldap_context);
145         if (ctx == NULL) {
146                 return NULL;
147         }
148         ret = tstream_bsd_existing_socket(ctx, fd, &ctx->conn);
149         if (ret == -1) {
150                 TALLOC_FREE(ctx);
151                 return NULL;
152         }
153         ctx->msgid = 1;
154         ctx->ld_version = 3;
155         ctx->outgoing = tevent_queue_create(ctx, "tldap_outgoing");
156         if (ctx->outgoing == NULL) {
157                 TALLOC_FREE(ctx);
158                 return NULL;
159         }
160         return ctx;
161 }
162
163 bool tldap_connection_ok(struct tldap_context *ld)
164 {
165         if (ld == NULL) {
166                 return false;
167         }
168         return !ld->server_down;
169 }
170
171 static struct tldap_ctx_attribute *tldap_context_findattr(
172         struct tldap_context *ld, const char *name)
173 {
174         int i, num_attrs;
175
176         num_attrs = talloc_array_length(ld->ctx_attrs);
177
178         for (i=0; i<num_attrs; i++) {
179                 if (strcmp(ld->ctx_attrs[i].name, name) == 0) {
180                         return &ld->ctx_attrs[i];
181                 }
182         }
183         return NULL;
184 }
185
186 bool tldap_context_setattr(struct tldap_context *ld,
187                            const char *name, const void *_pptr)
188 {
189         struct tldap_ctx_attribute *tmp, *attr;
190         char *tmpname;
191         int num_attrs;
192         void **pptr = (void **)discard_const_p(void,_pptr);
193
194         attr = tldap_context_findattr(ld, name);
195         if (attr != NULL) {
196                 /*
197                  * We don't actually delete attrs, we don't expect tons of
198                  * attributes being shuffled around.
199                  */
200                 TALLOC_FREE(attr->ptr);
201                 if (*pptr != NULL) {
202                         attr->ptr = talloc_move(ld->ctx_attrs, pptr);
203                         *pptr = NULL;
204                 }
205                 return true;
206         }
207
208         tmpname = talloc_strdup(ld, name);
209         if (tmpname == NULL) {
210                 return false;
211         }
212
213         num_attrs = talloc_array_length(ld->ctx_attrs);
214
215         tmp = talloc_realloc(ld, ld->ctx_attrs, struct tldap_ctx_attribute,
216                              num_attrs+1);
217         if (tmp == NULL) {
218                 TALLOC_FREE(tmpname);
219                 return false;
220         }
221         tmp[num_attrs].name = talloc_move(tmp, &tmpname);
222         if (*pptr != NULL) {
223                 tmp[num_attrs].ptr = talloc_move(tmp, pptr);
224         } else {
225                 tmp[num_attrs].ptr = NULL;
226         }
227         *pptr = NULL;
228         ld->ctx_attrs = tmp;
229         return true;
230 }
231
232 void *tldap_context_getattr(struct tldap_context *ld, const char *name)
233 {
234         struct tldap_ctx_attribute *attr = tldap_context_findattr(ld, name);
235
236         if (attr == NULL) {
237                 return NULL;
238         }
239         return attr->ptr;
240 }
241
242 struct read_ldap_state {
243         uint8_t *buf;
244         bool done;
245 };
246
247 static ssize_t read_ldap_more(uint8_t *buf, size_t buflen, void *private_data);
248 static void read_ldap_done(struct tevent_req *subreq);
249
250 static struct tevent_req *read_ldap_send(TALLOC_CTX *mem_ctx,
251                                          struct tevent_context *ev,
252                                          struct tstream_context *conn)
253 {
254         struct tevent_req *req, *subreq;
255         struct read_ldap_state *state;
256
257         req = tevent_req_create(mem_ctx, &state, struct read_ldap_state);
258         if (req == NULL) {
259                 return NULL;
260         }
261         state->done = false;
262
263         subreq = tstream_read_packet_send(state, ev, conn, 2, read_ldap_more,
264                                           state);
265         if (tevent_req_nomem(subreq, req)) {
266                 return tevent_req_post(req, ev);
267         }
268         tevent_req_set_callback(subreq, read_ldap_done, req);
269         return req;
270 }
271
272 static ssize_t read_ldap_more(uint8_t *buf, size_t buflen, void *private_data)
273 {
274         struct read_ldap_state *state = talloc_get_type_abort(
275                 private_data, struct read_ldap_state);
276         size_t len;
277         int i, lensize;
278
279         if (state->done) {
280                 /* We've been here, we're done */
281                 return 0;
282         }
283
284         /*
285          * From ldap.h: LDAP_TAG_MESSAGE is 0x30
286          */
287         if (buf[0] != 0x30) {
288                 return -1;
289         }
290
291         len = buf[1];
292         if ((len & 0x80) == 0) {
293                 state->done = true;
294                 return len;
295         }
296
297         lensize = (len & 0x7f);
298         len = 0;
299
300         if (buflen == 2) {
301                 /* Please get us the full length */
302                 return lensize;
303         }
304         if (buflen > 2 + lensize) {
305                 state->done = true;
306                 return 0;
307         }
308         if (buflen != 2 + lensize) {
309                 return -1;
310         }
311
312         for (i=0; i<lensize; i++) {
313                 len = (len << 8) | buf[2+i];
314         }
315         return len;
316 }
317
318 static void read_ldap_done(struct tevent_req *subreq)
319 {
320         struct tevent_req *req = tevent_req_callback_data(
321                 subreq, struct tevent_req);
322         struct read_ldap_state *state = tevent_req_data(
323                 req, struct read_ldap_state);
324         ssize_t nread;
325         int err;
326
327         nread = tstream_read_packet_recv(subreq, state, &state->buf, &err);
328         TALLOC_FREE(subreq);
329         if (nread == -1) {
330                 tevent_req_error(req, err);
331                 return;
332         }
333         tevent_req_done(req);
334 }
335
336 static ssize_t read_ldap_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
337                               uint8_t **pbuf, int *perrno)
338 {
339         struct read_ldap_state *state = tevent_req_data(
340                 req, struct read_ldap_state);
341
342         if (tevent_req_is_unix_error(req, perrno)) {
343                 return -1;
344         }
345         *pbuf = talloc_move(mem_ctx, &state->buf);
346         return talloc_get_size(*pbuf);
347 }
348
349 struct tldap_msg_state {
350         struct tldap_context *ld;
351         struct tevent_context *ev;
352         int id;
353         struct iovec iov;
354
355         struct asn1_data *data;
356         uint8_t *inbuf;
357 };
358
359 static void tldap_push_controls(struct asn1_data *data,
360                                 struct tldap_control *sctrls,
361                                 int num_sctrls)
362 {
363         int i;
364
365         if ((sctrls == NULL) || (num_sctrls == 0)) {
366                 return;
367         }
368
369         asn1_push_tag(data, ASN1_CONTEXT(0));
370
371         for (i=0; i<num_sctrls; i++) {
372                 struct tldap_control *c = &sctrls[i];
373                 asn1_push_tag(data, ASN1_SEQUENCE(0));
374                 asn1_write_OctetString(data, c->oid, strlen(c->oid));
375                 if (c->critical) {
376                         asn1_write_BOOLEAN(data, true);
377                 }
378                 if (c->value.data != NULL) {
379                         asn1_write_OctetString(data, c->value.data,
380                                                c->value.length);
381                 }
382                 asn1_pop_tag(data); /* ASN1_SEQUENCE(0) */
383         }
384
385         asn1_pop_tag(data); /* ASN1_CONTEXT(0) */
386 }
387
388 static void tldap_msg_sent(struct tevent_req *subreq);
389 static void tldap_msg_received(struct tevent_req *subreq);
390
391 static struct tevent_req *tldap_msg_send(TALLOC_CTX *mem_ctx,
392                                          struct tevent_context *ev,
393                                          struct tldap_context *ld,
394                                          int id, struct asn1_data *data,
395                                          struct tldap_control *sctrls,
396                                          int num_sctrls)
397 {
398         struct tevent_req *req, *subreq;
399         struct tldap_msg_state *state;
400         DATA_BLOB blob;
401
402         tldap_debug(ld, TLDAP_DEBUG_TRACE, "tldap_msg_send: sending msg %d\n",
403                     id);
404
405         req = tevent_req_create(mem_ctx, &state, struct tldap_msg_state);
406         if (req == NULL) {
407                 return NULL;
408         }
409         state->ld = ld;
410         state->ev = ev;
411         state->id = id;
412
413         if (state->ld->server_down) {
414                 tevent_req_error(req, TLDAP_SERVER_DOWN);
415                 return tevent_req_post(req, ev);
416         }
417
418         tldap_push_controls(data, sctrls, num_sctrls);
419
420         asn1_pop_tag(data);
421
422         if (!asn1_blob(data, &blob)) {
423                 tevent_req_error(req, TLDAP_ENCODING_ERROR);
424                 return tevent_req_post(req, ev);
425         }
426
427         state->iov.iov_base = (void *)blob.data;
428         state->iov.iov_len = blob.length;
429
430         subreq = tstream_writev_queue_send(state, ev, ld->conn, ld->outgoing,
431                                            &state->iov, 1);
432         if (tevent_req_nomem(subreq, req)) {
433                 return tevent_req_post(req, ev);
434         }
435         tevent_req_set_callback(subreq, tldap_msg_sent, req);
436         return req;
437 }
438
439 static void tldap_msg_unset_pending(struct tevent_req *req)
440 {
441         struct tldap_msg_state *state = tevent_req_data(
442                 req, struct tldap_msg_state);
443         struct tldap_context *ld = state->ld;
444         int num_pending = talloc_array_length(ld->pending);
445         int i;
446
447         if (num_pending == 1) {
448                 TALLOC_FREE(ld->pending);
449                 return;
450         }
451
452         for (i=0; i<num_pending; i++) {
453                 if (req == ld->pending[i]) {
454                         break;
455                 }
456         }
457         if (i == num_pending) {
458                 /*
459                  * Something's seriously broken. Just returning here is the
460                  * right thing nevertheless, the point of this routine is to
461                  * remove ourselves from cli->pending.
462                  */
463                 return;
464         }
465
466         /*
467          * Remove ourselves from the cli->pending array
468          */
469         if (num_pending > 1) {
470                 ld->pending[i] = ld->pending[num_pending-1];
471         }
472
473         /*
474          * No NULL check here, we're shrinking by sizeof(void *), and
475          * talloc_realloc just adjusts the size for this.
476          */
477         ld->pending = talloc_realloc(NULL, ld->pending, struct tevent_req *,
478                                      num_pending - 1);
479         return;
480 }
481
482 static int tldap_msg_destructor(struct tevent_req *req)
483 {
484         tldap_msg_unset_pending(req);
485         return 0;
486 }
487
488 static bool tldap_msg_set_pending(struct tevent_req *req)
489 {
490         struct tldap_msg_state *state = tevent_req_data(
491                 req, struct tldap_msg_state);
492         struct tldap_context *ld;
493         struct tevent_req **pending;
494         int num_pending;
495         struct tevent_req *subreq;
496
497         ld = state->ld;
498         num_pending = talloc_array_length(ld->pending);
499
500         pending = talloc_realloc(ld, ld->pending, struct tevent_req *,
501                                  num_pending+1);
502         if (pending == NULL) {
503                 return false;
504         }
505         pending[num_pending] = req;
506         ld->pending = pending;
507         talloc_set_destructor(req, tldap_msg_destructor);
508
509         if (num_pending > 0) {
510                 return true;
511         }
512
513         /*
514          * We're the first one, add the read_ldap request that waits for the
515          * answer from the server
516          */
517         subreq = read_ldap_send(ld->pending, state->ev, ld->conn);
518         if (subreq == NULL) {
519                 tldap_msg_unset_pending(req);
520                 return false;
521         }
522         tevent_req_set_callback(subreq, tldap_msg_received, ld);
523         return true;
524 }
525
526 static void tldap_msg_sent(struct tevent_req *subreq)
527 {
528         struct tevent_req *req = tevent_req_callback_data(
529                 subreq, struct tevent_req);
530         struct tldap_msg_state *state = tevent_req_data(
531                 req, struct tldap_msg_state);
532         ssize_t nwritten;
533         int err;
534
535         nwritten = tstream_writev_queue_recv(subreq, &err);
536         TALLOC_FREE(subreq);
537         if (nwritten == -1) {
538                 state->ld->server_down = true;
539                 tevent_req_error(req, TLDAP_SERVER_DOWN);
540                 return;
541         }
542
543         if (!tldap_msg_set_pending(req)) {
544                 tevent_req_oom(req);
545                 return;
546         }
547 }
548
549 static int tldap_msg_msgid(struct tevent_req *req)
550 {
551         struct tldap_msg_state *state = tevent_req_data(
552                 req, struct tldap_msg_state);
553
554         return state->id;
555 }
556
557 static void tldap_msg_received(struct tevent_req *subreq)
558 {
559         struct tldap_context *ld = tevent_req_callback_data(
560                 subreq, struct tldap_context);
561         struct tevent_req *req;
562         struct tldap_msg_state *state;
563         struct asn1_data *data;
564         uint8_t *inbuf;
565         ssize_t received;
566         size_t num_pending;
567         int i, err, status;
568         int id;
569         uint8_t type;
570         bool ok;
571
572         received = read_ldap_recv(subreq, talloc_tos(), &inbuf, &err);
573         TALLOC_FREE(subreq);
574         if (received == -1) {
575                 status = TLDAP_SERVER_DOWN;
576                 goto fail;
577         }
578
579         data = asn1_init(talloc_tos());
580         if (data == NULL) {
581                 status = TLDAP_NO_MEMORY;
582                 goto fail;
583         }
584         asn1_load_nocopy(data, inbuf, received);
585
586         ok = true;
587         ok &= asn1_start_tag(data, ASN1_SEQUENCE(0));
588         ok &= asn1_read_Integer(data, &id);
589         ok &= asn1_peek_uint8(data, &type);
590
591         if (!ok) {
592                 status = TLDAP_PROTOCOL_ERROR;
593                 goto fail;
594         }
595
596         tldap_debug(ld, TLDAP_DEBUG_TRACE, "tldap_msg_received: got msg %d "
597                     "type %d\n", id, (int)type);
598
599         num_pending = talloc_array_length(ld->pending);
600
601         for (i=0; i<num_pending; i++) {
602                 if (id == tldap_msg_msgid(ld->pending[i])) {
603                         break;
604                 }
605         }
606         if (i == num_pending) {
607                 /* Dump unexpected reply */
608                 tldap_debug(ld, TLDAP_DEBUG_WARNING, "tldap_msg_received: "
609                             "No request pending for msg %d\n", id);
610                 TALLOC_FREE(data);
611                 TALLOC_FREE(inbuf);
612                 goto done;
613         }
614
615         req = ld->pending[i];
616         state = tevent_req_data(req, struct tldap_msg_state);
617
618         state->inbuf = talloc_move(state, &inbuf);
619         state->data = talloc_move(state, &data);
620
621         talloc_set_destructor(req, NULL);
622         tldap_msg_unset_pending(req);
623         num_pending = talloc_array_length(ld->pending);
624
625         tevent_req_done(req);
626
627  done:
628         if (num_pending == 0) {
629                 return;
630         }
631         if (talloc_array_length(ld->pending) > num_pending) {
632                 /*
633                  * The callback functions called from tevent_req_done() above
634                  * have put something on the pending queue. We don't have to
635                  * trigger the read_ldap_send(), tldap_msg_set_pending() has
636                  * done it for us already.
637                  */
638                 return;
639         }
640
641         state = tevent_req_data(ld->pending[0], struct tldap_msg_state);
642         subreq = read_ldap_send(ld->pending, state->ev, ld->conn);
643         if (subreq == NULL) {
644                 status = TLDAP_NO_MEMORY;
645                 goto fail;
646         }
647         tevent_req_set_callback(subreq, tldap_msg_received, ld);
648         return;
649
650  fail:
651         while (talloc_array_length(ld->pending) > 0) {
652                 req = ld->pending[0];
653                 state = tevent_req_data(req, struct tldap_msg_state);
654                 tevent_req_defer_callback(req, state->ev);
655                 talloc_set_destructor(req, NULL);
656                 tldap_msg_destructor(req);
657                 tevent_req_error(req, status);
658         }
659 }
660
661 static int tldap_msg_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
662                           struct tldap_message **pmsg)
663 {
664         struct tldap_msg_state *state = tevent_req_data(
665                 req, struct tldap_msg_state);
666         struct tldap_message *msg;
667         int err;
668         uint8_t msgtype;
669
670         if (tevent_req_is_ldap_error(req, &err)) {
671                 return err;
672         }
673
674         if (!asn1_peek_uint8(state->data, &msgtype)) {
675                 return TLDAP_PROTOCOL_ERROR;
676         }
677
678         if (pmsg == NULL) {
679                 return TLDAP_SUCCESS;
680         }
681
682         msg = talloc_zero(mem_ctx, struct tldap_message);
683         if (msg == NULL) {
684                 return TLDAP_NO_MEMORY;
685         }
686         msg->id = state->id;
687
688         msg->inbuf = talloc_move(msg, &state->inbuf);
689         msg->data = talloc_move(msg, &state->data);
690         msg->type = msgtype;
691
692         *pmsg = msg;
693         return TLDAP_SUCCESS;
694 }
695
696 struct tldap_req_state {
697         int id;
698         struct asn1_data *out;
699         struct tldap_message *result;
700 };
701
702 static struct tevent_req *tldap_req_create(TALLOC_CTX *mem_ctx,
703                                            struct tldap_context *ld,
704                                            struct tldap_req_state **pstate)
705 {
706         struct tevent_req *req;
707         struct tldap_req_state *state;
708
709         req = tevent_req_create(mem_ctx, &state, struct tldap_req_state);
710         if (req == NULL) {
711                 return NULL;
712         }
713         ZERO_STRUCTP(state);
714         state->out = asn1_init(state);
715         if (state->out == NULL) {
716                 TALLOC_FREE(req);
717                 return NULL;
718         }
719         state->result = NULL;
720         state->id = tldap_next_msgid(ld);
721
722         asn1_push_tag(state->out, ASN1_SEQUENCE(0));
723         asn1_write_Integer(state->out, state->id);
724
725         *pstate = state;
726         return req;
727 }
728
729 static void tldap_save_msg(struct tldap_context *ld, struct tevent_req *req)
730 {
731         struct tldap_req_state *state = tevent_req_data(
732                 req, struct tldap_req_state);
733
734         TALLOC_FREE(ld->last_msg);
735         ld->last_msg = talloc_move(ld, &state->result);
736 }
737
738 static char *blob2string_talloc(TALLOC_CTX *mem_ctx, DATA_BLOB blob)
739 {
740         char *result = talloc_array(mem_ctx, char, blob.length+1);
741
742         if (result == NULL) {
743                 return NULL;
744         }
745
746         memcpy(result, blob.data, blob.length);
747         result[blob.length] = '\0';
748         return result;
749 }
750
751 static bool asn1_read_OctetString_talloc(TALLOC_CTX *mem_ctx,
752                                          struct asn1_data *data,
753                                          char **presult)
754 {
755         DATA_BLOB string;
756         char *result;
757         if (!asn1_read_OctetString(data, mem_ctx, &string))
758                 return false;
759
760         result = blob2string_talloc(mem_ctx, string);
761
762         data_blob_free(&string);
763
764         if (result == NULL) {
765                 return false;
766         }
767         *presult = result;
768         return true;
769 }
770
771 static bool tldap_decode_controls(struct tldap_req_state *state);
772
773 static bool tldap_decode_response(struct tldap_req_state *state)
774 {
775         struct asn1_data *data = state->result->data;
776         struct tldap_message *msg = state->result;
777         bool ok = true;
778
779         ok &= asn1_read_enumerated(data, &msg->lderr);
780         ok &= asn1_read_OctetString_talloc(msg, data, &msg->res_matcheddn);
781         ok &= asn1_read_OctetString_talloc(msg, data,
782                                            &msg->res_diagnosticmessage);
783         if (asn1_peek_tag(data, ASN1_CONTEXT(3))) {
784                 ok &= asn1_start_tag(data, ASN1_CONTEXT(3));
785                 ok &= asn1_read_OctetString_talloc(msg, data,
786                                                    &msg->res_referral);
787                 ok &= asn1_end_tag(data);
788         } else {
789                 msg->res_referral = NULL;
790         }
791
792         return ok;
793 }
794
795 static void tldap_sasl_bind_done(struct tevent_req *subreq);
796
797 struct tevent_req *tldap_sasl_bind_send(TALLOC_CTX *mem_ctx,
798                                         struct tevent_context *ev,
799                                         struct tldap_context *ld,
800                                         const char *dn,
801                                         const char *mechanism,
802                                         DATA_BLOB *creds,
803                                         struct tldap_control *sctrls,
804                                         int num_sctrls,
805                                         struct tldap_control *cctrls,
806                                         int num_cctrls)
807 {
808         struct tevent_req *req, *subreq;
809         struct tldap_req_state *state;
810
811         req = tldap_req_create(mem_ctx, ld, &state);
812         if (req == NULL) {
813                 return NULL;
814         }
815
816         if (dn == NULL) {
817                 dn = "";
818         }
819
820         asn1_push_tag(state->out, TLDAP_REQ_BIND);
821         asn1_write_Integer(state->out, ld->ld_version);
822         asn1_write_OctetString(state->out, dn, strlen(dn));
823
824         if (mechanism == NULL) {
825                 asn1_push_tag(state->out, ASN1_CONTEXT_SIMPLE(0));
826                 asn1_write(state->out, creds->data, creds->length);
827                 asn1_pop_tag(state->out);
828         } else {
829                 asn1_push_tag(state->out, ASN1_CONTEXT(3));
830                 asn1_write_OctetString(state->out, mechanism,
831                                        strlen(mechanism));
832                 if ((creds != NULL) && (creds->data != NULL)) {
833                         asn1_write_OctetString(state->out, creds->data,
834                                                creds->length);
835                 }
836                 asn1_pop_tag(state->out);
837         }
838
839         if (!asn1_pop_tag(state->out)) {
840                 tevent_req_error(req, TLDAP_ENCODING_ERROR);
841                 return tevent_req_post(req, ev);
842         }
843
844         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
845                                 sctrls, num_sctrls);
846         if (tevent_req_nomem(subreq, req)) {
847                 return tevent_req_post(req, ev);
848         }
849         tevent_req_set_callback(subreq, tldap_sasl_bind_done, req);
850         return req;
851 }
852
853 static void tldap_sasl_bind_done(struct tevent_req *subreq)
854 {
855         struct tevent_req *req = tevent_req_callback_data(
856                 subreq, struct tevent_req);
857         struct tldap_req_state *state = tevent_req_data(
858                 req, struct tldap_req_state);
859         int err;
860
861         err = tldap_msg_recv(subreq, state, &state->result);
862         TALLOC_FREE(subreq);
863         if (err != TLDAP_SUCCESS) {
864                 tevent_req_error(req, err);
865                 return;
866         }
867         if (state->result->type != TLDAP_RES_BIND) {
868                 tevent_req_error(req, TLDAP_PROTOCOL_ERROR);
869                 return;
870         }
871         if (!asn1_start_tag(state->result->data, state->result->type) ||
872             !tldap_decode_response(state) ||
873             !asn1_end_tag(state->result->data)) {
874                 tevent_req_error(req, TLDAP_DECODING_ERROR);
875                 return;
876         }
877         /*
878          * TODO: pull the reply blob
879          */
880         if (state->result->lderr != TLDAP_SUCCESS) {
881                 tevent_req_error(req, state->result->lderr);
882                 return;
883         }
884         tevent_req_done(req);
885 }
886
887 int tldap_sasl_bind_recv(struct tevent_req *req)
888 {
889         return tldap_simple_recv(req);
890 }
891
892 int tldap_sasl_bind(struct tldap_context *ld,
893                     const char *dn,
894                     const char *mechanism,
895                     DATA_BLOB *creds,
896                     struct tldap_control *sctrls,
897                     int num_sctrls,
898                     struct tldap_control *cctrls,
899                     int num_cctrls)
900 {
901         TALLOC_CTX *frame = talloc_stackframe();
902         struct tevent_context *ev;
903         struct tevent_req *req;
904         int result;
905
906         ev = samba_tevent_context_init(frame);
907         if (ev == NULL) {
908                 result = TLDAP_NO_MEMORY;
909                 goto fail;
910         }
911
912         req = tldap_sasl_bind_send(frame, ev, ld, dn, mechanism, creds,
913                                    sctrls, num_sctrls, cctrls, num_cctrls);
914         if (req == NULL) {
915                 result = TLDAP_NO_MEMORY;
916                 goto fail;
917         }
918
919         if (!tevent_req_poll(req, ev)) {
920                 result = TLDAP_OPERATIONS_ERROR;
921                 goto fail;
922         }
923
924         result = tldap_sasl_bind_recv(req);
925         tldap_save_msg(ld, req);
926  fail:
927         TALLOC_FREE(frame);
928         return result;
929 }
930
931 struct tevent_req *tldap_simple_bind_send(TALLOC_CTX *mem_ctx,
932                                           struct tevent_context *ev,
933                                           struct tldap_context *ld,
934                                           const char *dn,
935                                           const char *passwd)
936 {
937         DATA_BLOB cred;
938
939         if (passwd != NULL) {
940                 cred.data = discard_const_p(uint8_t, passwd);
941                 cred.length = strlen(passwd);
942         } else {
943                 cred.data = discard_const_p(uint8_t, "");
944                 cred.length = 0;
945         }
946         return tldap_sasl_bind_send(mem_ctx, ev, ld, dn, NULL, &cred, NULL, 0,
947                                     NULL, 0);
948 }
949
950 int tldap_simple_bind_recv(struct tevent_req *req)
951 {
952         return tldap_sasl_bind_recv(req);
953 }
954
955 int tldap_simple_bind(struct tldap_context *ld, const char *dn,
956                       const char *passwd)
957 {
958         DATA_BLOB cred;
959
960         if (passwd != NULL) {
961                 cred.data = discard_const_p(uint8_t, passwd);
962                 cred.length = strlen(passwd);
963         } else {
964                 cred.data = discard_const_p(uint8_t, "");
965                 cred.length = 0;
966         }
967         return tldap_sasl_bind(ld, dn, NULL, &cred, NULL, 0, NULL, 0);
968 }
969
970 /*****************************************************************************/
971
972 /* can't use isalpha() as only a strict set is valid for LDAP */
973
974 static bool tldap_is_alpha(char c)
975 {
976         return (((c >= 'a') && (c <= 'z')) || \
977                 ((c >= 'A') && (c <= 'Z')));
978 }
979
980 static bool tldap_is_adh(char c)
981 {
982         return tldap_is_alpha(c) || isdigit(c) || (c == '-');
983 }
984
985 #define TLDAP_FILTER_AND  ASN1_CONTEXT(0)
986 #define TLDAP_FILTER_OR   ASN1_CONTEXT(1)
987 #define TLDAP_FILTER_NOT  ASN1_CONTEXT(2)
988 #define TLDAP_FILTER_EQ   ASN1_CONTEXT(3)
989 #define TLDAP_FILTER_SUB  ASN1_CONTEXT(4)
990 #define TLDAP_FILTER_LE   ASN1_CONTEXT(5)
991 #define TLDAP_FILTER_GE   ASN1_CONTEXT(6)
992 #define TLDAP_FILTER_PRES ASN1_CONTEXT_SIMPLE(7)
993 #define TLDAP_FILTER_APX  ASN1_CONTEXT(8)
994 #define TLDAP_FILTER_EXT  ASN1_CONTEXT(9)
995
996 #define TLDAP_SUB_INI ASN1_CONTEXT_SIMPLE(0)
997 #define TLDAP_SUB_ANY ASN1_CONTEXT_SIMPLE(1)
998 #define TLDAP_SUB_FIN ASN1_CONTEXT_SIMPLE(2)
999
1000
1001 /* oid's should be numerical only in theory,
1002  * but apparently some broken servers may have alphanum aliases instead.
1003  * Do like openldap libraries and allow alphanum aliases for oids, but
1004  * do not allow Tagging options in that case.
1005  */
1006 static bool tldap_is_attrdesc(const char *s, int len, bool no_tagopts)
1007 {
1008         bool is_oid = false;
1009         bool dot = false;
1010         int i;
1011
1012         /* first char has stricter rules */
1013         if (isdigit(*s)) {
1014                 is_oid = true;
1015         } else if (!tldap_is_alpha(*s)) {
1016                 /* bad first char */
1017                 return false;
1018         }
1019
1020         for (i = 1; i < len; i++) {
1021
1022                 if (is_oid) {
1023                         if (isdigit(s[i])) {
1024                                 dot = false;
1025                                 continue;
1026                         }
1027                         if (s[i] == '.') {
1028                                 if (dot) {
1029                                         /* malformed */
1030                                         return false;
1031                                 }
1032                                 dot = true;
1033                                 continue;
1034                         }
1035                 } else {
1036                         if (tldap_is_adh(s[i])) {
1037                                 continue;
1038                         }
1039                 }
1040
1041                 if (s[i] == ';') {
1042                         if (no_tagopts) {
1043                                 /* no tagging options */
1044                                 return false;
1045                         }
1046                         if (dot) {
1047                                 /* malformed */
1048                                 return false;
1049                         }
1050                         if ((i + 1) == len) {
1051                                 /* malformed */
1052                                 return false;
1053                         }
1054
1055                         is_oid = false;
1056                         continue;
1057                 }
1058         }
1059
1060         if (dot) {
1061                 /* malformed */
1062                 return false;
1063         }
1064
1065         return true;
1066 }
1067
1068 /* this function copies the value until the closing parenthesis is found. */
1069 static char *tldap_get_val(TALLOC_CTX *memctx,
1070                            const char *value, const char **_s)
1071 {
1072         const char *s = value;
1073
1074         /* find terminator */
1075         while (*s) {
1076                 s = strchr(s, ')');
1077                 if (s && (*(s - 1) == '\\')) {
1078                         continue;
1079                 }
1080                 break;
1081         }
1082         if (!s || !(*s == ')')) {
1083                 /* malformed filter */
1084                 return NULL;
1085         }
1086
1087         *_s = s;
1088
1089         return talloc_strndup(memctx, value, s - value);
1090 }
1091
1092 static int tldap_hex2char(const char *x)
1093 {
1094         if (isxdigit(x[0]) && isxdigit(x[1])) {
1095                 const char h1 = x[0], h2 = x[1];
1096                 int c = 0;
1097
1098                 if (h1 >= 'a') c = h1 - (int)'a' + 10;
1099                 else if (h1 >= 'A') c = h1 - (int)'A' + 10;
1100                 else if (h1 >= '0') c = h1 - (int)'0';
1101                 c = c << 4;
1102                 if (h2 >= 'a') c += h2 - (int)'a' + 10;
1103                 else if (h2 >= 'A') c += h2 - (int)'A' + 10;
1104                 else if (h2 >= '0') c += h2 - (int)'0';
1105
1106                 return c;
1107         }
1108
1109         return -1;
1110 }
1111
1112 static bool tldap_find_first_star(const char *val, const char **star)
1113 {
1114         const char *s;
1115
1116         for (s = val; *s; s++) {
1117                 switch (*s) {
1118                 case '\\':
1119                         if (isxdigit(s[1]) && isxdigit(s[2])) {
1120                                 s += 2;
1121                                 break;
1122                         }
1123                         /* not hex based escape, check older syntax */
1124                         switch (s[1]) {
1125                         case '(':
1126                         case ')':
1127                         case '*':
1128                         case '\\':
1129                                 s++;
1130                                 break;
1131                         default:
1132                                 /* invalid escape sequence */
1133                                 return false;
1134                         }
1135                         break;
1136                 case ')':
1137                         /* end of val, nothing found */
1138                         *star = s;
1139                         return true;
1140
1141                 case '*':
1142                         *star = s;
1143                         return true;
1144                 }
1145         }
1146
1147         /* string ended without closing parenthesis, filter is malformed */
1148         return false;
1149 }
1150
1151 static bool tldap_unescape_inplace(char *value, size_t *val_len)
1152 {
1153         int c, i, p;
1154
1155         for (i = 0,p = 0; i < *val_len; i++) {
1156
1157                 switch (value[i]) {
1158                 case '(':
1159                 case ')':
1160                 case '*':
1161                         /* these must be escaped */
1162                         return false;
1163
1164                 case '\\':
1165                         if (!value[i + 1]) {
1166                                 /* invalid EOL */
1167                                 return false;
1168                         }
1169                         i++;
1170
1171                         c = tldap_hex2char(&value[i]);
1172                         if (c >= 0 && c < 256) {
1173                                 value[p] = c;
1174                                 i++;
1175                                 p++;
1176                                 break;
1177                         }
1178
1179                         switch (value[i]) {
1180                         case '(':
1181                         case ')':
1182                         case '*':
1183                         case '\\':
1184                                 value[p] = value[i];
1185                                 p++;
1186                         default:
1187                                 /* invalid */
1188                                 return false;
1189                         }
1190                         break;
1191
1192                 default:
1193                         value[p] = value[i];
1194                         p++;
1195                 }
1196         }
1197         value[p] = '\0';
1198         *val_len = p;
1199         return true;
1200 }
1201
1202 static bool tldap_push_filter_basic(struct tldap_context *ld,
1203                                     struct asn1_data *data,
1204                                     const char **_s);
1205 static bool tldap_push_filter_substring(struct tldap_context *ld,
1206                                         struct asn1_data *data,
1207                                         const char *val,
1208                                         const char **_s);
1209 static bool tldap_push_filter_int(struct tldap_context *ld,
1210                                   struct asn1_data *data,
1211                                   const char **_s)
1212 {
1213         const char *s = *_s;
1214         bool ret;
1215
1216         if (*s != '(') {
1217                 tldap_debug(ld, TLDAP_DEBUG_ERROR,
1218                             "Incomplete or malformed filter\n");
1219                 return false;
1220         }
1221         s++;
1222
1223         /* we are right after a parenthesis,
1224          * find out what op we have at hand */
1225         switch (*s) {
1226         case '&':
1227                 tldap_debug(ld, TLDAP_DEBUG_TRACE, "Filter op: AND\n");
1228                 asn1_push_tag(data, TLDAP_FILTER_AND);
1229                 s++;
1230                 break;
1231
1232         case '|':
1233                 tldap_debug(ld, TLDAP_DEBUG_TRACE, "Filter op: OR\n");
1234                 asn1_push_tag(data, TLDAP_FILTER_OR);
1235                 s++;
1236                 break;
1237
1238         case '!':
1239                 tldap_debug(ld, TLDAP_DEBUG_TRACE, "Filter op: NOT\n");
1240                 asn1_push_tag(data, TLDAP_FILTER_NOT);
1241                 s++;
1242                 ret = tldap_push_filter_int(ld, data, &s);
1243                 if (!ret) {
1244                         return false;
1245                 }
1246                 asn1_pop_tag(data);
1247                 goto done;
1248
1249         case '(':
1250         case ')':
1251                 tldap_debug(ld, TLDAP_DEBUG_ERROR,
1252                             "Invalid parenthesis '%c'\n", *s);
1253                 return false;
1254
1255         case '\0':
1256                 tldap_debug(ld, TLDAP_DEBUG_ERROR,
1257                             "Invalid filter termination\n");
1258                 return false;
1259
1260         default:
1261                 ret = tldap_push_filter_basic(ld, data, &s);
1262                 if (!ret) {
1263                         return false;
1264                 }
1265                 goto done;
1266         }
1267
1268         /* only and/or filters get here.
1269          * go through the list of filters */
1270
1271         if (*s == ')') {
1272                 /* RFC 4526: empty and/or */
1273                 asn1_pop_tag(data);
1274                 goto done;
1275         }
1276
1277         while (*s) {
1278                 ret = tldap_push_filter_int(ld, data, &s);
1279                 if (!ret) {
1280                         return false;
1281                 }
1282
1283                 if (*s == ')') {
1284                         /* end of list, return */
1285                         asn1_pop_tag(data);
1286                         break;
1287                 }
1288         }
1289
1290 done:
1291         if (*s != ')') {
1292                 tldap_debug(ld, TLDAP_DEBUG_ERROR,
1293                             "Incomplete or malformed filter\n");
1294                 return false;
1295         }
1296         s++;
1297
1298         if (data->has_error) {
1299                 return false;
1300         }
1301
1302         *_s = s;
1303         return true;
1304 }
1305
1306
1307 static bool tldap_push_filter_basic(struct tldap_context *ld,
1308                                     struct asn1_data *data,
1309                                     const char **_s)
1310 {
1311         TALLOC_CTX *tmpctx = talloc_tos();
1312         const char *s = *_s;
1313         const char *e;
1314         const char *eq;
1315         const char *val;
1316         const char *type;
1317         const char *dn;
1318         const char *rule;
1319         const char *star;
1320         size_t type_len = 0;
1321         char *uval;
1322         size_t uval_len;
1323         bool write_octect = true;
1324         bool ret;
1325
1326         eq = strchr(s, '=');
1327         if (!eq) {
1328                 tldap_debug(ld, TLDAP_DEBUG_ERROR,
1329                             "Invalid filter, missing equal sign\n");
1330                 return false;
1331         }
1332
1333         val = eq + 1;
1334         e = eq - 1;
1335
1336         switch (*e) {
1337         case '<':
1338                 asn1_push_tag(data, TLDAP_FILTER_LE);
1339                 break;
1340
1341         case '>':
1342                 asn1_push_tag(data, TLDAP_FILTER_GE);
1343                 break;
1344
1345         case '~':
1346                 asn1_push_tag(data, TLDAP_FILTER_APX);
1347                 break;
1348
1349         case ':':
1350                 asn1_push_tag(data, TLDAP_FILTER_EXT);
1351                 write_octect = false;
1352
1353                 type = NULL;
1354                 dn = NULL;
1355                 rule = NULL;
1356
1357                 if (*s == ':') { /* [:dn]:rule:= value */
1358                         if (s == e) {
1359                                 /* malformed filter */
1360                                 return false;
1361                         }
1362                         dn = s;
1363                 } else { /* type[:dn][:rule]:= value */
1364                         type = s;
1365                         dn = strchr(s, ':');
1366                         type_len = dn - type;
1367                         if (dn == e) { /* type:= value */
1368                                 dn = NULL;
1369                         }
1370                 }
1371                 if (dn) {
1372                         dn++;
1373
1374                         rule = strchr(dn, ':');
1375                         if (rule == NULL) {
1376                                 return false;
1377                         }
1378                         if ((rule == dn + 1) || rule + 1 == e) {
1379                                 /* malformed filter, contains "::" */
1380                                 return false;
1381                         }
1382
1383                         if (strncasecmp_m(dn, "dn:", 3) != 0) {
1384                                 if (rule == e) {
1385                                         rule = dn;
1386                                         dn = NULL;
1387                                 } else {
1388                                         /* malformed filter. With two
1389                                          * optionals, the first must be "dn"
1390                                          */
1391                                         return false;
1392                                 }
1393                         } else {
1394                                 if (rule == e) {
1395                                         rule = NULL;
1396                                 } else {
1397                                         rule++;
1398                                 }
1399                         }
1400                 }
1401
1402                 if (!type && !dn && !rule) {
1403                         /* malformed filter, there must be at least one */
1404                         return false;
1405                 }
1406
1407                 /*
1408                   MatchingRuleAssertion ::= SEQUENCE {
1409                   matchingRule    [1] MatchingRuleID OPTIONAL,
1410                   type      [2] AttributeDescription OPTIONAL,
1411                   matchValue      [3] AssertionValue,
1412                   dnAttributes    [4] BOOLEAN DEFAULT FALSE
1413                   }
1414                 */
1415
1416                 /* check and add rule */
1417                 if (rule) {
1418                         ret = tldap_is_attrdesc(rule, e - rule, true);
1419                         if (!ret) {
1420                                 return false;
1421                         }
1422                         asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1));
1423                         asn1_write(data, rule, e - rule);
1424                         asn1_pop_tag(data);
1425                 }
1426
1427                 /* check and add type */
1428                 if (type) {
1429                         ret = tldap_is_attrdesc(type, type_len, false);
1430                         if (!ret) {
1431                                 return false;
1432                         }
1433                         asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2));
1434                         asn1_write(data, type, type_len);
1435                         asn1_pop_tag(data);
1436                 }
1437
1438                 uval = tldap_get_val(tmpctx, val, _s);
1439                 if (!uval) {
1440                         return false;
1441                 }
1442                 uval_len = *_s - val;
1443                 ret = tldap_unescape_inplace(uval, &uval_len);
1444                 if (!ret) {
1445                         return false;
1446                 }
1447
1448                 asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3));
1449                 asn1_write(data, uval, uval_len);
1450                 asn1_pop_tag(data);
1451
1452                 asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4));
1453                 asn1_write_uint8(data, dn?1:0);
1454                 asn1_pop_tag(data);
1455                 break;
1456
1457         default:
1458                 e = eq;
1459
1460                 ret = tldap_is_attrdesc(s, e - s, false);
1461                 if (!ret) {
1462                         return false;
1463                 }
1464
1465                 if (strncmp(val, "*)", 2) == 0) {
1466                         /* presence */
1467                         asn1_push_tag(data, TLDAP_FILTER_PRES);
1468                         asn1_write(data, s, e - s);
1469                         *_s = val + 1;
1470                         write_octect = false;
1471                         break;
1472                 }
1473
1474                 ret = tldap_find_first_star(val, &star);
1475                 if (!ret) {
1476                         return false;
1477                 }
1478                 if (*star == '*') {
1479                         /* substring */
1480                         asn1_push_tag(data, TLDAP_FILTER_SUB);
1481                         asn1_write_OctetString(data, s, e - s);
1482                         ret = tldap_push_filter_substring(ld, data, val, &s);
1483                         if (!ret) {
1484                                 return false;
1485                         }
1486                         *_s = s;
1487                         write_octect = false;
1488                         break;
1489                 }
1490
1491                 /* if nothing else, then it is just equality */
1492                 asn1_push_tag(data, TLDAP_FILTER_EQ);
1493                 write_octect = true;
1494                 break;
1495         }
1496
1497         if (write_octect) {
1498                 uval = tldap_get_val(tmpctx, val, _s);
1499                 if (!uval) {
1500                         return false;
1501                 }
1502                 uval_len = *_s - val;
1503                 ret = tldap_unescape_inplace(uval, &uval_len);
1504                 if (!ret) {
1505                         return false;
1506                 }
1507
1508                 asn1_write_OctetString(data, s, e - s);
1509                 asn1_write_OctetString(data, uval, uval_len);
1510         }
1511
1512         if (data->has_error) {
1513                 return false;
1514         }
1515         asn1_pop_tag(data);
1516         return true;
1517 }
1518
1519 static bool tldap_push_filter_substring(struct tldap_context *ld,
1520                                         struct asn1_data *data,
1521                                         const char *val,
1522                                         const char **_s)
1523 {
1524         TALLOC_CTX *tmpctx = talloc_tos();
1525         bool initial = true;
1526         const char *star;
1527         char *chunk;
1528         size_t chunk_len;
1529         bool ret;
1530
1531         /*
1532           SubstringFilter ::= SEQUENCE {
1533                   type      AttributeDescription,
1534                   -- at least one must be present
1535                   substrings      SEQUENCE OF CHOICE {
1536                           initial [0] LDAPString,
1537                           any     [1] LDAPString,
1538                           final   [2] LDAPString } }
1539         */
1540         asn1_push_tag(data, ASN1_SEQUENCE(0));
1541
1542         do {
1543                 ret = tldap_find_first_star(val, &star);
1544                 if (!ret) {
1545                         return false;
1546                 }
1547                 chunk_len = star - val;
1548
1549                 switch (*star) {
1550                 case '*':
1551                         if (!initial && chunk_len == 0) {
1552                                 /* found '**', which is illegal */
1553                                 return false;
1554                         }
1555                         break;
1556                 case ')':
1557                         if (initial) {
1558                                 /* no stars ?? */
1559                                 return false;
1560                         }
1561                         /* we are done */
1562                         break;
1563                 default:
1564                         /* ?? */
1565                         return false;
1566                 }
1567
1568                 if (initial && chunk_len == 0) {
1569                         val = star + 1;
1570                         initial = false;
1571                         continue;
1572                 }
1573
1574                 chunk = talloc_strndup(tmpctx, val, chunk_len);
1575                 if (!chunk) {
1576                         return false;
1577                 }
1578                 ret = tldap_unescape_inplace(chunk, &chunk_len);
1579                 if (!ret) {
1580                         return false;
1581                 }
1582                 switch (*star) {
1583                 case '*':
1584                         if (initial) {
1585                                 asn1_push_tag(data, TLDAP_SUB_INI);
1586                                 initial = false;
1587                         } else {
1588                                 asn1_push_tag(data, TLDAP_SUB_ANY);
1589                         }
1590                         break;
1591                 case ')':
1592                         asn1_push_tag(data, TLDAP_SUB_FIN);
1593                         break;
1594                 default:
1595                         /* ?? */
1596                         return false;
1597                 }
1598                 asn1_write(data, chunk, chunk_len);
1599                 asn1_pop_tag(data);
1600
1601                 val = star + 1;
1602
1603         } while (*star == '*');
1604
1605         *_s = star;
1606
1607         /* end of sequence */
1608         asn1_pop_tag(data);
1609         return true;
1610 }
1611
1612 /* NOTE: although openldap libraries allow for spaces in some places, mosly
1613  * around parenthesis, we do not allow any spaces (except in values of
1614  * course) as I couldn't fine any place in RFC 4512 or RFC 4515 where
1615  * leading or trailing spaces where allowed.
1616  */
1617 static bool tldap_push_filter(struct tldap_context *ld,
1618                               struct asn1_data *data,
1619                               const char *filter)
1620 {
1621         const char *s = filter;
1622         bool ret;
1623
1624         ret = tldap_push_filter_int(ld, data, &s);
1625         if (ret && *s) {
1626                 tldap_debug(ld, TLDAP_DEBUG_ERROR,
1627                             "Incomplete or malformed filter\n");
1628                 return false;
1629         }
1630         return ret;
1631 }
1632
1633 /*****************************************************************************/
1634
1635 static void tldap_search_done(struct tevent_req *subreq);
1636
1637 struct tevent_req *tldap_search_send(TALLOC_CTX *mem_ctx,
1638                                      struct tevent_context *ev,
1639                                      struct tldap_context *ld,
1640                                      const char *base, int scope,
1641                                      const char *filter,
1642                                      const char **attrs,
1643                                      int num_attrs,
1644                                      int attrsonly,
1645                                      struct tldap_control *sctrls,
1646                                      int num_sctrls,
1647                                      struct tldap_control *cctrls,
1648                                      int num_cctrls,
1649                                      int timelimit,
1650                                      int sizelimit,
1651                                      int deref)
1652 {
1653         struct tevent_req *req, *subreq;
1654         struct tldap_req_state *state;
1655         int i;
1656
1657         req = tldap_req_create(mem_ctx, ld, &state);
1658         if (req == NULL) {
1659                 return NULL;
1660         }
1661
1662         asn1_push_tag(state->out, TLDAP_REQ_SEARCH);
1663         asn1_write_OctetString(state->out, base, strlen(base));
1664         asn1_write_enumerated(state->out, scope);
1665         asn1_write_enumerated(state->out, deref);
1666         asn1_write_Integer(state->out, sizelimit);
1667         asn1_write_Integer(state->out, timelimit);
1668         asn1_write_BOOLEAN(state->out, attrsonly);
1669
1670         if (!tldap_push_filter(ld, state->out, filter)) {
1671                 goto encoding_error;
1672         }
1673
1674         asn1_push_tag(state->out, ASN1_SEQUENCE(0));
1675         for (i=0; i<num_attrs; i++) {
1676                 asn1_write_OctetString(state->out, attrs[i], strlen(attrs[i]));
1677         }
1678         asn1_pop_tag(state->out);
1679         asn1_pop_tag(state->out);
1680
1681         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
1682                                 sctrls, num_sctrls);
1683         if (tevent_req_nomem(subreq, req)) {
1684                 return tevent_req_post(req, ev);
1685         }
1686         tevent_req_set_callback(subreq, tldap_search_done, req);
1687         return req;
1688
1689  encoding_error:
1690         tevent_req_error(req, TLDAP_ENCODING_ERROR);
1691         return tevent_req_post(req, ev);
1692 }
1693
1694 static void tldap_search_done(struct tevent_req *subreq)
1695 {
1696         struct tevent_req *req = tevent_req_callback_data(
1697                 subreq, struct tevent_req);
1698         struct tldap_req_state *state = tevent_req_data(
1699                 req, struct tldap_req_state);
1700         int err;
1701
1702         err = tldap_msg_recv(subreq, state, &state->result);
1703         if (err != TLDAP_SUCCESS) {
1704                 tevent_req_error(req, err);
1705                 return;
1706         }
1707         switch (state->result->type) {
1708         case TLDAP_RES_SEARCH_ENTRY:
1709         case TLDAP_RES_SEARCH_REFERENCE:
1710                 if (!tldap_msg_set_pending(subreq)) {
1711                         tevent_req_oom(req);
1712                         return;
1713                 }
1714                 tevent_req_notify_callback(req);
1715                 break;
1716         case TLDAP_RES_SEARCH_RESULT:
1717                 TALLOC_FREE(subreq);
1718                 if (!asn1_start_tag(state->result->data,
1719                                     state->result->type) ||
1720                     !tldap_decode_response(state) ||
1721                     !asn1_end_tag(state->result->data) ||
1722                     !tldap_decode_controls(state)) {
1723                         tevent_req_error(req, TLDAP_DECODING_ERROR);
1724                         return;
1725                 }
1726                 tevent_req_done(req);
1727                 break;
1728         default:
1729                 tevent_req_error(req, TLDAP_PROTOCOL_ERROR);
1730                 return;
1731         }
1732 }
1733
1734 int tldap_search_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1735                       struct tldap_message **pmsg)
1736 {
1737         struct tldap_req_state *state = tevent_req_data(
1738                 req, struct tldap_req_state);
1739         int err;
1740
1741         if (!tevent_req_is_in_progress(req)
1742             && tevent_req_is_ldap_error(req, &err)) {
1743                 return err;
1744         }
1745
1746         if (tevent_req_is_in_progress(req)) {
1747                 switch (state->result->type) {
1748                 case TLDAP_RES_SEARCH_ENTRY:
1749                 case TLDAP_RES_SEARCH_REFERENCE:
1750                         break;
1751                 default:
1752                         return TLDAP_OPERATIONS_ERROR;
1753                 }
1754         }
1755
1756         *pmsg = talloc_move(mem_ctx, &state->result);
1757         return TLDAP_SUCCESS;
1758 }
1759
1760 struct tldap_sync_search_state {
1761         TALLOC_CTX *mem_ctx;
1762         struct tldap_message **entries;
1763         struct tldap_message **refs;
1764         int rc;
1765 };
1766
1767 static void tldap_search_cb(struct tevent_req *req)
1768 {
1769         struct tldap_sync_search_state *state =
1770                 (struct tldap_sync_search_state *)
1771                 tevent_req_callback_data_void(req);
1772         struct tldap_message *msg, **tmp;
1773         int rc, num_entries, num_refs;
1774
1775         rc = tldap_search_recv(req, talloc_tos(), &msg);
1776         if (rc != TLDAP_SUCCESS) {
1777                 state->rc = rc;
1778                 return;
1779         }
1780
1781         switch (tldap_msg_type(msg)) {
1782         case TLDAP_RES_SEARCH_ENTRY:
1783                 num_entries = talloc_array_length(state->entries);
1784                 tmp = talloc_realloc(state->mem_ctx, state->entries,
1785                                      struct tldap_message *, num_entries + 1);
1786                 if (tmp == NULL) {
1787                         state->rc = TLDAP_NO_MEMORY;
1788                         return;
1789                 }
1790                 state->entries = tmp;
1791                 state->entries[num_entries] = talloc_move(state->entries,
1792                                                           &msg);
1793                 break;
1794         case TLDAP_RES_SEARCH_REFERENCE:
1795                 num_refs = talloc_array_length(state->refs);
1796                 tmp = talloc_realloc(state->mem_ctx, state->refs,
1797                                      struct tldap_message *, num_refs + 1);
1798                 if (tmp == NULL) {
1799                         state->rc = TLDAP_NO_MEMORY;
1800                         return;
1801                 }
1802                 state->refs = tmp;
1803                 state->refs[num_refs] = talloc_move(state->refs, &msg);
1804                 break;
1805         case TLDAP_RES_SEARCH_RESULT:
1806                 state->rc = TLDAP_SUCCESS;
1807                 break;
1808         default:
1809                 state->rc = TLDAP_PROTOCOL_ERROR;
1810                 break;
1811         }
1812 }
1813
1814 int tldap_search(struct tldap_context *ld,
1815                  const char *base, int scope, const char *filter,
1816                  const char **attrs, int num_attrs, int attrsonly,
1817                  struct tldap_control *sctrls, int num_sctrls,
1818                  struct tldap_control *cctrls, int num_cctrls,
1819                  int timelimit, int sizelimit, int deref,
1820                  TALLOC_CTX *mem_ctx, struct tldap_message ***entries,
1821                  struct tldap_message ***refs)
1822 {
1823         TALLOC_CTX *frame = talloc_stackframe();
1824         struct tevent_context *ev;
1825         struct tevent_req *req;
1826         struct tldap_sync_search_state state;
1827
1828         ZERO_STRUCT(state);
1829         state.mem_ctx = mem_ctx;
1830         state.rc = TLDAP_SUCCESS;
1831
1832         ev = samba_tevent_context_init(frame);
1833         if (ev == NULL) {
1834                 state.rc = TLDAP_NO_MEMORY;
1835                 goto fail;
1836         }
1837
1838         req = tldap_search_send(frame, ev, ld, base, scope, filter,
1839                                 attrs, num_attrs, attrsonly,
1840                                 sctrls, num_sctrls, cctrls, num_cctrls,
1841                                 timelimit, sizelimit, deref);
1842         if (req == NULL) {
1843                 state.rc = TLDAP_NO_MEMORY;
1844                 goto fail;
1845         }
1846
1847         tevent_req_set_callback(req, tldap_search_cb, &state);
1848
1849         if (!tevent_req_is_in_progress(req)) {
1850                 /* an error happend before sending */
1851                 if (tevent_req_is_ldap_error(req, &state.rc)) {
1852                         goto fail;
1853                 }
1854         }
1855
1856         while (tevent_req_is_in_progress(req)
1857                && (state.rc == TLDAP_SUCCESS)) {
1858                 if (tevent_loop_once(ev) == -1) {
1859                         return TLDAP_OPERATIONS_ERROR;
1860                 }
1861         }
1862
1863         if (state.rc != TLDAP_SUCCESS) {
1864                 return state.rc;
1865         }
1866
1867         if (entries != NULL) {
1868                 *entries = state.entries;
1869         } else {
1870                 TALLOC_FREE(state.entries);
1871         }
1872         if (refs != NULL) {
1873                 *refs = state.refs;
1874         } else {
1875                 TALLOC_FREE(state.refs);
1876         }
1877         tldap_save_msg(ld, req);
1878 fail:
1879         TALLOC_FREE(frame);
1880         return state.rc;
1881 }
1882
1883 static bool tldap_parse_search_entry(struct tldap_message *msg)
1884 {
1885         int num_attribs = 0;
1886
1887         asn1_start_tag(msg->data, msg->type);
1888
1889         /* dn */
1890
1891         asn1_read_OctetString_talloc(msg, msg->data, &msg->dn);
1892         if (msg->dn == NULL) {
1893                 return false;
1894         }
1895
1896         /*
1897          * Attributes: We overallocate msg->attribs by one, so that while
1898          * looping over the attributes we can directly parse into the last
1899          * array element. Same for the values in the inner loop.
1900          */
1901
1902         msg->attribs = talloc_array(msg, struct tldap_attribute, 1);
1903         if (msg->attribs == NULL) {
1904                 return false;
1905         }
1906
1907         asn1_start_tag(msg->data, ASN1_SEQUENCE(0));
1908         while (asn1_peek_tag(msg->data, ASN1_SEQUENCE(0))) {
1909                 struct tldap_attribute *attrib;
1910                 int num_values = 0;
1911
1912                 attrib = &msg->attribs[num_attribs];
1913                 attrib->values = talloc_array(msg->attribs, DATA_BLOB, 1);
1914                 if (attrib->values == NULL) {
1915                         return false;
1916                 }
1917                 asn1_start_tag(msg->data, ASN1_SEQUENCE(0));
1918                 asn1_read_OctetString_talloc(msg->attribs, msg->data,
1919                                              &attrib->name);
1920                 asn1_start_tag(msg->data, ASN1_SET);
1921
1922                 while (asn1_peek_tag(msg->data, ASN1_OCTET_STRING)) {
1923                         asn1_read_OctetString(msg->data, msg,
1924                                               &attrib->values[num_values]);
1925
1926                         attrib->values = talloc_realloc(
1927                                 msg->attribs, attrib->values, DATA_BLOB,
1928                                 num_values + 2);
1929                         if (attrib->values == NULL) {
1930                                 return false;
1931                         }
1932                         num_values += 1;
1933                 }
1934                 attrib->values = talloc_realloc(msg->attribs, attrib->values,
1935                                                 DATA_BLOB, num_values);
1936                 attrib->num_values = num_values;
1937
1938                 asn1_end_tag(msg->data); /* ASN1_SET */
1939                 asn1_end_tag(msg->data); /* ASN1_SEQUENCE(0) */
1940                 msg->attribs = talloc_realloc(
1941                         msg, msg->attribs, struct tldap_attribute,
1942                         num_attribs + 2);
1943                 if (msg->attribs == NULL) {
1944                         return false;
1945                 }
1946                 num_attribs += 1;
1947         }
1948         msg->attribs = talloc_realloc(
1949                 msg, msg->attribs, struct tldap_attribute, num_attribs);
1950         asn1_end_tag(msg->data);
1951         if (msg->data->has_error) {
1952                 return false;
1953         }
1954         return true;
1955 }
1956
1957 bool tldap_entry_dn(struct tldap_message *msg, char **dn)
1958 {
1959         if ((msg->dn == NULL) && (!tldap_parse_search_entry(msg))) {
1960                 return false;
1961         }
1962         *dn = msg->dn;
1963         return true;
1964 }
1965
1966 bool tldap_entry_attributes(struct tldap_message *msg,
1967                             struct tldap_attribute **attributes,
1968                             int *num_attributes)
1969 {
1970         if ((msg->dn == NULL) && (!tldap_parse_search_entry(msg))) {
1971                 return false;
1972         }
1973         *attributes = msg->attribs;
1974         *num_attributes = talloc_array_length(msg->attribs);
1975         return true;
1976 }
1977
1978 static bool tldap_decode_controls(struct tldap_req_state *state)
1979 {
1980         struct tldap_message *msg = state->result;
1981         struct asn1_data *data = msg->data;
1982         struct tldap_control *sctrls = NULL;
1983         int num_controls = 0;
1984
1985         msg->res_sctrls = NULL;
1986
1987         if (!asn1_peek_tag(data, ASN1_CONTEXT(0))) {
1988                 return true;
1989         }
1990
1991         asn1_start_tag(data, ASN1_CONTEXT(0));
1992
1993         while (asn1_peek_tag(data, ASN1_SEQUENCE(0))) {
1994                 struct tldap_control *c;
1995                 char *oid = NULL;
1996
1997                 sctrls = talloc_realloc(msg, sctrls, struct tldap_control,
1998                                         num_controls + 1);
1999                 if (sctrls == NULL) {
2000                         return false;
2001                 }
2002                 c = &sctrls[num_controls];
2003
2004                 asn1_start_tag(data, ASN1_SEQUENCE(0));
2005                 asn1_read_OctetString_talloc(msg, data, &oid);
2006                 if ((data->has_error) || (oid == NULL)) {
2007                         return false;
2008                 }
2009                 c->oid = oid;
2010                 if (asn1_peek_tag(data, ASN1_BOOLEAN)) {
2011                         asn1_read_BOOLEAN(data, &c->critical);
2012                 } else {
2013                         c->critical = false;
2014                 }
2015                 c->value = data_blob_null;
2016                 if (asn1_peek_tag(data, ASN1_OCTET_STRING) &&
2017                     !asn1_read_OctetString(data, msg, &c->value)) {
2018                         return false;
2019                 }
2020                 asn1_end_tag(data); /* ASN1_SEQUENCE(0) */
2021
2022                 num_controls += 1;
2023         }
2024
2025         asn1_end_tag(data);     /* ASN1_CONTEXT(0) */
2026
2027         if (data->has_error) {
2028                 TALLOC_FREE(sctrls);
2029                 return false;
2030         }
2031         msg->res_sctrls = sctrls;
2032         return true;
2033 }
2034
2035 static void tldap_simple_done(struct tevent_req *subreq, int type)
2036 {
2037         struct tevent_req *req = tevent_req_callback_data(
2038                 subreq, struct tevent_req);
2039         struct tldap_req_state *state = tevent_req_data(
2040                 req, struct tldap_req_state);
2041         int err;
2042
2043         err = tldap_msg_recv(subreq, state, &state->result);
2044         TALLOC_FREE(subreq);
2045         if (err != TLDAP_SUCCESS) {
2046                 tevent_req_error(req, err);
2047                 return;
2048         }
2049         if (state->result->type != type) {
2050                 tevent_req_error(req, TLDAP_PROTOCOL_ERROR);
2051                 return;
2052         }
2053         if (!asn1_start_tag(state->result->data, state->result->type) ||
2054             !tldap_decode_response(state) ||
2055             !asn1_end_tag(state->result->data) ||
2056             !tldap_decode_controls(state)) {
2057                 tevent_req_error(req, TLDAP_DECODING_ERROR);
2058                 return;
2059         }
2060         if (state->result->lderr != TLDAP_SUCCESS) {
2061                 tevent_req_error(req, state->result->lderr);
2062                 return;
2063         }
2064         tevent_req_done(req);
2065 }
2066
2067 static int tldap_simple_recv(struct tevent_req *req)
2068 {
2069         int err;
2070         if (tevent_req_is_ldap_error(req, &err)) {
2071                 return err;
2072         }
2073         return TLDAP_SUCCESS;
2074 }
2075
2076 static void tldap_add_done(struct tevent_req *subreq);
2077
2078 struct tevent_req *tldap_add_send(TALLOC_CTX *mem_ctx,
2079                                   struct tevent_context *ev,
2080                                   struct tldap_context *ld,
2081                                   const char *dn,
2082                                   struct tldap_mod *attributes,
2083                                   int num_attributes,
2084                                   struct tldap_control *sctrls,
2085                                   int num_sctrls,
2086                                   struct tldap_control *cctrls,
2087                                   int num_cctrls)
2088 {
2089         struct tevent_req *req, *subreq;
2090         struct tldap_req_state *state;
2091         int i, j;
2092
2093         req = tldap_req_create(mem_ctx, ld, &state);
2094         if (req == NULL) {
2095                 return NULL;
2096         }
2097
2098         asn1_push_tag(state->out, TLDAP_REQ_ADD);
2099         asn1_write_OctetString(state->out, dn, strlen(dn));
2100         asn1_push_tag(state->out, ASN1_SEQUENCE(0));
2101
2102         for (i=0; i<num_attributes; i++) {
2103                 struct tldap_mod *attrib = &attributes[i];
2104                 asn1_push_tag(state->out, ASN1_SEQUENCE(0));
2105                 asn1_write_OctetString(state->out, attrib->attribute,
2106                                        strlen(attrib->attribute));
2107                 asn1_push_tag(state->out, ASN1_SET);
2108                 for (j=0; j<attrib->num_values; j++) {
2109                         asn1_write_OctetString(state->out,
2110                                                attrib->values[j].data,
2111                                                attrib->values[j].length);
2112                 }
2113                 asn1_pop_tag(state->out);
2114                 asn1_pop_tag(state->out);
2115         }
2116
2117         asn1_pop_tag(state->out);
2118         asn1_pop_tag(state->out);
2119
2120         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
2121                                 sctrls, num_sctrls);
2122         if (tevent_req_nomem(subreq, req)) {
2123                 return tevent_req_post(req, ev);
2124         }
2125         tevent_req_set_callback(subreq, tldap_add_done, req);
2126         return req;
2127 }
2128
2129 static void tldap_add_done(struct tevent_req *subreq)
2130 {
2131         tldap_simple_done(subreq, TLDAP_RES_ADD);
2132 }
2133
2134 int tldap_add_recv(struct tevent_req *req)
2135 {
2136         return tldap_simple_recv(req);
2137 }
2138
2139 int tldap_add(struct tldap_context *ld, const char *dn,
2140               struct tldap_mod *attributes, int num_attributes,
2141               struct tldap_control *sctrls, int num_sctrls,
2142               struct tldap_control *cctrls, int num_cctrls)
2143 {
2144         TALLOC_CTX *frame = talloc_stackframe();
2145         struct tevent_context *ev;
2146         struct tevent_req *req;
2147         int result;
2148
2149         ev = samba_tevent_context_init(frame);
2150         if (ev == NULL) {
2151                 result = TLDAP_NO_MEMORY;
2152                 goto fail;
2153         }
2154
2155         req = tldap_add_send(frame, ev, ld, dn, attributes, num_attributes,
2156                              sctrls, num_sctrls, cctrls, num_cctrls);
2157         if (req == NULL) {
2158                 result = TLDAP_NO_MEMORY;
2159                 goto fail;
2160         }
2161
2162         if (!tevent_req_poll(req, ev)) {
2163                 result = TLDAP_OPERATIONS_ERROR;
2164                 goto fail;
2165         }
2166
2167         result = tldap_add_recv(req);
2168         tldap_save_msg(ld, req);
2169  fail:
2170         TALLOC_FREE(frame);
2171         return result;
2172 }
2173
2174 static void tldap_modify_done(struct tevent_req *subreq);
2175
2176 struct tevent_req *tldap_modify_send(TALLOC_CTX *mem_ctx,
2177                                      struct tevent_context *ev,
2178                                      struct tldap_context *ld,
2179                                      const char *dn,
2180                                      struct tldap_mod *mods, int num_mods,
2181                                      struct tldap_control *sctrls,
2182                                      int num_sctrls,
2183                                      struct tldap_control *cctrls,
2184                                      int num_cctrls)
2185 {
2186         struct tevent_req *req, *subreq;
2187         struct tldap_req_state *state;
2188         int i, j;
2189
2190         req = tldap_req_create(mem_ctx, ld, &state);
2191         if (req == NULL) {
2192                 return NULL;
2193         }
2194
2195         asn1_push_tag(state->out, TLDAP_REQ_MODIFY);
2196         asn1_write_OctetString(state->out, dn, strlen(dn));
2197         asn1_push_tag(state->out, ASN1_SEQUENCE(0));
2198
2199         for (i=0; i<num_mods; i++) {
2200                 struct tldap_mod *mod = &mods[i];
2201                 asn1_push_tag(state->out, ASN1_SEQUENCE(0));
2202                 asn1_write_enumerated(state->out, mod->mod_op),
2203                 asn1_push_tag(state->out, ASN1_SEQUENCE(0));
2204                 asn1_write_OctetString(state->out, mod->attribute,
2205                                        strlen(mod->attribute));
2206                 asn1_push_tag(state->out, ASN1_SET);
2207                 for (j=0; j<mod->num_values; j++) {
2208                         asn1_write_OctetString(state->out,
2209                                                mod->values[j].data,
2210                                                mod->values[j].length);
2211                 }
2212                 asn1_pop_tag(state->out);
2213                 asn1_pop_tag(state->out);
2214                 asn1_pop_tag(state->out);
2215         }
2216
2217         asn1_pop_tag(state->out);
2218         asn1_pop_tag(state->out);
2219
2220         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
2221                                 sctrls, num_sctrls);
2222         if (tevent_req_nomem(subreq, req)) {
2223                 return tevent_req_post(req, ev);
2224         }
2225         tevent_req_set_callback(subreq, tldap_modify_done, req);
2226         return req;
2227 }
2228
2229 static void tldap_modify_done(struct tevent_req *subreq)
2230 {
2231         tldap_simple_done(subreq, TLDAP_RES_MODIFY);
2232 }
2233
2234 int tldap_modify_recv(struct tevent_req *req)
2235 {
2236         return tldap_simple_recv(req);
2237 }
2238
2239 int tldap_modify(struct tldap_context *ld, const char *dn,
2240                  struct tldap_mod *mods, int num_mods,
2241                  struct tldap_control *sctrls, int num_sctrls,
2242                  struct tldap_control *cctrls, int num_cctrls)
2243  {
2244         TALLOC_CTX *frame = talloc_stackframe();
2245         struct tevent_context *ev;
2246         struct tevent_req *req;
2247         int result;
2248
2249         ev = samba_tevent_context_init(frame);
2250         if (ev == NULL) {
2251                 result = TLDAP_NO_MEMORY;
2252                 goto fail;
2253         }
2254
2255         req = tldap_modify_send(frame, ev, ld, dn, mods, num_mods,
2256                                 sctrls, num_sctrls, cctrls, num_cctrls);
2257         if (req == NULL) {
2258                 result = TLDAP_NO_MEMORY;
2259                 goto fail;
2260         }
2261
2262         if (!tevent_req_poll(req, ev)) {
2263                 result = TLDAP_OPERATIONS_ERROR;
2264                 goto fail;
2265         }
2266
2267         result = tldap_modify_recv(req);
2268         tldap_save_msg(ld, req);
2269  fail:
2270         TALLOC_FREE(frame);
2271         return result;
2272 }
2273
2274 static void tldap_delete_done(struct tevent_req *subreq);
2275
2276 struct tevent_req *tldap_delete_send(TALLOC_CTX *mem_ctx,
2277                                      struct tevent_context *ev,
2278                                      struct tldap_context *ld,
2279                                      const char *dn,
2280                                      struct tldap_control *sctrls,
2281                                      int num_sctrls,
2282                                      struct tldap_control *cctrls,
2283                                      int num_cctrls)
2284 {
2285         struct tevent_req *req, *subreq;
2286         struct tldap_req_state *state;
2287
2288         req = tldap_req_create(mem_ctx, ld, &state);
2289         if (req == NULL) {
2290                 return NULL;
2291         }
2292
2293         asn1_push_tag(state->out, TLDAP_REQ_DELETE);
2294         asn1_write(state->out, dn, strlen(dn));
2295         asn1_pop_tag(state->out);
2296
2297         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
2298                                 sctrls, num_sctrls);
2299         if (tevent_req_nomem(subreq, req)) {
2300                 return tevent_req_post(req, ev);
2301         }
2302         tevent_req_set_callback(subreq, tldap_delete_done, req);
2303         return req;
2304 }
2305
2306 static void tldap_delete_done(struct tevent_req *subreq)
2307 {
2308         tldap_simple_done(subreq, TLDAP_RES_DELETE);
2309 }
2310
2311 int tldap_delete_recv(struct tevent_req *req)
2312 {
2313         return tldap_simple_recv(req);
2314 }
2315
2316 int tldap_delete(struct tldap_context *ld, const char *dn,
2317                  struct tldap_control *sctrls, int num_sctrls,
2318                  struct tldap_control *cctrls, int num_cctrls)
2319 {
2320         TALLOC_CTX *frame = talloc_stackframe();
2321         struct tevent_context *ev;
2322         struct tevent_req *req;
2323         int result;
2324
2325         ev = samba_tevent_context_init(frame);
2326         if (ev == NULL) {
2327                 result = TLDAP_NO_MEMORY;
2328                 goto fail;
2329         }
2330
2331         req = tldap_delete_send(frame, ev, ld, dn, sctrls, num_sctrls,
2332                                 cctrls, num_cctrls);
2333         if (req == NULL) {
2334                 result = TLDAP_NO_MEMORY;
2335                 goto fail;
2336         }
2337
2338         if (!tevent_req_poll(req, ev)) {
2339                 result = TLDAP_OPERATIONS_ERROR;
2340                 goto fail;
2341         }
2342
2343         result = tldap_delete_recv(req);
2344         tldap_save_msg(ld, req);
2345  fail:
2346         TALLOC_FREE(frame);
2347         return result;
2348 }
2349
2350 int tldap_msg_id(const struct tldap_message *msg)
2351 {
2352         return msg->id;
2353 }
2354
2355 int tldap_msg_type(const struct tldap_message *msg)
2356 {
2357         return msg->type;
2358 }
2359
2360 const char *tldap_msg_matcheddn(struct tldap_message *msg)
2361 {
2362         if (msg == NULL) {
2363                 return NULL;
2364         }
2365         return msg->res_matcheddn;
2366 }
2367
2368 const char *tldap_msg_diagnosticmessage(struct tldap_message *msg)
2369 {
2370         if (msg == NULL) {
2371                 return NULL;
2372         }
2373         return msg->res_diagnosticmessage;
2374 }
2375
2376 const char *tldap_msg_referral(struct tldap_message *msg)
2377 {
2378         if (msg == NULL) {
2379                 return NULL;
2380         }
2381         return msg->res_referral;
2382 }
2383
2384 void tldap_msg_sctrls(struct tldap_message *msg, int *num_sctrls,
2385                       struct tldap_control **sctrls)
2386 {
2387         if (msg == NULL) {
2388                 *sctrls = NULL;
2389                 *num_sctrls = 0;
2390                 return;
2391         }
2392         *sctrls = msg->res_sctrls;
2393         *num_sctrls = talloc_array_length(msg->res_sctrls);
2394 }
2395
2396 struct tldap_message *tldap_ctx_lastmsg(struct tldap_context *ld)
2397 {
2398         return ld->last_msg;
2399 }
2400
2401 const char *tldap_err2string(int rc)
2402 {
2403         const char *res = NULL;
2404
2405         /*
2406          * This would normally be a table, but the error codes are not fully
2407          * sequential. Let the compiler figure out the optimum implementation
2408          * :-)
2409          */
2410
2411         switch (rc) {
2412         case TLDAP_SUCCESS:
2413                 res = "TLDAP_SUCCESS";
2414                 break;
2415         case TLDAP_OPERATIONS_ERROR:
2416                 res = "TLDAP_OPERATIONS_ERROR";
2417                 break;
2418         case TLDAP_PROTOCOL_ERROR:
2419                 res = "TLDAP_PROTOCOL_ERROR";
2420                 break;
2421         case TLDAP_TIMELIMIT_EXCEEDED:
2422                 res = "TLDAP_TIMELIMIT_EXCEEDED";
2423                 break;
2424         case TLDAP_SIZELIMIT_EXCEEDED:
2425                 res = "TLDAP_SIZELIMIT_EXCEEDED";
2426                 break;
2427         case TLDAP_COMPARE_FALSE:
2428                 res = "TLDAP_COMPARE_FALSE";
2429                 break;
2430         case TLDAP_COMPARE_TRUE:
2431                 res = "TLDAP_COMPARE_TRUE";
2432                 break;
2433         case TLDAP_STRONG_AUTH_NOT_SUPPORTED:
2434                 res = "TLDAP_STRONG_AUTH_NOT_SUPPORTED";
2435                 break;
2436         case TLDAP_STRONG_AUTH_REQUIRED:
2437                 res = "TLDAP_STRONG_AUTH_REQUIRED";
2438                 break;
2439         case TLDAP_REFERRAL:
2440                 res = "TLDAP_REFERRAL";
2441                 break;
2442         case TLDAP_ADMINLIMIT_EXCEEDED:
2443                 res = "TLDAP_ADMINLIMIT_EXCEEDED";
2444                 break;
2445         case TLDAP_UNAVAILABLE_CRITICAL_EXTENSION:
2446                 res = "TLDAP_UNAVAILABLE_CRITICAL_EXTENSION";
2447                 break;
2448         case TLDAP_CONFIDENTIALITY_REQUIRED:
2449                 res = "TLDAP_CONFIDENTIALITY_REQUIRED";
2450                 break;
2451         case TLDAP_SASL_BIND_IN_PROGRESS:
2452                 res = "TLDAP_SASL_BIND_IN_PROGRESS";
2453                 break;
2454         case TLDAP_NO_SUCH_ATTRIBUTE:
2455                 res = "TLDAP_NO_SUCH_ATTRIBUTE";
2456                 break;
2457         case TLDAP_UNDEFINED_TYPE:
2458                 res = "TLDAP_UNDEFINED_TYPE";
2459                 break;
2460         case TLDAP_INAPPROPRIATE_MATCHING:
2461                 res = "TLDAP_INAPPROPRIATE_MATCHING";
2462                 break;
2463         case TLDAP_CONSTRAINT_VIOLATION:
2464                 res = "TLDAP_CONSTRAINT_VIOLATION";
2465                 break;
2466         case TLDAP_TYPE_OR_VALUE_EXISTS:
2467                 res = "TLDAP_TYPE_OR_VALUE_EXISTS";
2468                 break;
2469         case TLDAP_INVALID_SYNTAX:
2470                 res = "TLDAP_INVALID_SYNTAX";
2471                 break;
2472         case TLDAP_NO_SUCH_OBJECT:
2473                 res = "TLDAP_NO_SUCH_OBJECT";
2474                 break;
2475         case TLDAP_ALIAS_PROBLEM:
2476                 res = "TLDAP_ALIAS_PROBLEM";
2477                 break;
2478         case TLDAP_INVALID_DN_SYNTAX:
2479                 res = "TLDAP_INVALID_DN_SYNTAX";
2480                 break;
2481         case TLDAP_IS_LEAF:
2482                 res = "TLDAP_IS_LEAF";
2483                 break;
2484         case TLDAP_ALIAS_DEREF_PROBLEM:
2485                 res = "TLDAP_ALIAS_DEREF_PROBLEM";
2486                 break;
2487         case TLDAP_INAPPROPRIATE_AUTH:
2488                 res = "TLDAP_INAPPROPRIATE_AUTH";
2489                 break;
2490         case TLDAP_INVALID_CREDENTIALS:
2491                 res = "TLDAP_INVALID_CREDENTIALS";
2492                 break;
2493         case TLDAP_INSUFFICIENT_ACCESS:
2494                 res = "TLDAP_INSUFFICIENT_ACCESS";
2495                 break;
2496         case TLDAP_BUSY:
2497                 res = "TLDAP_BUSY";
2498                 break;
2499         case TLDAP_UNAVAILABLE:
2500                 res = "TLDAP_UNAVAILABLE";
2501                 break;
2502         case TLDAP_UNWILLING_TO_PERFORM:
2503                 res = "TLDAP_UNWILLING_TO_PERFORM";
2504                 break;
2505         case TLDAP_LOOP_DETECT:
2506                 res = "TLDAP_LOOP_DETECT";
2507                 break;
2508         case TLDAP_NAMING_VIOLATION:
2509                 res = "TLDAP_NAMING_VIOLATION";
2510                 break;
2511         case TLDAP_OBJECT_CLASS_VIOLATION:
2512                 res = "TLDAP_OBJECT_CLASS_VIOLATION";
2513                 break;
2514         case TLDAP_NOT_ALLOWED_ON_NONLEAF:
2515                 res = "TLDAP_NOT_ALLOWED_ON_NONLEAF";
2516                 break;
2517         case TLDAP_NOT_ALLOWED_ON_RDN:
2518                 res = "TLDAP_NOT_ALLOWED_ON_RDN";
2519                 break;
2520         case TLDAP_ALREADY_EXISTS:
2521                 res = "TLDAP_ALREADY_EXISTS";
2522                 break;
2523         case TLDAP_NO_OBJECT_CLASS_MODS:
2524                 res = "TLDAP_NO_OBJECT_CLASS_MODS";
2525                 break;
2526         case TLDAP_RESULTS_TOO_LARGE:
2527                 res = "TLDAP_RESULTS_TOO_LARGE";
2528                 break;
2529         case TLDAP_AFFECTS_MULTIPLE_DSAS:
2530                 res = "TLDAP_AFFECTS_MULTIPLE_DSAS";
2531                 break;
2532         case TLDAP_OTHER:
2533                 res = "TLDAP_OTHER";
2534                 break;
2535         case TLDAP_SERVER_DOWN:
2536                 res = "TLDAP_SERVER_DOWN";
2537                 break;
2538         case TLDAP_LOCAL_ERROR:
2539                 res = "TLDAP_LOCAL_ERROR";
2540                 break;
2541         case TLDAP_ENCODING_ERROR:
2542                 res = "TLDAP_ENCODING_ERROR";
2543                 break;
2544         case TLDAP_DECODING_ERROR:
2545                 res = "TLDAP_DECODING_ERROR";
2546                 break;
2547         case TLDAP_TIMEOUT:
2548                 res = "TLDAP_TIMEOUT";
2549                 break;
2550         case TLDAP_AUTH_UNKNOWN:
2551                 res = "TLDAP_AUTH_UNKNOWN";
2552                 break;
2553         case TLDAP_FILTER_ERROR:
2554                 res = "TLDAP_FILTER_ERROR";
2555                 break;
2556         case TLDAP_USER_CANCELLED:
2557                 res = "TLDAP_USER_CANCELLED";
2558                 break;
2559         case TLDAP_PARAM_ERROR:
2560                 res = "TLDAP_PARAM_ERROR";
2561                 break;
2562         case TLDAP_NO_MEMORY:
2563                 res = "TLDAP_NO_MEMORY";
2564                 break;
2565         case TLDAP_CONNECT_ERROR:
2566                 res = "TLDAP_CONNECT_ERROR";
2567                 break;
2568         case TLDAP_NOT_SUPPORTED:
2569                 res = "TLDAP_NOT_SUPPORTED";
2570                 break;
2571         case TLDAP_CONTROL_NOT_FOUND:
2572                 res = "TLDAP_CONTROL_NOT_FOUND";
2573                 break;
2574         case TLDAP_NO_RESULTS_RETURNED:
2575                 res = "TLDAP_NO_RESULTS_RETURNED";
2576                 break;
2577         case TLDAP_MORE_RESULTS_TO_RETURN:
2578                 res = "TLDAP_MORE_RESULTS_TO_RETURN";
2579                 break;
2580         case TLDAP_CLIENT_LOOP:
2581                 res = "TLDAP_CLIENT_LOOP";
2582                 break;
2583         case TLDAP_REFERRAL_LIMIT_EXCEEDED:
2584                 res = "TLDAP_REFERRAL_LIMIT_EXCEEDED";
2585                 break;
2586         default:
2587                 res = talloc_asprintf(talloc_tos(), "Unknown LDAP Error (%d)",
2588                                       rc);
2589                 break;
2590         }
2591         if (res == NULL) {
2592                 res = "Unknown LDAP Error";
2593         }
2594         return res;
2595 }