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