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