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