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