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