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