Move asn1_load_nocopy() to lib/util/asn1.c
[samba.git] / source3 / lib / tldap.c
1 /*
2    Unix SMB/CIFS implementation.
3    Infrastructure for async ldap client requests
4    Copyright (C) Volker Lendecke 2009
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21
22 bool tevent_req_is_ldap_error(struct tevent_req *req, int *perr)
23 {
24         enum tevent_req_state state;
25         uint64_t err;
26
27         if (!tevent_req_is_error(req, &state, &err)) {
28                 return false;
29         }
30         switch (state) {
31         case TEVENT_REQ_TIMED_OUT:
32                 *perr = TLDAP_TIMEOUT;
33                 break;
34         case TEVENT_REQ_NO_MEMORY:
35                 *perr = TLDAP_NO_MEMORY;
36                 break;
37         case TEVENT_REQ_USER_ERROR:
38                 *perr = err;
39                 break;
40         default:
41                 *perr = TLDAP_OPERATIONS_ERROR;
42                 break;
43         }
44         return true;
45 }
46
47 struct tldap_ctx_attribute {
48         char *name;
49         void *ptr;
50 };
51
52 struct tldap_context {
53         int ld_version;
54         int ld_deref;
55         int ld_sizelimit;
56         int ld_timelimit;
57         int fd;
58         int msgid;
59         struct tevent_queue *outgoing;
60         struct tevent_req **pending;
61
62         /* For the sync wrappers we need something like get_last_error... */
63         int lderr;
64         char *res_matcheddn;
65         char *res_diagnosticmessage;
66         char *res_referral;
67         struct tldap_control *res_sctrls;
68
69         /* debug */
70         void (*log_fn)(void *context, enum tldap_debug_level level,
71                        const char *fmt, va_list ap);
72         void *log_private;
73
74         struct tldap_ctx_attribute *ctx_attrs;
75 };
76
77 struct tldap_message {
78         struct asn1_data *data;
79         uint8_t *inbuf;
80         int type;
81         int id;
82
83         /* RESULT_ENTRY */
84         char *dn;
85         struct tldap_attribute *attribs;
86 };
87
88 void tldap_set_debug(struct tldap_context *ld,
89                      void (*log_fn)(void *log_private,
90                                     enum tldap_debug_level level,
91                                     const char *fmt,
92                                     va_list ap) PRINTF_ATTRIBUTE(3,0),
93                      void *log_private)
94 {
95         ld->log_fn = log_fn;
96         ld->log_private = log_private;
97 }
98
99 static void tldap_debug(struct tldap_context *ld,
100                          enum tldap_debug_level level,
101                          const char *fmt, ...)
102 {
103         va_list ap;
104         if (!ld) {
105                 return;
106         }
107         if (ld->log_fn == NULL) {
108                 return;
109         }
110         va_start(ap, fmt);
111         ld->log_fn(ld->log_private, level, fmt, ap);
112         va_end(ap);
113 }
114
115 static int tldap_next_msgid(struct tldap_context *ld)
116 {
117         int result;
118
119         result = ld->msgid++;
120         if (ld->msgid == 2147483647) {
121                 ld->msgid = 1;
122         }
123         return result;
124 }
125
126 struct tldap_context *tldap_context_create(TALLOC_CTX *mem_ctx, int fd)
127 {
128         struct tldap_context *ctx;
129
130         ctx = talloc_zero(mem_ctx, struct tldap_context);
131         if (ctx == NULL) {
132                 return NULL;
133         }
134         ctx->fd = fd;
135         ctx->msgid = 1;
136         ctx->ld_version = 3;
137         ctx->outgoing = tevent_queue_create(ctx, "tldap_outgoing");
138         if (ctx->outgoing == NULL) {
139                 TALLOC_FREE(ctx);
140                 return NULL;
141         }
142         return ctx;
143 }
144
145 static struct tldap_ctx_attribute *tldap_context_findattr(
146         struct tldap_context *ld, const char *name)
147 {
148         int i, num_attrs;
149
150         num_attrs = talloc_array_length(ld->ctx_attrs);
151
152         for (i=0; i<num_attrs; i++) {
153                 if (strcmp(ld->ctx_attrs[i].name, name) == 0) {
154                         return &ld->ctx_attrs[i];
155                 }
156         }
157         return NULL;
158 }
159
160 bool tldap_context_setattr(struct tldap_context *ld,
161                            const char *name, const void *_pptr)
162 {
163         struct tldap_ctx_attribute *tmp, *attr;
164         char *tmpname;
165         int num_attrs;
166         void **pptr = (void **)_pptr;
167
168         attr = tldap_context_findattr(ld, name);
169         if (attr != NULL) {
170                 /*
171                  * We don't actually delete attrs, we don't expect tons of
172                  * attributes being shuffled around.
173                  */
174                 TALLOC_FREE(attr->ptr);
175                 if (*pptr != NULL) {
176                         attr->ptr = talloc_move(ld->ctx_attrs, pptr);
177                         *pptr = NULL;
178                 }
179                 return true;
180         }
181
182         tmpname = talloc_strdup(ld, name);
183         if (tmpname == NULL) {
184                 return false;
185         }
186
187         num_attrs = talloc_array_length(ld->ctx_attrs);
188
189         tmp = talloc_realloc(ld, ld->ctx_attrs, struct tldap_ctx_attribute,
190                              num_attrs+1);
191         if (tmp == NULL) {
192                 TALLOC_FREE(tmpname);
193                 return false;
194         }
195         tmp[num_attrs].name = talloc_move(tmp, &tmpname);
196         if (*pptr != NULL) {
197                 tmp[num_attrs].ptr = talloc_move(tmp, pptr);
198         } else {
199                 tmp[num_attrs].ptr = NULL;
200         }
201         *pptr = NULL;
202         ld->ctx_attrs = tmp;
203         return true;
204 }
205
206 void *tldap_context_getattr(struct tldap_context *ld, const char *name)
207 {
208         struct tldap_ctx_attribute *attr = tldap_context_findattr(ld, name);
209
210         if (attr == NULL) {
211                 return NULL;
212         }
213         return attr->ptr;
214 }
215
216 struct read_ldap_state {
217         uint8_t *buf;
218         bool done;
219 };
220
221 static ssize_t read_ldap_more(uint8_t *buf, size_t buflen, void *private_data)
222 {
223         struct read_ldap_state *state = talloc_get_type_abort(
224                 private_data, struct read_ldap_state);
225         size_t len;
226         int i, lensize;
227
228         if (state->done) {
229                 /* We've been here, we're done */
230                 return 0;
231         }
232
233         /*
234          * From ldap.h: LDAP_TAG_MESSAGE is 0x30
235          */
236         if (buf[0] != 0x30) {
237                 return -1;
238         }
239
240         len = buf[1];
241         if ((len & 0x80) == 0) {
242                 state->done = true;
243                 return len;
244         }
245
246         lensize = (len & 0x7f);
247         len = 0;
248
249         if (buflen == 2) {
250                 /* Please get us the full length */
251                 return lensize;
252         }
253         if (buflen > 2 + lensize) {
254                 state->done = true;
255                 return 0;
256         }
257         if (buflen != 2 + lensize) {
258                 return -1;
259         }
260
261         for (i=0; i<lensize; i++) {
262                 len = (len << 8) | buf[2+i];
263         }
264         return len;
265 }
266
267 static void read_ldap_done(struct tevent_req *subreq);
268
269 static struct tevent_req *read_ldap_send(TALLOC_CTX *mem_ctx,
270                                          struct tevent_context *ev,
271                                          int fd)
272 {
273         struct tevent_req *req, *subreq;
274         struct read_ldap_state *state;
275
276         req = tevent_req_create(mem_ctx, &state, struct read_ldap_state);
277         if (req == NULL) {
278                 return NULL;
279         }
280         state->done = false;
281
282         subreq = read_packet_send(state, ev, fd, 2, read_ldap_more, state);
283         if (tevent_req_nomem(subreq, req)) {
284                 return tevent_req_post(req, ev);
285         }
286         tevent_req_set_callback(subreq, read_ldap_done, req);
287         return req;
288 }
289
290 static void read_ldap_done(struct tevent_req *subreq)
291 {
292         struct tevent_req *req = tevent_req_callback_data(
293                 subreq, struct tevent_req);
294         struct read_ldap_state *state = tevent_req_data(
295                 req, struct read_ldap_state);
296         ssize_t nread;
297         int err;
298
299         nread = read_packet_recv(subreq, state, &state->buf, &err);
300         TALLOC_FREE(subreq);
301         if (nread == -1) {
302                 tevent_req_error(req, err);
303                 return;
304         }
305         tevent_req_done(req);
306 }
307
308 static ssize_t read_ldap_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
309                               uint8_t **pbuf, int *perrno)
310 {
311         struct read_ldap_state *state = tevent_req_data(
312                 req, struct read_ldap_state);
313
314         if (tevent_req_is_unix_error(req, perrno)) {
315                 return -1;
316         }
317         *pbuf = talloc_move(mem_ctx, &state->buf);
318         return talloc_get_size(*pbuf);
319 }
320
321 struct tldap_msg_state {
322         struct tldap_context *ld;
323         struct tevent_context *ev;
324         int id;
325         struct iovec iov;
326
327         struct asn1_data *data;
328         uint8_t *inbuf;
329 };
330
331 static void tldap_push_controls(struct asn1_data *data,
332                                 struct tldap_control *sctrls,
333                                 int num_sctrls)
334 {
335         int i;
336
337         if ((sctrls == NULL) || (num_sctrls == 0)) {
338                 return;
339         }
340
341         asn1_push_tag(data, ASN1_CONTEXT(0));
342
343         for (i=0; i<num_sctrls; i++) {
344                 struct tldap_control *c = &sctrls[i];
345                 asn1_push_tag(data, ASN1_SEQUENCE(0));
346                 asn1_write_OctetString(data, c->oid, strlen(c->oid));
347                 if (c->critical) {
348                         asn1_write_BOOLEAN(data, true);
349                 }
350                 if (c->value.data != NULL) {
351                         asn1_write_OctetString(data, c->value.data,
352                                                c->value.length);
353                 }
354                 asn1_pop_tag(data); /* ASN1_SEQUENCE(0) */
355         }
356
357         asn1_pop_tag(data); /* ASN1_CONTEXT(0) */
358 }
359
360 static void tldap_msg_sent(struct tevent_req *subreq);
361 static void tldap_msg_received(struct tevent_req *subreq);
362
363 static struct tevent_req *tldap_msg_send(TALLOC_CTX *mem_ctx,
364                                          struct tevent_context *ev,
365                                          struct tldap_context *ld,
366                                          int id, struct asn1_data *data,
367                                          struct tldap_control *sctrls,
368                                          int num_sctrls)
369 {
370         struct tevent_req *req, *subreq;
371         struct tldap_msg_state *state;
372         DATA_BLOB blob;
373
374         tldap_debug(ld, TLDAP_DEBUG_TRACE, "tldap_msg_send: sending msg %d\n",
375                     id);
376
377         req = tevent_req_create(mem_ctx, &state, struct tldap_msg_state);
378         if (req == NULL) {
379                 return NULL;
380         }
381         state->ld = ld;
382         state->ev = ev;
383         state->id = id;
384
385         tldap_push_controls(data, sctrls, num_sctrls);
386
387         asn1_pop_tag(data);
388
389         if (!asn1_blob(data, &blob)) {
390                 tevent_req_error(req, TLDAP_ENCODING_ERROR);
391                 return tevent_req_post(req, ev);
392         }
393
394         state->iov.iov_base = blob.data;
395         state->iov.iov_len = blob.length;
396
397         subreq = writev_send(state, ev, ld->outgoing, ld->fd, false,
398                              &state->iov, 1);
399         if (tevent_req_nomem(subreq, req)) {
400                 return tevent_req_post(req, ev);
401         }
402         tevent_req_set_callback(subreq, tldap_msg_sent, req);
403         return req;
404 }
405
406 static void tldap_msg_unset_pending(struct tevent_req *req)
407 {
408         struct tldap_msg_state *state = tevent_req_data(
409                 req, struct tldap_msg_state);
410         struct tldap_context *ld = state->ld;
411         int num_pending = talloc_array_length(ld->pending);
412         int i;
413
414         if (num_pending == 1) {
415                 TALLOC_FREE(ld->pending);
416                 return;
417         }
418
419         for (i=0; i<num_pending; i++) {
420                 if (req == ld->pending[i]) {
421                         break;
422                 }
423         }
424         if (i == num_pending) {
425                 /*
426                  * Something's seriously broken. Just returning here is the
427                  * right thing nevertheless, the point of this routine is to
428                  * remove ourselves from cli->pending.
429                  */
430                 return;
431         }
432
433         /*
434          * Remove ourselves from the cli->pending array
435          */
436         if (num_pending > 1) {
437                 ld->pending[i] = ld->pending[num_pending-1];
438         }
439
440         /*
441          * No NULL check here, we're shrinking by sizeof(void *), and
442          * talloc_realloc just adjusts the size for this.
443          */
444         ld->pending = talloc_realloc(NULL, ld->pending, struct tevent_req *,
445                                      num_pending - 1);
446         return;
447 }
448
449 static int tldap_msg_destructor(struct tevent_req *req)
450 {
451         tldap_msg_unset_pending(req);
452         return 0;
453 }
454
455 static bool tldap_msg_set_pending(struct tevent_req *req)
456 {
457         struct tldap_msg_state *state = tevent_req_data(
458                 req, struct tldap_msg_state);
459         struct tldap_context *ld;
460         struct tevent_req **pending;
461         int num_pending;
462         struct tevent_req *subreq;
463
464         ld = state->ld;
465         num_pending = talloc_array_length(ld->pending);
466
467         pending = talloc_realloc(ld, ld->pending, struct tevent_req *,
468                                  num_pending+1);
469         if (pending == NULL) {
470                 return false;
471         }
472         pending[num_pending] = req;
473         ld->pending = pending;
474         talloc_set_destructor(req, tldap_msg_destructor);
475
476         if (num_pending > 0) {
477                 return true;
478         }
479
480         /*
481          * We're the first ones, add the read_ldap request that waits for the
482          * answer from the server
483          */
484         subreq = read_ldap_send(ld->pending, state->ev, ld->fd);
485         if (subreq == NULL) {
486                 tldap_msg_unset_pending(req);
487                 return false;
488         }
489         tevent_req_set_callback(subreq, tldap_msg_received, ld);
490         return true;
491 }
492
493 static void tldap_msg_sent(struct tevent_req *subreq)
494 {
495         struct tevent_req *req = tevent_req_callback_data(
496                 subreq, struct tevent_req);
497         ssize_t nwritten;
498         int err;
499
500         nwritten = writev_recv(subreq, &err);
501         TALLOC_FREE(subreq);
502         if (nwritten == -1) {
503                 tevent_req_error(req, TLDAP_SERVER_DOWN);
504                 return;
505         }
506
507         if (!tldap_msg_set_pending(req)) {
508                 tevent_req_nomem(NULL, req);
509                 return;
510         }
511 }
512
513 static int tldap_msg_msgid(struct tevent_req *req)
514 {
515         struct tldap_msg_state *state = tevent_req_data(
516                 req, struct tldap_msg_state);
517
518         return state->id;
519 }
520
521 static void tldap_msg_received(struct tevent_req *subreq)
522 {
523         struct tldap_context *ld = tevent_req_callback_data(
524                 subreq, struct tldap_context);
525         struct tevent_req *req;
526         struct tldap_msg_state *state;
527         struct tevent_context *ev;
528         struct asn1_data *data;
529         uint8_t *inbuf;
530         ssize_t received;
531         size_t num_pending;
532         int i, err, status;
533         int id;
534         uint8_t type;
535         bool ok;
536
537         received = read_ldap_recv(subreq, talloc_tos(), &inbuf, &err);
538         TALLOC_FREE(subreq);
539         if (received == -1) {
540                 status = TLDAP_SERVER_DOWN;
541                 goto fail;
542         }
543
544         data = asn1_init(talloc_tos());
545         if (data == NULL) {
546                 status = TLDAP_NO_MEMORY;
547                 goto fail;
548         }
549         asn1_load_nocopy(data, inbuf, received);
550
551         ok = true;
552         ok &= asn1_start_tag(data, ASN1_SEQUENCE(0));
553         ok &= asn1_read_Integer(data, &id);
554         ok &= asn1_peek_uint8(data, &type);
555
556         if (!ok) {
557                 status = TLDAP_PROTOCOL_ERROR;
558                 goto fail;
559         }
560
561         tldap_debug(ld, TLDAP_DEBUG_TRACE, "tldap_msg_received: got msg %d "
562                     "type %d\n", id, (int)type);
563
564         num_pending = talloc_array_length(ld->pending);
565
566         for (i=0; i<num_pending; i++) {
567                 if (id == tldap_msg_msgid(ld->pending[i])) {
568                         break;
569                 }
570         }
571         if (i == num_pending) {
572                 /* Dump unexpected reply */
573                 tldap_debug(ld, TLDAP_DEBUG_WARNING, "tldap_msg_received: "
574                             "No request pending for msg %d\n", id);
575                 TALLOC_FREE(inbuf);
576                 goto done;
577         }
578
579         req = ld->pending[i];
580         state = tevent_req_data(req, struct tldap_msg_state);
581
582         state->inbuf = talloc_move(state, &inbuf);
583         state->data = talloc_move(state, &data);
584
585         ev = state->ev;
586
587         talloc_set_destructor(req, NULL);
588         tldap_msg_destructor(req);
589         tevent_req_done(req);
590
591  done:
592         if (talloc_array_length(ld->pending) > 0) {
593                 state = tevent_req_data(ld->pending[0],
594                                         struct tldap_msg_state);
595                 subreq = read_ldap_send(ld->pending, state->ev, ld->fd);
596                 if (subreq == NULL) {
597                         status = TLDAP_NO_MEMORY;
598                         goto fail;
599                 }
600                 tevent_req_set_callback(subreq, tldap_msg_received, ld);
601         }
602         return;
603
604  fail:
605         while (talloc_array_length(ld->pending) > 0) {
606                 req = ld->pending[0];
607                 talloc_set_destructor(req, NULL);
608                 tldap_msg_destructor(req);
609                 tevent_req_error(req, status);
610         }
611 }
612
613 static int tldap_msg_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
614                           struct tldap_message **pmsg)
615 {
616         struct tldap_msg_state *state = tevent_req_data(
617                 req, struct tldap_msg_state);
618         struct tldap_message *msg;
619         int err;
620         uint8_t msgtype;
621
622         if (tevent_req_is_ldap_error(req, &err)) {
623                 return err;
624         }
625
626         if (!asn1_peek_uint8(state->data, &msgtype)) {
627                 return TLDAP_PROTOCOL_ERROR;
628         }
629
630         if (pmsg == NULL) {
631                 return TLDAP_SUCCESS;
632         }
633
634         msg = talloc_zero(mem_ctx, struct tldap_message);
635         if (msg == NULL) {
636                 return TLDAP_NO_MEMORY;
637         }
638         msg->id = state->id;
639
640         msg->inbuf = talloc_move(msg, &state->inbuf);
641         msg->data = talloc_move(msg, &state->data);
642         msg->type = msgtype;
643
644         *pmsg = msg;
645         return TLDAP_SUCCESS;
646 }
647
648 struct tldap_req_state {
649         int id;
650         struct asn1_data *out;
651         struct tldap_message *result;
652
653         int lderr;
654         char *res_matcheddn;
655         char *res_diagnosticmessage;
656         char *res_referral;
657         struct tldap_control *res_sctrls;
658 };
659
660 static struct tevent_req *tldap_req_create(TALLOC_CTX *mem_ctx,
661                                            struct tldap_context *ld,
662                                            struct tldap_req_state **pstate)
663 {
664         struct tevent_req *req;
665         struct tldap_req_state *state;
666
667         req = tevent_req_create(mem_ctx, &state, struct tldap_req_state);
668         if (req == NULL) {
669                 return NULL;
670         }
671         ZERO_STRUCTP(state);
672         state->out = asn1_init(state);
673         if (state->out == NULL) {
674                 TALLOC_FREE(req);
675                 return NULL;
676         }
677         state->result = NULL;
678         state->id = tldap_next_msgid(ld);
679
680         asn1_push_tag(state->out, ASN1_SEQUENCE(0));
681         asn1_write_Integer(state->out, state->id);
682
683         *pstate = state;
684         return req;
685 }
686
687 static void tldap_save_errors(struct tldap_context *ctx,
688                               struct tevent_req *req)
689 {
690         struct tldap_req_state *state = tevent_req_data(
691                 req, struct tldap_req_state);
692
693         TALLOC_FREE(ctx->res_matcheddn);
694         TALLOC_FREE(ctx->res_diagnosticmessage);
695         TALLOC_FREE(ctx->res_referral);
696         TALLOC_FREE(ctx->res_sctrls);
697
698         ctx->lderr = state->lderr;
699         ctx->res_matcheddn = talloc_move(ctx, &state->res_matcheddn);
700         ctx->res_diagnosticmessage = talloc_move(
701                 ctx, &state->res_diagnosticmessage);
702         ctx->res_referral = talloc_move(ctx, &state->res_referral);
703         ctx->res_sctrls = talloc_move(ctx, &state->res_sctrls);
704 }
705
706 static char *blob2string_talloc(TALLOC_CTX *mem_ctx, DATA_BLOB blob)
707 {
708         char *result = talloc_array(mem_ctx, char, blob.length+1);
709         memcpy(result, blob.data, blob.length);
710         result[blob.length] = '\0';
711         return result;
712 }
713
714 static bool asn1_read_OctetString_talloc(TALLOC_CTX *mem_ctx,
715                                          struct asn1_data *data,
716                                          char **result)
717 {
718         DATA_BLOB string;
719         if (!asn1_read_OctetString(data, mem_ctx, &string))
720                 return false;
721         *result = blob2string_talloc(mem_ctx, string);
722         data_blob_free(&string);
723         return true;
724 }
725
726 static bool tldap_decode_response(struct tldap_req_state *state)
727 {
728         struct asn1_data *data = state->result->data;
729         bool ok = true;
730
731         ok &= asn1_read_enumerated(data, &state->lderr);
732         ok &= asn1_read_OctetString_talloc(state, data, &state->res_matcheddn);
733         ok &= asn1_read_OctetString_talloc(state, data,
734                                            &state->res_diagnosticmessage);
735         if (asn1_peek_tag(data, ASN1_CONTEXT(3))) {
736                 ok &= asn1_start_tag(data, ASN1_CONTEXT(3));
737                 ok &= asn1_read_OctetString_talloc(
738                         state, data, &state->res_referral);
739                 ok &= asn1_end_tag(data);
740         } else {
741                 state->res_referral = NULL;
742         }
743
744         return ok;
745 }
746
747 static void tldap_sasl_bind_done(struct tevent_req *subreq);
748
749 struct tevent_req *tldap_sasl_bind_send(TALLOC_CTX *mem_ctx,
750                                         struct tevent_context *ev,
751                                         struct tldap_context *ld,
752                                         const char *dn,
753                                         const char *mechanism,
754                                         DATA_BLOB *creds,
755                                         struct tldap_control *sctrls,
756                                         int num_sctrls,
757                                         struct tldap_control *cctrls,
758                                         int num_cctrls)
759 {
760         struct tevent_req *req, *subreq;
761         struct tldap_req_state *state;
762
763         req = tldap_req_create(mem_ctx, ld, &state);
764         if (req == NULL) {
765                 return NULL;
766         }
767
768         if (dn == NULL) {
769                 dn = "";
770         }
771
772         asn1_push_tag(state->out, TLDAP_REQ_BIND);
773         asn1_write_Integer(state->out, ld->ld_version);
774         asn1_write_OctetString(state->out, dn, (dn != NULL) ? strlen(dn) : 0);
775
776         if (mechanism == NULL) {
777                 asn1_push_tag(state->out, ASN1_CONTEXT_SIMPLE(0));
778                 asn1_write(state->out, creds->data, creds->length);
779                 asn1_pop_tag(state->out);
780         } else {
781                 asn1_push_tag(state->out, ASN1_CONTEXT(3));
782                 asn1_write_OctetString(state->out, mechanism,
783                                        strlen(mechanism));
784                 if ((creds != NULL) && (creds->data != NULL)) {
785                         asn1_write_OctetString(state->out, creds->data,
786                                                creds->length);
787                 }
788                 asn1_pop_tag(state->out);
789         }
790
791         if (!asn1_pop_tag(state->out)) {
792                 tevent_req_error(req, TLDAP_ENCODING_ERROR);
793                 return tevent_req_post(req, ev);
794         }
795
796         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
797                                 sctrls, num_sctrls);
798         if (tevent_req_nomem(subreq, req)) {
799                 return tevent_req_post(req, ev);
800         }
801         tevent_req_set_callback(subreq, tldap_sasl_bind_done, req);
802         return req;
803 }
804
805 static void tldap_sasl_bind_done(struct tevent_req *subreq)
806 {
807         struct tevent_req *req = tevent_req_callback_data(
808                 subreq, struct tevent_req);
809         struct tldap_req_state *state = tevent_req_data(
810                 req, struct tldap_req_state);
811         int err;
812
813         err = tldap_msg_recv(subreq, state, &state->result);
814         TALLOC_FREE(subreq);
815         if (err != TLDAP_SUCCESS) {
816                 tevent_req_error(req, err);
817                 return;
818         }
819         if (state->result->type != TLDAP_RES_BIND) {
820                 tevent_req_error(req, TLDAP_PROTOCOL_ERROR);
821                 return;
822         }
823         if (!asn1_start_tag(state->result->data, state->result->type) ||
824             !tldap_decode_response(state) ||
825             !asn1_end_tag(state->result->data)) {
826                 tevent_req_error(req, TLDAP_DECODING_ERROR);
827                 return;
828         }
829         /*
830          * TODO: pull the reply blob
831          */
832         if (state->lderr != TLDAP_SUCCESS) {
833                 tevent_req_error(req, state->lderr);
834                 return;
835         }
836         tevent_req_done(req);
837 }
838
839 int tldap_sasl_bind_recv(struct tevent_req *req)
840 {
841         int err;
842
843         if (tevent_req_is_ldap_error(req, &err)) {
844                 return err;
845         }
846         return TLDAP_SUCCESS;
847 }
848
849 int tldap_sasl_bind(struct tldap_context *ld,
850                     const char *dn,
851                     const char *mechanism,
852                     DATA_BLOB *creds,
853                     struct tldap_control *sctrls,
854                     int num_sctrls,
855                     struct tldap_control *cctrls,
856                     int num_cctrls)
857 {
858         TALLOC_CTX *frame = talloc_stackframe();
859         struct tevent_context *ev;
860         struct tevent_req *req;
861         int result;
862
863         ev = event_context_init(frame);
864         if (ev == NULL) {
865                 result = TLDAP_NO_MEMORY;
866                 goto fail;
867         }
868
869         req = tldap_sasl_bind_send(frame, ev, ld, dn, mechanism, creds,
870                                    sctrls, num_sctrls, cctrls, num_cctrls);
871         if (req == NULL) {
872                 result = TLDAP_NO_MEMORY;
873                 goto fail;
874         }
875
876         if (!tevent_req_poll(req, ev)) {
877                 result = TLDAP_OPERATIONS_ERROR;
878                 goto fail;
879         }
880
881         result = tldap_sasl_bind_recv(req);
882         tldap_save_errors(ld, req);
883  fail:
884         TALLOC_FREE(frame);
885         return result;
886 }
887
888 struct tevent_req *tldap_simple_bind_send(TALLOC_CTX *mem_ctx,
889                                           struct tevent_context *ev,
890                                           struct tldap_context *ld,
891                                           const char *dn,
892                                           const char *passwd)
893 {
894         DATA_BLOB cred;
895
896         if (passwd != NULL) {
897                 cred.data = (uint8_t *)passwd;
898                 cred.length = strlen(passwd);
899         } else {
900                 cred.data = (uint8_t *)"";
901                 cred.length = 0;
902         }
903         return tldap_sasl_bind_send(mem_ctx, ev, ld, dn, NULL, &cred, NULL, 0,
904                                     NULL, 0);
905 }
906
907 int tldap_simple_bind_recv(struct tevent_req *req)
908 {
909         return tldap_sasl_bind_recv(req);
910 }
911
912 int tldap_simple_bind(struct tldap_context *ld, const char *dn,
913                       const char *passwd)
914 {
915         DATA_BLOB cred;
916
917         if (passwd != NULL) {
918                 cred.data = (uint8_t *)passwd;
919                 cred.length = strlen(passwd);
920         } else {
921                 cred.data = (uint8_t *)"";
922                 cred.length = 0;
923         }
924         return tldap_sasl_bind(ld, dn, NULL, &cred, NULL, 0, NULL, 0);
925 }
926
927 /*****************************************************************************/
928
929 /*
930  * This piece has a dependency on ldb, the ldb_parse_tree() function is used.
931  * In case we want to separate out tldap, we need to copy or rewrite it.
932  */
933
934 #include "lib/ldb/include/ldb.h"
935 #include "lib/ldb/include/ldb_errors.h"
936
937 static bool ldap_push_filter(struct asn1_data *data,
938                              struct ldb_parse_tree *tree)
939 {
940         int i;
941
942         switch (tree->operation) {
943         case LDB_OP_AND:
944         case LDB_OP_OR:
945                 asn1_push_tag(data,
946                               ASN1_CONTEXT(tree->operation==LDB_OP_AND?0:1));
947                 for (i=0; i<tree->u.list.num_elements; i++) {
948                         if (!ldap_push_filter(data,
949                                               tree->u.list.elements[i])) {
950                                 return false;
951                         }
952                 }
953                 asn1_pop_tag(data);
954                 break;
955
956         case LDB_OP_NOT:
957                 asn1_push_tag(data, ASN1_CONTEXT(2));
958                 if (!ldap_push_filter(data, tree->u.isnot.child)) {
959                         return false;
960                 }
961                 asn1_pop_tag(data);
962                 break;
963
964         case LDB_OP_EQUALITY:
965                 /* equality test */
966                 asn1_push_tag(data, ASN1_CONTEXT(3));
967                 asn1_write_OctetString(data, tree->u.equality.attr,
968                                       strlen(tree->u.equality.attr));
969                 asn1_write_OctetString(data, tree->u.equality.value.data,
970                                       tree->u.equality.value.length);
971                 asn1_pop_tag(data);
972                 break;
973
974         case LDB_OP_SUBSTRING:
975                 /*
976                   SubstringFilter ::= SEQUENCE {
977                           type            AttributeDescription,
978                           -- at least one must be present
979                           substrings      SEQUENCE OF CHOICE {
980                                   initial [0] LDAPString,
981                                   any     [1] LDAPString,
982                                   final   [2] LDAPString } }
983                 */
984                 asn1_push_tag(data, ASN1_CONTEXT(4));
985                 asn1_write_OctetString(data, tree->u.substring.attr,
986                                        strlen(tree->u.substring.attr));
987                 asn1_push_tag(data, ASN1_SEQUENCE(0));
988                 i = 0;
989                 if (!tree->u.substring.start_with_wildcard) {
990                         asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(0));
991                         asn1_write_DATA_BLOB_LDAPString(
992                                 data, tree->u.substring.chunks[i]);
993                         asn1_pop_tag(data);
994                         i++;
995                 }
996                 while (tree->u.substring.chunks[i]) {
997                         int ctx;
998
999                         if ((!tree->u.substring.chunks[i + 1]) &&
1000                             (tree->u.substring.end_with_wildcard == 0)) {
1001                                 ctx = 2;
1002                         } else {
1003                                 ctx = 1;
1004                         }
1005                         asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(ctx));
1006                         asn1_write_DATA_BLOB_LDAPString(
1007                                 data, tree->u.substring.chunks[i]);
1008                         asn1_pop_tag(data);
1009                         i++;
1010                 }
1011                 asn1_pop_tag(data);
1012                 asn1_pop_tag(data);
1013                 break;
1014
1015         case LDB_OP_GREATER:
1016                 /* greaterOrEqual test */
1017                 asn1_push_tag(data, ASN1_CONTEXT(5));
1018                 asn1_write_OctetString(data, tree->u.comparison.attr,
1019                                       strlen(tree->u.comparison.attr));
1020                 asn1_write_OctetString(data, tree->u.comparison.value.data,
1021                                       tree->u.comparison.value.length);
1022                 asn1_pop_tag(data);
1023                 break;
1024
1025         case LDB_OP_LESS:
1026                 /* lessOrEqual test */
1027                 asn1_push_tag(data, ASN1_CONTEXT(6));
1028                 asn1_write_OctetString(data, tree->u.comparison.attr,
1029                                       strlen(tree->u.comparison.attr));
1030                 asn1_write_OctetString(data, tree->u.comparison.value.data,
1031                                       tree->u.comparison.value.length);
1032                 asn1_pop_tag(data);
1033                 break;
1034
1035         case LDB_OP_PRESENT:
1036                 /* present test */
1037                 asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(7));
1038                 asn1_write_LDAPString(data, tree->u.present.attr);
1039                 asn1_pop_tag(data);
1040                 return !data->has_error;
1041
1042         case LDB_OP_APPROX:
1043                 /* approx test */
1044                 asn1_push_tag(data, ASN1_CONTEXT(8));
1045                 asn1_write_OctetString(data, tree->u.comparison.attr,
1046                                       strlen(tree->u.comparison.attr));
1047                 asn1_write_OctetString(data, tree->u.comparison.value.data,
1048                                       tree->u.comparison.value.length);
1049                 asn1_pop_tag(data);
1050                 break;
1051
1052         case LDB_OP_EXTENDED:
1053                 /*
1054                   MatchingRuleAssertion ::= SEQUENCE {
1055                   matchingRule    [1] MatchingRuleID OPTIONAL,
1056                   type            [2] AttributeDescription OPTIONAL,
1057                   matchValue      [3] AssertionValue,
1058                   dnAttributes    [4] BOOLEAN DEFAULT FALSE
1059                   }
1060                 */
1061                 asn1_push_tag(data, ASN1_CONTEXT(9));
1062                 if (tree->u.extended.rule_id) {
1063                         asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(1));
1064                         asn1_write_LDAPString(data, tree->u.extended.rule_id);
1065                         asn1_pop_tag(data);
1066                 }
1067                 if (tree->u.extended.attr) {
1068                         asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(2));
1069                         asn1_write_LDAPString(data, tree->u.extended.attr);
1070                         asn1_pop_tag(data);
1071                 }
1072                 asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(3));
1073                 asn1_write_DATA_BLOB_LDAPString(data, &tree->u.extended.value);
1074                 asn1_pop_tag(data);
1075                 asn1_push_tag(data, ASN1_CONTEXT_SIMPLE(4));
1076                 asn1_write_uint8(data, tree->u.extended.dnAttributes);
1077                 asn1_pop_tag(data);
1078                 asn1_pop_tag(data);
1079                 break;
1080
1081         default:
1082                 return false;
1083         }
1084         return !data->has_error;
1085 }
1086
1087 static bool tldap_push_filter(struct asn1_data *data, const char *filter)
1088 {
1089         struct ldb_parse_tree *tree;
1090         bool ret;
1091
1092         tree = ldb_parse_tree(talloc_tos(), filter);
1093         if (tree == NULL) {
1094                 return false;
1095         }
1096         ret = ldap_push_filter(data, tree);
1097         TALLOC_FREE(tree);
1098         return ret;
1099 }
1100
1101 /*****************************************************************************/
1102
1103 static void tldap_search_done(struct tevent_req *subreq);
1104
1105 struct tevent_req *tldap_search_send(TALLOC_CTX *mem_ctx,
1106                                      struct tevent_context *ev,
1107                                      struct tldap_context *ld,
1108                                      const char *base, int scope,
1109                                      const char *filter,
1110                                      const char **attrs,
1111                                      int num_attrs,
1112                                      int attrsonly,
1113                                      struct tldap_control *sctrls,
1114                                      int num_sctrls,
1115                                      struct tldap_control *cctrls,
1116                                      int num_cctrls,
1117                                      int timelimit,
1118                                      int sizelimit,
1119                                      int deref)
1120 {
1121         struct tevent_req *req, *subreq;
1122         struct tldap_req_state *state;
1123         int i;
1124
1125         req = tldap_req_create(mem_ctx, ld, &state);
1126         if (req == NULL) {
1127                 return NULL;
1128         }
1129
1130         asn1_push_tag(state->out, TLDAP_REQ_SEARCH);
1131         asn1_write_OctetString(state->out, base, strlen(base));
1132         asn1_write_enumerated(state->out, scope);
1133         asn1_write_enumerated(state->out, deref);
1134         asn1_write_Integer(state->out, sizelimit);
1135         asn1_write_Integer(state->out, timelimit);
1136         asn1_write_BOOLEAN(state->out, attrsonly);
1137
1138         if (!tldap_push_filter(state->out, filter)) {
1139                 goto encoding_error;
1140         }
1141
1142         asn1_push_tag(state->out, ASN1_SEQUENCE(0));
1143         for (i=0; i<num_attrs; i++) {
1144                 asn1_write_OctetString(state->out, attrs[i], strlen(attrs[i]));
1145         }
1146         asn1_pop_tag(state->out);
1147         asn1_pop_tag(state->out);
1148
1149         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
1150                                 sctrls, num_sctrls);
1151         if (tevent_req_nomem(subreq, req)) {
1152                 return tevent_req_post(req, ev);
1153         }
1154         tevent_req_set_callback(subreq, tldap_search_done, req);
1155         return req;
1156
1157  encoding_error:
1158         tevent_req_error(req, TLDAP_ENCODING_ERROR);
1159         return tevent_req_post(req, ev);
1160 }
1161
1162 static void tldap_search_done(struct tevent_req *subreq)
1163 {
1164         struct tevent_req *req = tevent_req_callback_data(
1165                 subreq, struct tevent_req);
1166         struct tldap_req_state *state = tevent_req_data(
1167                 req, struct tldap_req_state);
1168         int err;
1169
1170         err = tldap_msg_recv(subreq, state, &state->result);
1171         if (err != TLDAP_SUCCESS) {
1172                 tevent_req_error(req, err);
1173                 return;
1174         }
1175         switch (state->result->type) {
1176         case TLDAP_RES_SEARCH_ENTRY:
1177         case TLDAP_RES_SEARCH_REFERENCE:
1178                 tevent_req_notify_callback(req);
1179                 if (!tldap_msg_set_pending(subreq)) {
1180                         tevent_req_nomem(NULL, req);
1181                         return;
1182                 }
1183                 break;
1184         case TLDAP_RES_SEARCH_RESULT:
1185                 TALLOC_FREE(subreq);
1186                 if (!asn1_start_tag(state->result->data,
1187                                     state->result->type) ||
1188                     !tldap_decode_response(state) ||
1189                     !asn1_end_tag(state->result->data)) {
1190                         tevent_req_error(req, TLDAP_DECODING_ERROR);
1191                         return;
1192                 }
1193                 tevent_req_done(req);
1194                 break;
1195         default:
1196                 tevent_req_error(req, TLDAP_PROTOCOL_ERROR);
1197                 return;
1198         }
1199 }
1200
1201 int tldap_search_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
1202                       struct tldap_message **pmsg)
1203 {
1204         struct tldap_req_state *state = tevent_req_data(
1205                 req, struct tldap_req_state);
1206         int err;
1207
1208         if (!tevent_req_is_in_progress(req)
1209             && tevent_req_is_ldap_error(req, &err)) {
1210                 return err;
1211         }
1212
1213         if (tevent_req_is_in_progress(req)) {
1214                 switch (state->result->type) {
1215                 case TLDAP_RES_SEARCH_ENTRY:
1216                 case TLDAP_RES_SEARCH_REFERENCE:
1217                         break;
1218                 default:
1219                         return TLDAP_OPERATIONS_ERROR;
1220                 }
1221         }
1222
1223         *pmsg = talloc_move(mem_ctx, &state->result);
1224         return TLDAP_SUCCESS;
1225 }
1226
1227 struct tldap_sync_search_state {
1228         TALLOC_CTX *mem_ctx;
1229         struct tldap_message **entries;
1230         struct tldap_message **refs;
1231         int rc;
1232 };
1233
1234 static void tldap_search_cb(struct tevent_req *req)
1235 {
1236         struct tldap_sync_search_state *state =
1237                 (struct tldap_sync_search_state *)
1238                 tevent_req_callback_data_void(req);
1239         struct tldap_message *msg, **tmp;
1240         int rc, num_entries, num_refs;
1241
1242         rc = tldap_search_recv(req, talloc_tos(), &msg);
1243         if (rc != TLDAP_SUCCESS) {
1244                 state->rc = rc;
1245                 return;
1246         }
1247
1248         switch (tldap_msg_type(msg)) {
1249         case TLDAP_RES_SEARCH_ENTRY:
1250                 num_entries = talloc_array_length(state->entries);
1251                 tmp = talloc_realloc(state->mem_ctx, state->entries,
1252                                      struct tldap_message *, num_entries + 1);
1253                 if (tmp == NULL) {
1254                         state->rc = TLDAP_NO_MEMORY;
1255                         return;
1256                 }
1257                 state->entries = tmp;
1258                 state->entries[num_entries] = talloc_move(state->entries,
1259                                                           &msg);
1260                 break;
1261         case TLDAP_RES_SEARCH_REFERENCE:
1262                 num_refs = talloc_array_length(state->refs);
1263                 tmp = talloc_realloc(state->mem_ctx, state->refs,
1264                                      struct tldap_message *, num_refs + 1);
1265                 if (tmp == NULL) {
1266                         state->rc = TLDAP_NO_MEMORY;
1267                         return;
1268                 }
1269                 state->refs = tmp;
1270                 state->refs[num_refs] = talloc_move(state->refs, &msg);
1271                 break;
1272         case TLDAP_RES_SEARCH_RESULT:
1273                 state->rc = TLDAP_SUCCESS;
1274                 break;
1275         default:
1276                 state->rc = TLDAP_PROTOCOL_ERROR;
1277                 break;
1278         }
1279 }
1280
1281 int tldap_search(struct tldap_context *ld,
1282                  const char *base, int scope, const char *filter,
1283                  const char **attrs, int num_attrs, int attrsonly,
1284                  struct tldap_control *sctrls, int num_sctrls,
1285                  struct tldap_control *cctrls, int num_cctrls,
1286                  int timelimit, int sizelimit, int deref,
1287                  TALLOC_CTX *mem_ctx, struct tldap_message ***entries,
1288                  struct tldap_message ***refs)
1289 {
1290         TALLOC_CTX *frame = talloc_stackframe();
1291         struct tevent_context *ev;
1292         struct tevent_req *req;
1293         struct tldap_sync_search_state state;
1294
1295         ZERO_STRUCT(state);
1296         state.mem_ctx = mem_ctx;
1297         state.rc = TLDAP_SUCCESS;
1298
1299         ev = event_context_init(frame);
1300         if (ev == NULL) {
1301                 state.rc = TLDAP_NO_MEMORY;
1302                 goto fail;
1303         }
1304
1305         req = tldap_search_send(frame, ev, ld, base, scope, filter,
1306                                 attrs, num_attrs, attrsonly,
1307                                 sctrls, num_sctrls, cctrls, num_cctrls,
1308                                 timelimit, sizelimit, deref);
1309         if (req == NULL) {
1310                 state.rc = TLDAP_NO_MEMORY;
1311                 goto fail;
1312         }
1313
1314         tevent_req_set_callback(req, tldap_search_cb, &state);
1315
1316         while (tevent_req_is_in_progress(req)
1317                && (state.rc == TLDAP_SUCCESS)) {
1318                 if (tevent_loop_once(ev) == -1) {
1319                         return TLDAP_OPERATIONS_ERROR;
1320                 }
1321         }
1322
1323         if (state.rc != TLDAP_SUCCESS) {
1324                 return state.rc;
1325         }
1326
1327         if (entries != NULL) {
1328                 *entries = state.entries;
1329         } else {
1330                 TALLOC_FREE(state.entries);
1331         }
1332         if (refs != NULL) {
1333                 *refs = state.refs;
1334         } else {
1335                 TALLOC_FREE(state.refs);
1336         }
1337         tldap_save_errors(ld, req);
1338 fail:
1339         TALLOC_FREE(frame);
1340         return state.rc;
1341 }
1342
1343 static bool tldap_parse_search_entry(struct tldap_message *msg)
1344 {
1345         int num_attribs = 0;
1346
1347         asn1_start_tag(msg->data, msg->type);
1348
1349         /* dn */
1350
1351         asn1_read_OctetString_talloc(msg, msg->data, &msg->dn);
1352         if (msg->dn == NULL) {
1353                 return false;
1354         }
1355
1356         /*
1357          * Attributes: We overallocate msg->attribs by one, so that while
1358          * looping over the attributes we can directly parse into the last
1359          * array element. Same for the values in the inner loop.
1360          */
1361
1362         msg->attribs = talloc_array(msg, struct tldap_attribute, 1);
1363         if (msg->attribs == NULL) {
1364                 return false;
1365         }
1366
1367         asn1_start_tag(msg->data, ASN1_SEQUENCE(0));
1368         while (asn1_peek_tag(msg->data, ASN1_SEQUENCE(0))) {
1369                 struct tldap_attribute *attrib;
1370                 int num_values = 0;
1371
1372                 attrib = &msg->attribs[num_attribs];
1373                 attrib->values = talloc_array(msg->attribs, DATA_BLOB, 1);
1374                 if (attrib->values == NULL) {
1375                         return false;
1376                 }
1377                 asn1_start_tag(msg->data, ASN1_SEQUENCE(0));
1378                 asn1_read_OctetString_talloc(msg->attribs, msg->data,
1379                                              &attrib->name);
1380                 asn1_start_tag(msg->data, ASN1_SET);
1381
1382                 while (asn1_peek_tag(msg->data, ASN1_OCTET_STRING)) {
1383                         asn1_read_OctetString(msg->data, msg,
1384                                               &attrib->values[num_values]);
1385
1386                         attrib->values = talloc_realloc(
1387                                 msg->attribs, attrib->values, DATA_BLOB,
1388                                 num_values + 2);
1389                         if (attrib->values == NULL) {
1390                                 return false;
1391                         }
1392                         num_values += 1;
1393                 }
1394                 attrib->values = talloc_realloc(msg->attribs, attrib->values,
1395                                                 DATA_BLOB, num_values);
1396                 attrib->num_values = num_values;
1397
1398                 asn1_end_tag(msg->data); /* ASN1_SET */
1399                 asn1_end_tag(msg->data); /* ASN1_SEQUENCE(0) */
1400                 msg->attribs = talloc_realloc(
1401                         msg, msg->attribs, struct tldap_attribute,
1402                         num_attribs + 2);
1403                 if (msg->attribs == NULL) {
1404                         return false;
1405                 }
1406                 num_attribs += 1;
1407         }
1408         msg->attribs = talloc_realloc(
1409                 msg, msg->attribs, struct tldap_attribute, num_attribs);
1410         asn1_end_tag(msg->data);
1411         if (msg->data->has_error) {
1412                 return false;
1413         }
1414         return true;
1415 }
1416
1417 bool tldap_entry_dn(struct tldap_message *msg, char **dn)
1418 {
1419         if ((msg->dn == NULL) && (!tldap_parse_search_entry(msg))) {
1420                 return false;
1421         }
1422         *dn = msg->dn;
1423         return true;
1424 }
1425
1426 bool tldap_entry_attributes(struct tldap_message *msg, int *num_attributes,
1427                             struct tldap_attribute **attributes)
1428 {
1429         if ((msg->dn == NULL) && (!tldap_parse_search_entry(msg))) {
1430                 return false;
1431         }
1432         *attributes = msg->attribs;
1433         *num_attributes = talloc_array_length(msg->attribs);
1434         return true;
1435 }
1436
1437 static bool tldap_decode_controls(struct tldap_req_state *state)
1438 {
1439         struct asn1_data *data = state->result->data;
1440         struct tldap_control *sctrls = NULL;
1441         int num_controls = 0;
1442
1443         state->res_sctrls = NULL;
1444
1445         if (!asn1_peek_tag(data, ASN1_CONTEXT(0))) {
1446                 return true;
1447         }
1448
1449         asn1_start_tag(data, ASN1_CONTEXT(0));
1450
1451         while (asn1_peek_tag(data, ASN1_SEQUENCE(0))) {
1452                 struct tldap_control *c;
1453                 char *oid = NULL;
1454
1455                 sctrls = talloc_realloc(state, sctrls, struct tldap_control,
1456                                         num_controls + 1);
1457                 if (sctrls == NULL) {
1458                         return false;
1459                 }
1460                 c = &sctrls[num_controls];
1461
1462                 asn1_start_tag(data, ASN1_SEQUENCE(0));
1463                 asn1_read_OctetString_talloc(state, data, &oid);
1464                 if ((data->has_error) || (oid == NULL)) {
1465                         return false;
1466                 }
1467                 c->oid = oid;
1468                 if (asn1_peek_tag(data, ASN1_BOOLEAN)) {
1469                         asn1_read_BOOLEAN(data, &c->critical);
1470                 } else {
1471                         c->critical = false;
1472                 }
1473                 c->value = data_blob_null;
1474                 if (asn1_peek_tag(data, ASN1_OCTET_STRING) &&
1475                     !asn1_read_OctetString(data, state, &c->value)) {
1476                         return false;
1477                 }
1478                 asn1_end_tag(data); /* ASN1_SEQUENCE(0) */
1479
1480                 num_controls += 1;
1481         }
1482
1483         asn1_end_tag(data);     /* ASN1_CONTEXT(0) */
1484
1485         if (data->has_error) {
1486                 TALLOC_FREE(sctrls);
1487                 return false;
1488         }
1489         state->res_sctrls = sctrls;
1490         return true;
1491 }
1492
1493 static void tldap_simple_done(struct tevent_req *subreq, int type)
1494 {
1495         struct tevent_req *req = tevent_req_callback_data(
1496                 subreq, struct tevent_req);
1497         struct tldap_req_state *state = tevent_req_data(
1498                 req, struct tldap_req_state);
1499         int err;
1500
1501         err = tldap_msg_recv(subreq, state, &state->result);
1502         TALLOC_FREE(subreq);
1503         if (err != TLDAP_SUCCESS) {
1504                 tevent_req_error(req, err);
1505                 return;
1506         }
1507         if (state->result->type != type) {
1508                 tevent_req_error(req, TLDAP_PROTOCOL_ERROR);
1509                 return;
1510         }
1511         if (!asn1_start_tag(state->result->data, state->result->type) ||
1512             !tldap_decode_response(state) ||
1513             !asn1_end_tag(state->result->data) ||
1514             !tldap_decode_controls(state)) {
1515                 tevent_req_error(req, TLDAP_DECODING_ERROR);
1516                 return;
1517         }
1518         if (state->lderr != TLDAP_SUCCESS) {
1519                 tevent_req_error(req, state->lderr);
1520                 return;
1521         }
1522         tevent_req_done(req);
1523 }
1524
1525 static int tldap_simple_recv(struct tevent_req *req)
1526 {
1527         int err;
1528         if (tevent_req_is_ldap_error(req, &err)) {
1529                 return err;
1530         }
1531         return TLDAP_SUCCESS;
1532 }
1533
1534 static void tldap_add_done(struct tevent_req *subreq);
1535
1536 struct tevent_req *tldap_add_send(TALLOC_CTX *mem_ctx,
1537                                   struct tevent_context *ev,
1538                                   struct tldap_context *ld,
1539                                   const char *dn,
1540                                   struct tldap_mod *attributes,
1541                                   int num_attributes,
1542                                   struct tldap_control *sctrls,
1543                                   int num_sctrls,
1544                                   struct tldap_control *cctrls,
1545                                   int num_cctrls)
1546 {
1547         struct tevent_req *req, *subreq;
1548         struct tldap_req_state *state;
1549         int i, j;
1550
1551         req = tldap_req_create(mem_ctx, ld, &state);
1552         if (req == NULL) {
1553                 return NULL;
1554         }
1555
1556         asn1_push_tag(state->out, TLDAP_REQ_ADD);
1557         asn1_write_OctetString(state->out, dn, strlen(dn));
1558         asn1_push_tag(state->out, ASN1_SEQUENCE(0));
1559
1560         for (i=0; i<num_attributes; i++) {
1561                 struct tldap_mod *attrib = &attributes[i];
1562                 asn1_push_tag(state->out, ASN1_SEQUENCE(0));
1563                 asn1_write_OctetString(state->out, attrib->attribute,
1564                                        strlen(attrib->attribute));
1565                 asn1_push_tag(state->out, ASN1_SET);
1566                 for (j=0; j<attrib->num_values; j++) {
1567                         asn1_write_OctetString(state->out,
1568                                                attrib->values[j].data,
1569                                                attrib->values[j].length);
1570                 }
1571                 asn1_pop_tag(state->out);
1572                 asn1_pop_tag(state->out);
1573         }
1574
1575         asn1_pop_tag(state->out);
1576         asn1_pop_tag(state->out);
1577
1578         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
1579                                 sctrls, num_sctrls);
1580         if (tevent_req_nomem(subreq, req)) {
1581                 return tevent_req_post(req, ev);
1582         }
1583         tevent_req_set_callback(subreq, tldap_add_done, req);
1584         return req;
1585 }
1586
1587 static void tldap_add_done(struct tevent_req *subreq)
1588 {
1589         return tldap_simple_done(subreq, TLDAP_RES_ADD);
1590 }
1591
1592 int tldap_add_recv(struct tevent_req *req)
1593 {
1594         return tldap_simple_recv(req);
1595 }
1596
1597 int tldap_add(struct tldap_context *ld, const char *dn,
1598               int num_attributes, struct tldap_mod *attributes,
1599               struct tldap_control *sctrls, int num_sctrls,
1600               struct tldap_control *cctrls, int num_cctrls)
1601 {
1602         TALLOC_CTX *frame = talloc_stackframe();
1603         struct tevent_context *ev;
1604         struct tevent_req *req;
1605         int result;
1606
1607         ev = event_context_init(frame);
1608         if (ev == NULL) {
1609                 result = TLDAP_NO_MEMORY;
1610                 goto fail;
1611         }
1612
1613         req = tldap_add_send(frame, ev, ld, dn, attributes, num_attributes,
1614                              sctrls, num_sctrls, cctrls, num_cctrls);
1615         if (req == NULL) {
1616                 result = TLDAP_NO_MEMORY;
1617                 goto fail;
1618         }
1619
1620         if (!tevent_req_poll(req, ev)) {
1621                 result = TLDAP_OPERATIONS_ERROR;
1622                 goto fail;
1623         }
1624
1625         result = tldap_add_recv(req);
1626         tldap_save_errors(ld, req);
1627  fail:
1628         TALLOC_FREE(frame);
1629         return result;
1630 }
1631
1632 static void tldap_modify_done(struct tevent_req *subreq);
1633
1634 struct tevent_req *tldap_modify_send(TALLOC_CTX *mem_ctx,
1635                                      struct tevent_context *ev,
1636                                      struct tldap_context *ld,
1637                                      const char *dn,
1638                                      int num_mods, struct tldap_mod *mods,
1639                                      struct tldap_control *sctrls,
1640                                      int num_sctrls,
1641                                      struct tldap_control *cctrls,
1642                                      int num_cctrls)
1643 {
1644         struct tevent_req *req, *subreq;
1645         struct tldap_req_state *state;
1646         int i, j;
1647
1648         req = tldap_req_create(mem_ctx, ld, &state);
1649         if (req == NULL) {
1650                 return NULL;
1651         }
1652
1653         asn1_push_tag(state->out, TLDAP_REQ_MODIFY);
1654         asn1_write_OctetString(state->out, dn, strlen(dn));
1655         asn1_push_tag(state->out, ASN1_SEQUENCE(0));
1656
1657         for (i=0; i<num_mods; i++) {
1658                 struct tldap_mod *mod = &mods[i];
1659                 asn1_push_tag(state->out, ASN1_SEQUENCE(0));
1660                 asn1_write_enumerated(state->out, mod->mod_op),
1661                 asn1_push_tag(state->out, ASN1_SEQUENCE(0));
1662                 asn1_write_OctetString(state->out, mod->attribute,
1663                                        strlen(mod->attribute));
1664                 asn1_push_tag(state->out, ASN1_SET);
1665                 for (j=0; j<mod->num_values; j++) {
1666                         asn1_write_OctetString(state->out,
1667                                                mod->values[j].data,
1668                                                mod->values[j].length);
1669                 }
1670                 asn1_pop_tag(state->out);
1671                 asn1_pop_tag(state->out);
1672                 asn1_pop_tag(state->out);
1673         }
1674
1675         asn1_pop_tag(state->out);
1676         asn1_pop_tag(state->out);
1677
1678         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
1679                                 sctrls, num_sctrls);
1680         if (tevent_req_nomem(subreq, req)) {
1681                 return tevent_req_post(req, ev);
1682         }
1683         tevent_req_set_callback(subreq, tldap_modify_done, req);
1684         return req;
1685 }
1686
1687 static void tldap_modify_done(struct tevent_req *subreq)
1688 {
1689         return tldap_simple_done(subreq, TLDAP_RES_MODIFY);
1690 }
1691
1692 int tldap_modify_recv(struct tevent_req *req)
1693 {
1694         return tldap_simple_recv(req);
1695 }
1696
1697 int tldap_modify(struct tldap_context *ld, const char *dn,
1698                  int num_mods, struct tldap_mod *mods,
1699                  struct tldap_control *sctrls, int num_sctrls,
1700                  struct tldap_control *cctrls, int num_cctrls)
1701  {
1702         TALLOC_CTX *frame = talloc_stackframe();
1703         struct tevent_context *ev;
1704         struct tevent_req *req;
1705         int result;
1706
1707         ev = event_context_init(frame);
1708         if (ev == NULL) {
1709                 result = TLDAP_NO_MEMORY;
1710                 goto fail;
1711         }
1712
1713         req = tldap_modify_send(frame, ev, ld, dn, num_mods, mods,
1714                                 sctrls, num_sctrls, cctrls, num_cctrls);
1715         if (req == NULL) {
1716                 result = TLDAP_NO_MEMORY;
1717                 goto fail;
1718         }
1719
1720         if (!tevent_req_poll(req, ev)) {
1721                 result = TLDAP_OPERATIONS_ERROR;
1722                 goto fail;
1723         }
1724
1725         result = tldap_modify_recv(req);
1726         tldap_save_errors(ld, req);
1727  fail:
1728         TALLOC_FREE(frame);
1729         return result;
1730 }
1731
1732 static void tldap_delete_done(struct tevent_req *subreq);
1733
1734 struct tevent_req *tldap_delete_send(TALLOC_CTX *mem_ctx,
1735                                      struct tevent_context *ev,
1736                                      struct tldap_context *ld,
1737                                      const char *dn,
1738                                      struct tldap_control *sctrls,
1739                                      int num_sctrls,
1740                                      struct tldap_control *cctrls,
1741                                      int num_cctrls)
1742 {
1743         struct tevent_req *req, *subreq;
1744         struct tldap_req_state *state;
1745
1746         req = tldap_req_create(mem_ctx, ld, &state);
1747         if (req == NULL) {
1748                 return NULL;
1749         }
1750
1751         asn1_push_tag(state->out, TLDAP_REQ_DELETE);
1752         asn1_write(state->out, dn, strlen(dn));
1753         asn1_pop_tag(state->out);
1754
1755         subreq = tldap_msg_send(state, ev, ld, state->id, state->out,
1756                                 sctrls, num_sctrls);
1757         if (tevent_req_nomem(subreq, req)) {
1758                 return tevent_req_post(req, ev);
1759         }
1760         tevent_req_set_callback(subreq, tldap_delete_done, req);
1761         return req;
1762 }
1763
1764 static void tldap_delete_done(struct tevent_req *subreq)
1765 {
1766         return tldap_simple_done(subreq, TLDAP_RES_DELETE);
1767 }
1768
1769 int tldap_delete_recv(struct tevent_req *req)
1770 {
1771         return tldap_simple_recv(req);
1772 }
1773
1774 int tldap_delete(struct tldap_context *ld, const char *dn,
1775                  struct tldap_control *sctrls, int num_sctrls,
1776                  struct tldap_control *cctrls, int num_cctrls)
1777 {
1778         TALLOC_CTX *frame = talloc_stackframe();
1779         struct tevent_context *ev;
1780         struct tevent_req *req;
1781         int result;
1782
1783         ev = event_context_init(frame);
1784         if (ev == NULL) {
1785                 result = TLDAP_NO_MEMORY;
1786                 goto fail;
1787         }
1788
1789         req = tldap_delete_send(frame, ev, ld, dn, sctrls, num_sctrls,
1790                                 cctrls, num_cctrls);
1791         if (req == NULL) {
1792                 result = TLDAP_NO_MEMORY;
1793                 goto fail;
1794         }
1795
1796         if (!tevent_req_poll(req, ev)) {
1797                 result = TLDAP_OPERATIONS_ERROR;
1798                 goto fail;
1799         }
1800
1801         result = tldap_delete_recv(req);
1802         tldap_save_errors(ld, req);
1803  fail:
1804         TALLOC_FREE(frame);
1805         return result;
1806 }
1807
1808 int tldap_msg_id(const struct tldap_message *msg)
1809 {
1810         return msg->id;
1811 }
1812
1813 int tldap_msg_type(const struct tldap_message *msg)
1814 {
1815         return msg->type;
1816 }
1817
1818 const char *tldap_req_matcheddn(struct tevent_req *req)
1819 {
1820         struct tldap_req_state *state = tevent_req_data(
1821                 req, struct tldap_req_state);
1822         return state->res_matcheddn;
1823 }
1824
1825 const char *tldap_req_diagnosticmessage(struct tevent_req *req)
1826 {
1827         struct tldap_req_state *state = tevent_req_data(
1828                 req, struct tldap_req_state);
1829         return state->res_diagnosticmessage;
1830 }
1831
1832 const char *tldap_req_referral(struct tevent_req *req)
1833 {
1834         struct tldap_req_state *state = tevent_req_data(
1835                 req, struct tldap_req_state);
1836         return state->res_referral;
1837 }
1838
1839 void tldap_req_sctrls(struct tevent_req *req, int *num_sctrls,
1840                       struct tldap_control **sctrls)
1841 {
1842         struct tldap_req_state *state = tevent_req_data(
1843                 req, struct tldap_req_state);
1844         *sctrls = state->res_sctrls;
1845         *num_sctrls = talloc_array_length(state->res_sctrls);
1846 }
1847
1848 const char *tldap_ctx_matcheddn(struct tldap_context *ctx)
1849 {
1850         return ctx->res_matcheddn;
1851 }
1852
1853 const char *tldap_ctx_diagnosticmessage(struct tldap_context *ctx)
1854 {
1855         return ctx->res_diagnosticmessage;
1856 }
1857
1858 const char *tldap_ctx_referral(struct tldap_context *ctx)
1859 {
1860         return ctx->res_referral;
1861 }
1862
1863 void tldap_ctx_sctrls(struct tldap_context *ctx, int *num_sctrls,
1864                       struct tldap_control **sctrls)
1865 {
1866         *sctrls = ctx->res_sctrls;
1867         *num_sctrls = talloc_array_length(ctx->res_sctrls);
1868 }
1869
1870 const char *tldap_err2string(int rc)
1871 {
1872         const char *res = NULL;
1873
1874         /*
1875          * This would normally be a table, but the error codes are not fully
1876          * sequential. Let the compiler figure out the optimum implementation
1877          * :-)
1878          */
1879
1880         switch (rc) {
1881         case TLDAP_SUCCESS:
1882                 res = "TLDAP_SUCCESS";
1883                 break;
1884         case TLDAP_OPERATIONS_ERROR:
1885                 res = "TLDAP_OPERATIONS_ERROR";
1886                 break;
1887         case TLDAP_PROTOCOL_ERROR:
1888                 res = "TLDAP_PROTOCOL_ERROR";
1889                 break;
1890         case TLDAP_TIMELIMIT_EXCEEDED:
1891                 res = "TLDAP_TIMELIMIT_EXCEEDED";
1892                 break;
1893         case TLDAP_SIZELIMIT_EXCEEDED:
1894                 res = "TLDAP_SIZELIMIT_EXCEEDED";
1895                 break;
1896         case TLDAP_COMPARE_FALSE:
1897                 res = "TLDAP_COMPARE_FALSE";
1898                 break;
1899         case TLDAP_COMPARE_TRUE:
1900                 res = "TLDAP_COMPARE_TRUE";
1901                 break;
1902         case TLDAP_STRONG_AUTH_NOT_SUPPORTED:
1903                 res = "TLDAP_STRONG_AUTH_NOT_SUPPORTED";
1904                 break;
1905         case TLDAP_STRONG_AUTH_REQUIRED:
1906                 res = "TLDAP_STRONG_AUTH_REQUIRED";
1907                 break;
1908         case TLDAP_REFERRAL:
1909                 res = "TLDAP_REFERRAL";
1910                 break;
1911         case TLDAP_ADMINLIMIT_EXCEEDED:
1912                 res = "TLDAP_ADMINLIMIT_EXCEEDED";
1913                 break;
1914         case TLDAP_UNAVAILABLE_CRITICAL_EXTENSION:
1915                 res = "TLDAP_UNAVAILABLE_CRITICAL_EXTENSION";
1916                 break;
1917         case TLDAP_CONFIDENTIALITY_REQUIRED:
1918                 res = "TLDAP_CONFIDENTIALITY_REQUIRED";
1919                 break;
1920         case TLDAP_SASL_BIND_IN_PROGRESS:
1921                 res = "TLDAP_SASL_BIND_IN_PROGRESS";
1922                 break;
1923         case TLDAP_NO_SUCH_ATTRIBUTE:
1924                 res = "TLDAP_NO_SUCH_ATTRIBUTE";
1925                 break;
1926         case TLDAP_UNDEFINED_TYPE:
1927                 res = "TLDAP_UNDEFINED_TYPE";
1928                 break;
1929         case TLDAP_INAPPROPRIATE_MATCHING:
1930                 res = "TLDAP_INAPPROPRIATE_MATCHING";
1931                 break;
1932         case TLDAP_CONSTRAINT_VIOLATION:
1933                 res = "TLDAP_CONSTRAINT_VIOLATION";
1934                 break;
1935         case TLDAP_TYPE_OR_VALUE_EXISTS:
1936                 res = "TLDAP_TYPE_OR_VALUE_EXISTS";
1937                 break;
1938         case TLDAP_INVALID_SYNTAX:
1939                 res = "TLDAP_INVALID_SYNTAX";
1940                 break;
1941         case TLDAP_NO_SUCH_OBJECT:
1942                 res = "TLDAP_NO_SUCH_OBJECT";
1943                 break;
1944         case TLDAP_ALIAS_PROBLEM:
1945                 res = "TLDAP_ALIAS_PROBLEM";
1946                 break;
1947         case TLDAP_INVALID_DN_SYNTAX:
1948                 res = "TLDAP_INVALID_DN_SYNTAX";
1949                 break;
1950         case TLDAP_IS_LEAF:
1951                 res = "TLDAP_IS_LEAF";
1952                 break;
1953         case TLDAP_ALIAS_DEREF_PROBLEM:
1954                 res = "TLDAP_ALIAS_DEREF_PROBLEM";
1955                 break;
1956         case TLDAP_INAPPROPRIATE_AUTH:
1957                 res = "TLDAP_INAPPROPRIATE_AUTH";
1958                 break;
1959         case TLDAP_INVALID_CREDENTIALS:
1960                 res = "TLDAP_INVALID_CREDENTIALS";
1961                 break;
1962         case TLDAP_INSUFFICIENT_ACCESS:
1963                 res = "TLDAP_INSUFFICIENT_ACCESS";
1964                 break;
1965         case TLDAP_BUSY:
1966                 res = "TLDAP_BUSY";
1967                 break;
1968         case TLDAP_UNAVAILABLE:
1969                 res = "TLDAP_UNAVAILABLE";
1970                 break;
1971         case TLDAP_UNWILLING_TO_PERFORM:
1972                 res = "TLDAP_UNWILLING_TO_PERFORM";
1973                 break;
1974         case TLDAP_LOOP_DETECT:
1975                 res = "TLDAP_LOOP_DETECT";
1976                 break;
1977         case TLDAP_NAMING_VIOLATION:
1978                 res = "TLDAP_NAMING_VIOLATION";
1979                 break;
1980         case TLDAP_OBJECT_CLASS_VIOLATION:
1981                 res = "TLDAP_OBJECT_CLASS_VIOLATION";
1982                 break;
1983         case TLDAP_NOT_ALLOWED_ON_NONLEAF:
1984                 res = "TLDAP_NOT_ALLOWED_ON_NONLEAF";
1985                 break;
1986         case TLDAP_NOT_ALLOWED_ON_RDN:
1987                 res = "TLDAP_NOT_ALLOWED_ON_RDN";
1988                 break;
1989         case TLDAP_ALREADY_EXISTS:
1990                 res = "TLDAP_ALREADY_EXISTS";
1991                 break;
1992         case TLDAP_NO_OBJECT_CLASS_MODS:
1993                 res = "TLDAP_NO_OBJECT_CLASS_MODS";
1994                 break;
1995         case TLDAP_RESULTS_TOO_LARGE:
1996                 res = "TLDAP_RESULTS_TOO_LARGE";
1997                 break;
1998         case TLDAP_AFFECTS_MULTIPLE_DSAS:
1999                 res = "TLDAP_AFFECTS_MULTIPLE_DSAS";
2000                 break;
2001         case TLDAP_OTHER:
2002                 res = "TLDAP_OTHER";
2003                 break;
2004         case TLDAP_SERVER_DOWN:
2005                 res = "TLDAP_SERVER_DOWN";
2006                 break;
2007         case TLDAP_LOCAL_ERROR:
2008                 res = "TLDAP_LOCAL_ERROR";
2009                 break;
2010         case TLDAP_ENCODING_ERROR:
2011                 res = "TLDAP_ENCODING_ERROR";
2012                 break;
2013         case TLDAP_DECODING_ERROR:
2014                 res = "TLDAP_DECODING_ERROR";
2015                 break;
2016         case TLDAP_TIMEOUT:
2017                 res = "TLDAP_TIMEOUT";
2018                 break;
2019         case TLDAP_AUTH_UNKNOWN:
2020                 res = "TLDAP_AUTH_UNKNOWN";
2021                 break;
2022         case TLDAP_FILTER_ERROR:
2023                 res = "TLDAP_FILTER_ERROR";
2024                 break;
2025         case TLDAP_USER_CANCELLED:
2026                 res = "TLDAP_USER_CANCELLED";
2027                 break;
2028         case TLDAP_PARAM_ERROR:
2029                 res = "TLDAP_PARAM_ERROR";
2030                 break;
2031         case TLDAP_NO_MEMORY:
2032                 res = "TLDAP_NO_MEMORY";
2033                 break;
2034         case TLDAP_CONNECT_ERROR:
2035                 res = "TLDAP_CONNECT_ERROR";
2036                 break;
2037         case TLDAP_NOT_SUPPORTED:
2038                 res = "TLDAP_NOT_SUPPORTED";
2039                 break;
2040         case TLDAP_CONTROL_NOT_FOUND:
2041                 res = "TLDAP_CONTROL_NOT_FOUND";
2042                 break;
2043         case TLDAP_NO_RESULTS_RETURNED:
2044                 res = "TLDAP_NO_RESULTS_RETURNED";
2045                 break;
2046         case TLDAP_MORE_RESULTS_TO_RETURN:
2047                 res = "TLDAP_MORE_RESULTS_TO_RETURN";
2048                 break;
2049         case TLDAP_CLIENT_LOOP:
2050                 res = "TLDAP_CLIENT_LOOP";
2051                 break;
2052         case TLDAP_REFERRAL_LIMIT_EXCEEDED:
2053                 res = "TLDAP_REFERRAL_LIMIT_EXCEEDED";
2054                 break;
2055         default:
2056                 res = talloc_asprintf(talloc_tos(), "Unknown LDAP Error (%d)",
2057                                       rc);
2058                 break;
2059         }
2060         if (res == NULL) {
2061                 res = "Unknown LDAP Error";
2062         }
2063         return res;
2064 }