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