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