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