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