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