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