ctdb: Remove an unnecessary cast
[vlendec/samba-autobuild/.git] / source3 / lib / tldap_util.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 "tldap_util.h"
23 #include "../libcli/security/security.h"
24 #include "../lib/util/asn1.h"
25
26 bool tldap_entry_values(struct tldap_message *msg, const char *attribute,
27                         DATA_BLOB **values, int *num_values)
28 {
29         struct tldap_attribute *attributes;
30         int i, num_attributes;
31
32         if (!tldap_entry_attributes(msg, &attributes, &num_attributes)) {
33                 return false;
34         }
35
36         for (i=0; i<num_attributes; i++) {
37                 if (strequal(attribute, attributes[i].name)) {
38                         break;
39                 }
40         }
41         if (i == num_attributes) {
42                 return false;
43         }
44         *num_values = attributes[i].num_values;
45         *values = attributes[i].values;
46         return true;
47 }
48
49 bool tldap_get_single_valueblob(struct tldap_message *msg,
50                                 const char *attribute, DATA_BLOB *blob)
51 {
52         int num_values;
53         DATA_BLOB *values;
54
55         if (attribute == NULL) {
56                 return NULL;
57         }
58         if (!tldap_entry_values(msg, attribute, &values, &num_values)) {
59                 return NULL;
60         }
61         if (num_values != 1) {
62                 return NULL;
63         }
64         *blob = values[0];
65         return true;
66 }
67
68 char *tldap_talloc_single_attribute(struct tldap_message *msg,
69                                     const char *attribute,
70                                     TALLOC_CTX *mem_ctx)
71 {
72         DATA_BLOB val;
73         char *result;
74         size_t len;
75
76         if (!tldap_get_single_valueblob(msg, attribute, &val)) {
77                 return NULL;
78         }
79         if (!convert_string_talloc(mem_ctx, CH_UTF8, CH_UNIX,
80                                    val.data, val.length,
81                                    &result, &len)) {
82                 return NULL;
83         }
84         return result;
85 }
86
87 bool tldap_pull_binsid(struct tldap_message *msg, const char *attribute,
88                        struct dom_sid *sid)
89 {
90         DATA_BLOB val;
91         ssize_t ret;
92
93         if (!tldap_get_single_valueblob(msg, attribute, &val)) {
94                 return false;
95         }
96         ret = sid_parse(val.data, val.length, sid);
97         return (ret != -1);
98 }
99
100 bool tldap_pull_guid(struct tldap_message *msg, const char *attribute,
101                      struct GUID *guid)
102 {
103         DATA_BLOB val;
104
105         if (!tldap_get_single_valueblob(msg, attribute, &val)) {
106                 return false;
107         }
108         return NT_STATUS_IS_OK(GUID_from_data_blob(&val, guid));
109 }
110
111 static bool tldap_add_blob_vals(TALLOC_CTX *mem_ctx, struct tldap_mod *mod,
112                                 DATA_BLOB *newvals, int num_newvals)
113 {
114         int num_values = talloc_array_length(mod->values);
115         int i;
116         DATA_BLOB *tmp;
117
118         tmp = talloc_realloc(mem_ctx, mod->values, DATA_BLOB,
119                              num_values + num_newvals);
120         if (tmp == NULL) {
121                 return false;
122         }
123         mod->values = tmp;
124
125         for (i=0; i<num_newvals; i++) {
126                 mod->values[i+num_values].data = (uint8_t *)talloc_memdup(
127                         mod->values, newvals[i].data, newvals[i].length);
128                 if (mod->values[i+num_values].data == NULL) {
129                         return false;
130                 }
131                 mod->values[i+num_values].length = newvals[i].length;
132         }
133         mod->num_values = num_values + num_newvals;
134         return true;
135 }
136
137 bool tldap_add_mod_blobs(TALLOC_CTX *mem_ctx,
138                          struct tldap_mod **pmods, int *pnum_mods,
139                          int mod_op, const char *attrib,
140                          DATA_BLOB *newvals, int num_newvals)
141 {
142         struct tldap_mod new_mod;
143         struct tldap_mod *mods = *pmods;
144         struct tldap_mod *mod = NULL;
145         int i, num_mods;
146
147         if (mods == NULL) {
148                 mods = talloc_array(mem_ctx, struct tldap_mod, 0);
149         }
150         if (mods == NULL) {
151                 return false;
152         }
153
154         num_mods = *pnum_mods;
155
156         for (i=0; i<num_mods; i++) {
157                 if ((mods[i].mod_op == mod_op)
158                     && strequal(mods[i].attribute, attrib)) {
159                         mod = &mods[i];
160                         break;
161                 }
162         }
163
164         if (mod == NULL) {
165                 new_mod.mod_op = mod_op;
166                 new_mod.attribute = talloc_strdup(mods, attrib);
167                 if (new_mod.attribute == NULL) {
168                         return false;
169                 }
170                 new_mod.num_values = 0;
171                 new_mod.values = NULL;
172                 mod = &new_mod;
173         }
174
175         if ((num_newvals != 0)
176             && !tldap_add_blob_vals(mods, mod, newvals, num_newvals)) {
177                 return false;
178         }
179
180         if ((i == num_mods) && (talloc_array_length(mods) < num_mods + 1)) {
181                 mods = talloc_realloc(talloc_tos(), mods, struct tldap_mod,
182                                       num_mods+1);
183                 if (mods == NULL) {
184                         return false;
185                 }
186                 mods[num_mods] = *mod;
187         }
188
189         *pmods = mods;
190         *pnum_mods += 1;
191         return true;
192 }
193
194 bool tldap_add_mod_str(TALLOC_CTX *mem_ctx,
195                        struct tldap_mod **pmods, int *pnum_mods,
196                        int mod_op, const char *attrib, const char *str)
197 {
198         DATA_BLOB utf8;
199         bool ret;
200
201         if (!convert_string_talloc(talloc_tos(), CH_UNIX, CH_UTF8, str,
202                                    strlen(str), &utf8.data, &utf8.length)) {
203                 return false;
204         }
205
206         ret = tldap_add_mod_blobs(mem_ctx, pmods, pnum_mods, mod_op, attrib,
207                                   &utf8, 1);
208         TALLOC_FREE(utf8.data);
209         return ret;
210 }
211
212 static bool tldap_make_mod_blob_int(struct tldap_message *existing,
213                                     TALLOC_CTX *mem_ctx,
214                                     struct tldap_mod **pmods, int *pnum_mods,
215                                     const char *attrib, DATA_BLOB newval,
216                                     int (*comparison)(const DATA_BLOB *d1,
217                                                       const DATA_BLOB *d2))
218 {
219         int num_values = 0;
220         DATA_BLOB *values = NULL;
221         DATA_BLOB oldval = data_blob_null;
222
223         if ((existing != NULL)
224             && tldap_entry_values(existing, attrib, &values, &num_values)) {
225
226                 if (num_values > 1) {
227                         /* can't change multivalue attributes atm */
228                         return false;
229                 }
230                 if (num_values == 1) {
231                         oldval = values[0];
232                 }
233         }
234
235         if ((oldval.data != NULL) && (newval.data != NULL)
236             && (comparison(&oldval, &newval) == 0)) {
237                 /* Believe it or not, but LDAP will deny a delete and
238                    an add at the same time if the values are the
239                    same... */
240                 DEBUG(10,("tldap_make_mod_blob_int: attribute |%s| not "
241                           "changed.\n", attrib));
242                 return true;
243         }
244
245         if (oldval.data != NULL) {
246                 /* By deleting exactly the value we found in the entry this
247                  * should be race-free in the sense that the LDAP-Server will
248                  * deny the complete operation if somebody changed the
249                  * attribute behind our back. */
250                 /* This will also allow modifying single valued attributes in
251                  * Novell NDS. In NDS you have to first remove attribute and
252                  * then you could add new value */
253
254                 DEBUG(10, ("tldap_make_mod_blob_int: deleting attribute |%s|\n",
255                            attrib));
256                 if (!tldap_add_mod_blobs(mem_ctx, pmods, pnum_mods,
257                                          TLDAP_MOD_DELETE,
258                                          attrib, &oldval, 1)) {
259                         return false;
260                 }
261         }
262
263         /* Regardless of the real operation (add or modify)
264            we add the new value here. We rely on deleting
265            the old value, should it exist. */
266
267         if (newval.data != NULL) {
268                 DEBUG(10, ("tldap_make_mod_blob_int: adding attribute |%s| value len "
269                            "%d\n", attrib, (int)newval.length));
270                 if (!tldap_add_mod_blobs(mem_ctx, pmods, pnum_mods,
271                                          TLDAP_MOD_ADD,
272                                          attrib, &newval, 1)) {
273                         return false;
274                 }
275         }
276         return true;
277 }
278
279 bool tldap_make_mod_blob(struct tldap_message *existing, TALLOC_CTX *mem_ctx,
280                          struct tldap_mod **pmods, int *pnum_mods,
281                          const char *attrib, DATA_BLOB newval)
282 {
283         return tldap_make_mod_blob_int(existing, mem_ctx, pmods, pnum_mods,
284                                        attrib, newval, data_blob_cmp);
285 }
286
287 static int compare_utf8_blobs(const DATA_BLOB *d1, const DATA_BLOB *d2)
288 {
289         char *s1, *s2;
290         size_t s1len, s2len;
291         int ret;
292
293         if (!convert_string_talloc(talloc_tos(), CH_UTF8, CH_UNIX, d1->data,
294                                    d1->length, &s1, &s1len)) {
295                 /* can't do much here */
296                 return 0;
297         }
298         if (!convert_string_talloc(talloc_tos(), CH_UTF8, CH_UNIX, d2->data,
299                                    d2->length, &s2, &s2len)) {
300                 /* can't do much here */
301                 TALLOC_FREE(s1);
302                 return 0;
303         }
304         ret = strcasecmp_m(s1, s2);
305         TALLOC_FREE(s2);
306         TALLOC_FREE(s1);
307         return ret;
308 }
309
310 bool tldap_make_mod_fmt(struct tldap_message *existing, TALLOC_CTX *mem_ctx,
311                         struct tldap_mod **pmods, int *pnum_mods,
312                         const char *attrib, const char *fmt, ...)
313 {
314         va_list ap;
315         char *newval;
316         bool ret;
317         DATA_BLOB blob = data_blob_null;
318
319         va_start(ap, fmt);
320         newval = talloc_vasprintf(talloc_tos(), fmt, ap);
321         va_end(ap);
322
323         if (newval == NULL) {
324                 return false;
325         }
326
327         blob.length = strlen(newval);
328         if (blob.length != 0) {
329                 blob.data = discard_const_p(uint8_t, newval);
330         }
331         ret = tldap_make_mod_blob_int(existing, mem_ctx, pmods, pnum_mods,
332                                       attrib, blob, compare_utf8_blobs);
333         TALLOC_FREE(newval);
334         return ret;
335 }
336
337 const char *tldap_errstr(TALLOC_CTX *mem_ctx, struct tldap_context *ld,
338                          TLDAPRC rc)
339 {
340         const char *ld_error = NULL;
341         char *res;
342
343         if (ld != NULL) {
344                 ld_error = tldap_msg_diagnosticmessage(tldap_ctx_lastmsg(ld));
345         }
346         res = talloc_asprintf(mem_ctx, "LDAP error %d (%s), %s",
347                               (int)TLDAP_RC_V(rc), tldap_rc2string(rc),
348                               ld_error ? ld_error : "unknown");
349         return res;
350 }
351
352 TLDAPRC tldap_search_va(struct tldap_context *ld, const char *base, int scope,
353                         const char *attrs[], int num_attrs, int attrsonly,
354                         TALLOC_CTX *mem_ctx, struct tldap_message ***res,
355                         const char *fmt, va_list ap)
356 {
357         char *filter;
358         TLDAPRC rc;
359
360         filter = talloc_vasprintf(talloc_tos(), fmt, ap);
361         if (filter == NULL) {
362                 return TLDAP_NO_MEMORY;
363         }
364
365         rc = tldap_search(ld, base, scope, filter,
366                           attrs, num_attrs, attrsonly,
367                           NULL /*sctrls*/, 0, NULL /*cctrls*/, 0,
368                           0 /*timelimit*/, 0 /*sizelimit*/, 0 /*deref*/,
369                           mem_ctx, res);
370         TALLOC_FREE(filter);
371         return rc;
372 }
373
374 TLDAPRC tldap_search_fmt(struct tldap_context *ld, const char *base, int scope,
375                          const char *attrs[], int num_attrs, int attrsonly,
376                          TALLOC_CTX *mem_ctx, struct tldap_message ***res,
377                          const char *fmt, ...)
378 {
379         va_list ap;
380         TLDAPRC rc;
381
382         va_start(ap, fmt);
383         rc = tldap_search_va(ld, base, scope, attrs, num_attrs, attrsonly,
384                              mem_ctx, res, fmt, ap);
385         va_end(ap);
386         return rc;
387 }
388
389 bool tldap_pull_uint64(struct tldap_message *msg, const char *attr,
390                        uint64_t *presult)
391 {
392         char *str;
393         uint64_t result;
394         int error = 0;
395
396         str = tldap_talloc_single_attribute(msg, attr, talloc_tos());
397         if (str == NULL) {
398                 DEBUG(10, ("Could not find attribute %s\n", attr));
399                 return false;
400         }
401
402         result = strtoull_err(str, NULL, 10, &error);
403         if (error != 0) {
404                 DBG_DEBUG("Attribute conversion failed (%s)\n",
405                           strerror(error));
406                 TALLOC_FREE(str);
407                 return false;
408         }
409
410         TALLOC_FREE(str);
411         *presult = result;
412         return true;
413 }
414
415 bool tldap_pull_uint32(struct tldap_message *msg, const char *attr,
416                        uint32_t *presult)
417 {
418         uint64_t result;
419
420         if (!tldap_pull_uint64(msg, attr, &result)) {
421                 return false;
422         }
423         *presult = (uint32_t)result;
424         return true;
425 }
426
427 struct tldap_fetch_rootdse_state {
428         struct tldap_context *ld;
429         struct tldap_message *rootdse;
430 };
431
432 static void tldap_fetch_rootdse_done(struct tevent_req *subreq);
433
434 struct tevent_req *tldap_fetch_rootdse_send(TALLOC_CTX *mem_ctx,
435                                             struct tevent_context *ev,
436                                             struct tldap_context *ld)
437 {
438         struct tevent_req *req, *subreq;
439         struct tldap_fetch_rootdse_state *state;
440         static const char *attrs[2] = { "*", "+" };
441
442         req = tevent_req_create(mem_ctx, &state,
443                                 struct tldap_fetch_rootdse_state);
444         if (req == NULL) {
445                 return NULL;
446         }
447         state->ld = ld;
448         state->rootdse = NULL;
449
450         subreq = tldap_search_send(
451                 mem_ctx, ev, ld, "", TLDAP_SCOPE_BASE, "(objectclass=*)",
452                 attrs, ARRAY_SIZE(attrs), 0, NULL, 0, NULL, 0, 0, 0, 0);
453         if (tevent_req_nomem(subreq, req)) {
454                 return tevent_req_post(req, ev);
455         }
456         tevent_req_set_callback(subreq, tldap_fetch_rootdse_done, req);
457         return req;
458 }
459
460 static void tldap_fetch_rootdse_done(struct tevent_req *subreq)
461 {
462         struct tevent_req *req = tevent_req_callback_data(
463                 subreq, struct tevent_req);
464         struct tldap_fetch_rootdse_state *state = tevent_req_data(
465                 req, struct tldap_fetch_rootdse_state);
466         struct tldap_message *msg;
467         TLDAPRC rc;
468
469         rc = tldap_search_recv(subreq, state, &msg);
470         if (tevent_req_ldap_error(req, rc)) {
471                 return;
472         }
473
474         switch (tldap_msg_type(msg)) {
475         case TLDAP_RES_SEARCH_ENTRY:
476                 if (state->rootdse != NULL) {
477                         goto protocol_error;
478                 }
479                 state->rootdse = msg;
480                 break;
481         case TLDAP_RES_SEARCH_RESULT:
482                 TALLOC_FREE(subreq);
483                 if (state->rootdse == NULL) {
484                         goto protocol_error;
485                 }
486                 tevent_req_done(req);
487                 break;
488         default:
489                 goto protocol_error;
490         }
491         return;
492
493 protocol_error:
494         tevent_req_ldap_error(req, TLDAP_PROTOCOL_ERROR);
495         return;
496 }
497
498 TLDAPRC tldap_fetch_rootdse_recv(struct tevent_req *req)
499 {
500         struct tldap_fetch_rootdse_state *state = tevent_req_data(
501                 req, struct tldap_fetch_rootdse_state);
502         TLDAPRC rc;
503         char *dn;
504
505         if (tevent_req_is_ldap_error(req, &rc)) {
506                 return rc;
507         }
508         /* Trigger parsing the dn, just to make sure it's ok */
509         if (!tldap_entry_dn(state->rootdse, &dn)) {
510                 return TLDAP_DECODING_ERROR;
511         }
512         if (!tldap_context_setattr(state->ld, "tldap:rootdse",
513                                    &state->rootdse)) {
514                 return TLDAP_NO_MEMORY;
515         }
516         return TLDAP_SUCCESS;
517 }
518
519 TLDAPRC tldap_fetch_rootdse(struct tldap_context *ld)
520 {
521         TALLOC_CTX *frame = talloc_stackframe();
522         struct tevent_context *ev;
523         struct tevent_req *req;
524         TLDAPRC rc = TLDAP_NO_MEMORY;
525
526         ev = samba_tevent_context_init(frame);
527         if (ev == NULL) {
528                 goto fail;
529         }
530         req = tldap_fetch_rootdse_send(frame, ev, ld);
531         if (req == NULL) {
532                 goto fail;
533         }
534         if (!tevent_req_poll(req, ev)) {
535                 rc = TLDAP_OPERATIONS_ERROR;
536                 goto fail;
537         }
538
539         rc = tldap_fetch_rootdse_recv(req);
540  fail:
541         TALLOC_FREE(frame);
542         return rc;
543 }
544
545 struct tldap_message *tldap_rootdse(struct tldap_context *ld)
546 {
547         return talloc_get_type(tldap_context_getattr(ld, "tldap:rootdse"),
548                                struct tldap_message);
549 }
550
551 bool tldap_entry_has_attrvalue(struct tldap_message *msg,
552                                const char *attribute,
553                                const DATA_BLOB blob)
554 {
555         int i, num_values;
556         DATA_BLOB *values;
557
558         if (!tldap_entry_values(msg, attribute, &values, &num_values)) {
559                 return false;
560         }
561         for (i=0; i<num_values; i++) {
562                 if (data_blob_cmp(&values[i], &blob) == 0) {
563                         return true;
564                 }
565         }
566         return false;
567 }
568
569 bool tldap_supports_control(struct tldap_context *ld, const char *oid)
570 {
571         struct tldap_message *rootdse = tldap_rootdse(ld);
572
573         if (rootdse == NULL) {
574                 return false;
575         }
576         return tldap_entry_has_attrvalue(rootdse, "supportedControl",
577                                          data_blob_const(oid, strlen(oid)));
578 }
579
580 struct tldap_control *tldap_add_control(TALLOC_CTX *mem_ctx,
581                                         struct tldap_control *ctrls,
582                                         int num_ctrls,
583                                         struct tldap_control *ctrl)
584 {
585         struct tldap_control *result;
586
587         result = talloc_array(mem_ctx, struct tldap_control, num_ctrls+1);
588         if (result == NULL) {
589                 return NULL;
590         }
591         memcpy(result, ctrls, sizeof(struct tldap_control) * num_ctrls);
592         result[num_ctrls] = *ctrl;
593         return result;
594 }
595
596 /*
597  * Find a control returned by the server
598  */
599 struct tldap_control *tldap_msg_findcontrol(struct tldap_message *msg,
600                                             const char *oid)
601 {
602         struct tldap_control *controls;
603         int i, num_controls;
604
605         tldap_msg_sctrls(msg, &num_controls, &controls);
606
607         for (i=0; i<num_controls; i++) {
608                 if (strcmp(controls[i].oid, oid) == 0) {
609                         return &controls[i];
610                 }
611         }
612         return NULL;
613 }
614
615 struct tldap_search_paged_state {
616         struct tevent_context *ev;
617         struct tldap_context *ld;
618         const char *base;
619         const char *filter;
620         int scope;
621         const char **attrs;
622         int num_attrs;
623         int attrsonly;
624         struct tldap_control *sctrls;
625         int num_sctrls;
626         struct tldap_control *cctrls;
627         int num_cctrls;
628         int timelimit;
629         int sizelimit;
630         int deref;
631
632         int page_size;
633         struct asn1_data *asn1;
634         DATA_BLOB cookie;
635         struct tldap_message *result;
636 };
637
638 static struct tevent_req *tldap_ship_paged_search(
639         TALLOC_CTX *mem_ctx,
640         struct tldap_search_paged_state *state)
641 {
642         struct tldap_control *pgctrl;
643         struct asn1_data *asn1 = NULL;
644
645         asn1 = asn1_init(state);
646         if (asn1 == NULL) {
647                 return NULL;
648         }
649         if (!asn1_push_tag(asn1, ASN1_SEQUENCE(0))) goto err;
650         if (!asn1_write_Integer(asn1, state->page_size)) goto err;
651         if (!asn1_write_OctetString(asn1, state->cookie.data, state->cookie.length)) goto err;
652         if (!asn1_pop_tag(asn1)) goto err;
653         state->asn1 = asn1;
654
655         pgctrl = &state->sctrls[state->num_sctrls-1];
656         pgctrl->oid = TLDAP_CONTROL_PAGEDRESULTS;
657         pgctrl->critical = true;
658         if (!asn1_blob(state->asn1, &pgctrl->value)) {
659                 goto err;
660         }
661         return tldap_search_send(mem_ctx, state->ev, state->ld, state->base,
662                                  state->scope, state->filter, state->attrs,
663                                  state->num_attrs, state->attrsonly,
664                                  state->sctrls, state->num_sctrls,
665                                  state->cctrls, state->num_cctrls,
666                                  state->timelimit, state->sizelimit,
667                                  state->deref);
668
669   err:
670
671         TALLOC_FREE(asn1);
672         return NULL;
673 }
674
675 static void tldap_search_paged_done(struct tevent_req *subreq);
676
677 struct tevent_req *tldap_search_paged_send(TALLOC_CTX *mem_ctx,
678                                            struct tevent_context *ev,
679                                            struct tldap_context *ld,
680                                            const char *base, int scope,
681                                            const char *filter,
682                                            const char **attrs,
683                                            int num_attrs,
684                                            int attrsonly,
685                                            struct tldap_control *sctrls,
686                                            int num_sctrls,
687                                            struct tldap_control *cctrls,
688                                            int num_cctrls,
689                                            int timelimit,
690                                            int sizelimit,
691                                            int deref,
692                                            int page_size)
693 {
694         struct tevent_req *req, *subreq;
695         struct tldap_search_paged_state *state;
696         struct tldap_control empty_control;
697
698         req = tevent_req_create(mem_ctx, &state,
699                                 struct tldap_search_paged_state);
700         if (req == NULL) {
701                 return NULL;
702         }
703         state->ev = ev;
704         state->ld = ld;
705         state->base = base;
706         state->filter = filter;
707         state->scope = scope;
708         state->attrs = attrs;
709         state->num_attrs = num_attrs;
710         state->attrsonly = attrsonly;
711         state->cctrls = cctrls;
712         state->num_cctrls = num_cctrls;
713         state->timelimit = timelimit;
714         state->sizelimit = sizelimit;
715         state->deref = deref;
716
717         state->page_size = page_size;
718         state->asn1 = NULL;
719         state->cookie = data_blob_null;
720
721         ZERO_STRUCT(empty_control);
722
723         state->sctrls = tldap_add_control(state, sctrls, num_sctrls,
724                                           &empty_control);
725         if (tevent_req_nomem(state->sctrls, req)) {
726                 return tevent_req_post(req, ev);
727         }
728         state->num_sctrls = num_sctrls+1;
729
730         subreq = tldap_ship_paged_search(state, state);
731         if (tevent_req_nomem(subreq, req)) {
732                 return tevent_req_post(req, ev);
733         }
734         tevent_req_set_callback(subreq, tldap_search_paged_done, req);
735
736         return req;
737 }
738
739 static void tldap_search_paged_done(struct tevent_req *subreq)
740 {
741         struct tevent_req *req = tevent_req_callback_data(
742                 subreq, struct tevent_req);
743         struct tldap_search_paged_state *state = tevent_req_data(
744                 req, struct tldap_search_paged_state);
745         struct asn1_data *asn1 = NULL;
746         struct tldap_control *pgctrl;
747         TLDAPRC rc;
748         int size;
749
750         rc = tldap_search_recv(subreq, state, &state->result);
751         if (tevent_req_ldap_error(req, rc)) {
752                 return;
753         }
754
755         TALLOC_FREE(state->asn1);
756
757         switch (tldap_msg_type(state->result)) {
758         case TLDAP_RES_SEARCH_ENTRY:
759         case TLDAP_RES_SEARCH_REFERENCE:
760                 tevent_req_notify_callback(req);
761                 return;
762         case TLDAP_RES_SEARCH_RESULT:
763                 break;
764         default:
765                 TALLOC_FREE(subreq);
766                 tevent_req_ldap_error(req, TLDAP_PROTOCOL_ERROR);
767                 return;
768         }
769
770         TALLOC_FREE(subreq);
771
772         /* We've finished one paged search, fire the next */
773
774         pgctrl = tldap_msg_findcontrol(state->result,
775                                        TLDAP_CONTROL_PAGEDRESULTS);
776         if (pgctrl == NULL) {
777                 /* RFC2696 requires the server to return the control */
778                 tevent_req_ldap_error(req, TLDAP_PROTOCOL_ERROR);
779                 return;
780         }
781
782         TALLOC_FREE(state->cookie.data);
783
784         asn1 = asn1_init(talloc_tos());
785         if (tevent_req_nomem(asn1, req)) {
786                 return;
787         }
788
789         asn1_load_nocopy(asn1, pgctrl->value.data, pgctrl->value.length);
790         if (!asn1_start_tag(asn1, ASN1_SEQUENCE(0))) goto err;
791         if (!asn1_read_Integer(asn1, &size)) goto err;
792         if (!asn1_read_OctetString(asn1, state, &state->cookie)) goto err;
793         if (!asn1_end_tag(asn1)) goto err;
794
795         TALLOC_FREE(asn1);
796
797         if (state->cookie.length == 0) {
798                 /* We're done, no cookie anymore */
799                 tevent_req_done(req);
800                 return;
801         }
802
803         TALLOC_FREE(state->result);
804
805         subreq = tldap_ship_paged_search(state, state);
806         if (tevent_req_nomem(subreq, req)) {
807                 return;
808         }
809         tevent_req_set_callback(subreq, tldap_search_paged_done, req);
810
811   err:
812
813         TALLOC_FREE(asn1);
814         tevent_req_ldap_error(req, TLDAP_DECODING_ERROR);
815 }
816
817 TLDAPRC tldap_search_paged_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
818                                 struct tldap_message **pmsg)
819 {
820         struct tldap_search_paged_state *state = tevent_req_data(
821                 req, struct tldap_search_paged_state);
822         TLDAPRC rc;
823
824         if (!tevent_req_is_in_progress(req)
825             && tevent_req_is_ldap_error(req, &rc)) {
826                 return rc;
827         }
828         if (tevent_req_is_in_progress(req)) {
829                 switch (tldap_msg_type(state->result)) {
830                 case TLDAP_RES_SEARCH_ENTRY:
831                 case TLDAP_RES_SEARCH_REFERENCE:
832                         break;
833                 default:
834                         return TLDAP_PROTOCOL_ERROR;
835                 }
836         }
837         *pmsg = talloc_move(mem_ctx, &state->result);
838         return TLDAP_SUCCESS;
839 }