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