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