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