0cb0f3fa4b9d7e99bf64c275cfe3ca5eef090967
[samba.git] / source4 / dsdb / samdb / ldb_modules / rootdse.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    rootDSE ldb module
5
6    Copyright (C) Andrew Tridgell 2005
7    Copyright (C) Simo Sorce 2005-2008
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 */
22
23 #include "includes.h"
24 #include "lib/ldb/include/ldb.h"
25 #include "lib/ldb/include/ldb_module.h"
26 #include "system/time.h"
27 #include "dsdb/samdb/samdb.h"
28 #include "version.h"
29 #include "dsdb/samdb/ldb_modules/util.h"
30 #include "libcli/security/security.h"
31 #include "librpc/ndr/libndr.h"
32 #include "auth/auth.h"
33
34 struct private_data {
35         unsigned int num_controls;
36         char **controls;
37         unsigned int num_partitions;
38         struct ldb_dn **partitions;
39 };
40
41 /*
42   return 1 if a specific attribute has been requested
43 */
44 static int do_attribute(const char * const *attrs, const char *name)
45 {
46         return attrs == NULL ||
47                 ldb_attr_in_list(attrs, name) ||
48                 ldb_attr_in_list(attrs, "*");
49 }
50
51 static int do_attribute_explicit(const char * const *attrs, const char *name)
52 {
53         return attrs != NULL && ldb_attr_in_list(attrs, name);
54 }
55
56
57 /*
58   expand a DN attribute to include extended DN information if requested
59  */
60 static int expand_dn_in_message(struct ldb_module *module, struct ldb_message *msg,
61                                 const char *attrname, struct ldb_control *edn_control,
62                                 struct ldb_request *req)
63 {
64         struct ldb_dn *dn, *dn2;
65         struct ldb_val *v;
66         int ret;
67         struct ldb_request *req2;
68         char *dn_string;
69         const char *no_attrs[] = { NULL };
70         struct ldb_result *res;
71         struct ldb_extended_dn_control *edn;
72         TALLOC_CTX *tmp_ctx = talloc_new(req);
73         struct ldb_context *ldb;
74         int edn_type = 0;
75
76         ldb = ldb_module_get_ctx(module);
77
78         edn = talloc_get_type(edn_control->data, struct ldb_extended_dn_control);
79         if (edn) {
80                 edn_type = edn->type;
81         }
82
83         v = discard_const_p(struct ldb_val, ldb_msg_find_ldb_val(msg, attrname));
84         if (v == NULL) {
85                 talloc_free(tmp_ctx);
86                 return LDB_SUCCESS;
87         }
88
89         dn_string = talloc_strndup(tmp_ctx, (const char *)v->data, v->length);
90         if (dn_string == NULL) {
91                 talloc_free(tmp_ctx);
92                 return LDB_ERR_OPERATIONS_ERROR;
93         }
94
95         res = talloc_zero(tmp_ctx, struct ldb_result);
96         if (res == NULL) {
97                 talloc_free(tmp_ctx);
98                 return LDB_ERR_OPERATIONS_ERROR;
99         }
100
101         dn = ldb_dn_new(tmp_ctx, ldb, dn_string);
102         if (!ldb_dn_validate(dn)) {
103                 talloc_free(tmp_ctx);
104                 return LDB_ERR_OPERATIONS_ERROR;
105         }
106
107         ret = ldb_build_search_req(&req2, ldb, tmp_ctx,
108                                    dn,
109                                    LDB_SCOPE_BASE,
110                                    NULL,
111                                    no_attrs,
112                                    NULL,
113                                    res, ldb_search_default_callback,
114                                    req);
115         if (ret != LDB_SUCCESS) {
116                 talloc_free(tmp_ctx);
117                 return ret;
118         }
119
120
121         ret = ldb_request_add_control(req2,
122                                       LDB_CONTROL_EXTENDED_DN_OID,
123                                       edn_control->critical, edn);
124         if (ret != LDB_SUCCESS) {
125                 talloc_free(tmp_ctx);
126                 return ret;
127         }
128
129         ret = ldb_next_request(module, req2);
130         if (ret == LDB_SUCCESS) {
131                 ret = ldb_wait(req2->handle, LDB_WAIT_ALL);
132         }
133         if (ret != LDB_SUCCESS) {
134                 talloc_free(tmp_ctx);
135                 return ret;
136         }
137
138         if (!res || res->count != 1) {
139                 talloc_free(tmp_ctx);
140                 return LDB_ERR_OPERATIONS_ERROR;
141         }
142
143         dn2 = res->msgs[0]->dn;
144
145         v->data = (uint8_t *)ldb_dn_get_extended_linearized(msg->elements, dn2, edn_type);
146         v->length = strlen((char *)v->data);
147
148         if (v->data == NULL) {
149                 talloc_free(tmp_ctx);
150                 return LDB_ERR_OPERATIONS_ERROR;
151         }
152
153         talloc_free(tmp_ctx);
154
155         return LDB_SUCCESS;
156 }
157
158
159 /*
160   add dynamically generated attributes to rootDSE result
161 */
162 static int rootdse_add_dynamic(struct ldb_module *module, struct ldb_message *msg,
163                                const char * const *attrs, struct ldb_request *req)
164 {
165         struct ldb_context *ldb;
166         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
167         char **server_sasl;
168         const struct dsdb_schema *schema;
169         int *val;
170         struct ldb_control *edn_control;
171         const char *dn_attrs[] = {
172                 "configurationNamingContext",
173                 "defaultNamingContext",
174                 "dsServiceName",
175                 "rootDomainNamingContext",
176                 "schemaNamingContext",
177                 "serverName",
178                 NULL
179         };
180
181         ldb = ldb_module_get_ctx(module);
182         schema = dsdb_get_schema(ldb, NULL);
183
184         msg->dn = ldb_dn_new(msg, ldb, NULL);
185
186         /* don't return the distinduishedName, cn and name attributes */
187         ldb_msg_remove_attr(msg, "distinguishedName");
188         ldb_msg_remove_attr(msg, "cn");
189         ldb_msg_remove_attr(msg, "name");
190
191         if (do_attribute(attrs, "currentTime")) {
192                 if (ldb_msg_add_steal_string(msg, "currentTime",
193                                              ldb_timestring(msg, time(NULL))) != 0) {
194                         goto failed;
195                 }
196         }
197
198         if (priv && do_attribute(attrs, "supportedControl")) {
199                 unsigned int i;
200                 for (i = 0; i < priv->num_controls; i++) {
201                         char *control = talloc_strdup(msg, priv->controls[i]);
202                         if (!control) {
203                                 goto failed;
204                         }
205                         if (ldb_msg_add_steal_string(msg, "supportedControl",
206                                                      control) != 0) {
207                                 goto failed;
208                         }
209                 }
210         }
211
212         if (priv && do_attribute(attrs, "namingContexts")) {
213                 unsigned int i;
214                 for (i = 0; i < priv->num_partitions; i++) {
215                         struct ldb_dn *dn = priv->partitions[i];
216                         if (ldb_msg_add_steal_string(msg, "namingContexts",
217                                                      ldb_dn_alloc_linearized(msg, dn)) != 0) {
218                                 goto failed;
219                         }
220                 }
221         }
222
223         server_sasl = talloc_get_type(ldb_get_opaque(ldb, "supportedSASLMechanims"),
224                                        char *);
225         if (server_sasl && do_attribute(attrs, "supportedSASLMechanisms")) {
226                 unsigned int i;
227                 for (i = 0; server_sasl && server_sasl[i]; i++) {
228                         char *sasl_name = talloc_strdup(msg, server_sasl[i]);
229                         if (!sasl_name) {
230                                 goto failed;
231                         }
232                         if (ldb_msg_add_steal_string(msg, "supportedSASLMechanisms",
233                                                      sasl_name) != 0) {
234                                 goto failed;
235                         }
236                 }
237         }
238
239         if (do_attribute(attrs, "highestCommittedUSN")) {
240                 uint64_t seq_num;
241                 int ret = ldb_sequence_number(ldb, LDB_SEQ_HIGHEST_SEQ, &seq_num);
242                 if (ret == LDB_SUCCESS) {
243                         if (ldb_msg_add_fmt(msg, "highestCommittedUSN",
244                                             "%llu", (unsigned long long)seq_num) != 0) {
245                                 goto failed;
246                         }
247                 }
248         }
249
250         if (schema && do_attribute_explicit(attrs, "dsSchemaAttrCount")) {
251                 struct dsdb_attribute *cur;
252                 unsigned int n = 0;
253
254                 for (cur = schema->attributes; cur; cur = cur->next) {
255                         n++;
256                 }
257
258                 if (ldb_msg_add_fmt(msg, "dsSchemaAttrCount",
259                                     "%u", n) != 0) {
260                         goto failed;
261                 }
262         }
263
264         if (schema && do_attribute_explicit(attrs, "dsSchemaClassCount")) {
265                 struct dsdb_class *cur;
266                 unsigned int n = 0;
267
268                 for (cur = schema->classes; cur; cur = cur->next) {
269                         n++;
270                 }
271
272                 if (ldb_msg_add_fmt(msg, "dsSchemaClassCount",
273                                     "%u", n) != 0) {
274                         goto failed;
275                 }
276         }
277
278         if (schema && do_attribute_explicit(attrs, "dsSchemaPrefixCount")) {
279                 if (ldb_msg_add_fmt(msg, "dsSchemaPrefixCount",
280                                     "%u", schema->prefixmap->length) != 0) {
281                         goto failed;
282                 }
283         }
284
285         if (do_attribute_explicit(attrs, "validFSMOs")) {
286                 const struct dsdb_naming_fsmo *naming_fsmo;
287                 const struct dsdb_pdc_fsmo *pdc_fsmo;
288                 const char *dn_str;
289
290                 if (schema && schema->fsmo.we_are_master) {
291                         dn_str = ldb_dn_get_linearized(ldb_get_schema_basedn(ldb));
292                         if (dn_str && dn_str[0]) {
293                                 if (ldb_msg_add_fmt(msg, "validFSMOs", "%s", dn_str) != 0) {
294                                         goto failed;
295                                 }
296                         }
297                 }
298
299                 naming_fsmo = talloc_get_type(ldb_get_opaque(ldb, "dsdb_naming_fsmo"),
300                                               struct dsdb_naming_fsmo);
301                 if (naming_fsmo && naming_fsmo->we_are_master) {
302                         dn_str = ldb_dn_get_linearized(samdb_partitions_dn(ldb, msg));
303                         if (dn_str && dn_str[0]) {
304                                 if (ldb_msg_add_fmt(msg, "validFSMOs", "%s", dn_str) != 0) {
305                                         goto failed;
306                                 }
307                         }
308                 }
309
310                 pdc_fsmo = talloc_get_type(ldb_get_opaque(ldb, "dsdb_pdc_fsmo"),
311                                            struct dsdb_pdc_fsmo);
312                 if (pdc_fsmo && pdc_fsmo->we_are_master) {
313                         dn_str = ldb_dn_get_linearized(ldb_get_default_basedn(ldb));
314                         if (dn_str && dn_str[0]) {
315                                 if (ldb_msg_add_fmt(msg, "validFSMOs", "%s", dn_str) != 0) {
316                                         goto failed;
317                                 }
318                         }
319                 }
320         }
321
322         if (do_attribute_explicit(attrs, "vendorVersion")) {
323                 if (ldb_msg_add_fmt(msg, "vendorVersion",
324                                     "%s", SAMBA_VERSION_STRING) != 0) {
325                         goto failed;
326                 }
327         }
328
329         if (priv && do_attribute(attrs, "domainFunctionality")) {
330                 if (ldb_msg_add_fmt(msg, "domainFunctionality",
331                                     "%d", dsdb_functional_level(ldb)) != 0) {
332                         goto failed;
333                 }
334         }
335
336         if (priv && do_attribute(attrs, "forestFunctionality")
337             && (val = talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int))) {
338                 if (ldb_msg_add_fmt(msg, "forestFunctionality",
339                                     "%d", *val) != 0) {
340                         goto failed;
341                 }
342         }
343
344         if (priv && do_attribute(attrs, "domainControllerFunctionality")
345             && (val = talloc_get_type(ldb_get_opaque(ldb, "domainControllerFunctionality"), int))) {
346                 if (ldb_msg_add_fmt(msg, "domainControllerFunctionality",
347                                     "%d", *val) != 0) {
348                         goto failed;
349                 }
350         }
351
352         edn_control = ldb_request_get_control(req, LDB_CONTROL_EXTENDED_DN_OID);
353
354         /* if the client sent us the EXTENDED_DN control then we need
355            to expand the DNs to have GUID and SID. W2K8 join relies on
356            this */
357         if (edn_control) {
358                 unsigned int i;
359                 int ret;
360                 for (i=0; dn_attrs[i]; i++) {
361                         if (!do_attribute(attrs, dn_attrs[i])) continue;
362                         ret = expand_dn_in_message(module, msg, dn_attrs[i],
363                                                    edn_control, req);
364                         if (ret != LDB_SUCCESS) {
365                                 DEBUG(0,(__location__ ": Failed to expand DN in rootDSE for %s\n",
366                                          dn_attrs[i]));
367                                 goto failed;
368                         }
369                 }
370         }
371
372         if (do_attribute(attrs, "isGlobalCatalogReady")) {
373                 /* MS-ADTS 3.1.1.3.2.10
374                    Note, we should only return true here is we have
375                    completed at least one synchronisation. As both
376                    provision and vampire do a full sync, this means we
377                    can return true is the gc bit is set in the NTDSDSA
378                    options */
379                 if (ldb_msg_add_fmt(msg, "isGlobalCatalogReady",
380                                     "%s", samdb_is_gc(ldb)?"TRUE":"FALSE") != 0) {
381                         goto failed;
382                 }
383         }
384
385         if (do_attribute_explicit(attrs, "tokenGroups")) {
386                 unsigned int i;
387                 /* Obtain the user's session_info */
388                 struct auth_session_info *session_info
389                         = (struct auth_session_info *)ldb_get_opaque(ldb, "sessionInfo");
390                 if (session_info && session_info->security_token) {
391                         /* The list of groups this user is in */
392                         for (i = 0; i < session_info->security_token->num_sids; i++) {
393                                 if (samdb_msg_add_dom_sid(ldb, msg, msg,
394                                                           "tokenGroups",
395                                                           session_info->security_token->sids[i]) != 0) {
396                                         goto failed;
397                                 }
398                         }
399                 }
400         }
401
402         /* TODO: lots more dynamic attributes should be added here */
403
404         return LDB_SUCCESS;
405
406 failed:
407         return LDB_ERR_OPERATIONS_ERROR;
408 }
409
410 /*
411   handle search requests
412 */
413
414 struct rootdse_context {
415         struct ldb_module *module;
416         struct ldb_request *req;
417 };
418
419 static struct rootdse_context *rootdse_init_context(struct ldb_module *module,
420                                                     struct ldb_request *req)
421 {
422         struct ldb_context *ldb;
423         struct rootdse_context *ac;
424
425         ldb = ldb_module_get_ctx(module);
426
427         ac = talloc_zero(req, struct rootdse_context);
428         if (ac == NULL) {
429                 ldb_set_errstring(ldb, "Out of Memory");
430                 return NULL;
431         }
432
433         ac->module = module;
434         ac->req = req;
435
436         return ac;
437 }
438
439 static int rootdse_callback(struct ldb_request *req, struct ldb_reply *ares)
440 {
441         struct rootdse_context *ac;
442         int ret;
443
444         ac = talloc_get_type(req->context, struct rootdse_context);
445
446         if (!ares) {
447                 return ldb_module_done(ac->req, NULL, NULL,
448                                         LDB_ERR_OPERATIONS_ERROR);
449         }
450         if (ares->error != LDB_SUCCESS) {
451                 return ldb_module_done(ac->req, ares->controls,
452                                         ares->response, ares->error);
453         }
454
455         switch (ares->type) {
456         case LDB_REPLY_ENTRY:
457                 /*
458                  * if the client explicit asks for the 'netlogon' attribute
459                  * the reply_entry needs to be skipped
460                  */
461                 if (ac->req->op.search.attrs &&
462                     ldb_attr_in_list(ac->req->op.search.attrs, "netlogon")) {
463                         talloc_free(ares);
464                         return LDB_SUCCESS;
465                 }
466
467                 /* for each record returned post-process to add any dynamic
468                    attributes that have been asked for */
469                 ret = rootdse_add_dynamic(ac->module, ares->message,
470                                           ac->req->op.search.attrs, ac->req);
471                 if (ret != LDB_SUCCESS) {
472                         talloc_free(ares);
473                         return ldb_module_done(ac->req, NULL, NULL, ret);
474                 }
475
476                 return ldb_module_send_entry(ac->req, ares->message, ares->controls);
477
478         case LDB_REPLY_REFERRAL:
479                 /* should we allow the backend to return referrals in this case
480                  * ?? */
481                 break;
482
483         case LDB_REPLY_DONE:
484                 return ldb_module_done(ac->req, ares->controls,
485                                         ares->response, ares->error);
486         }
487
488         talloc_free(ares);
489         return LDB_SUCCESS;
490 }
491
492 static int rootdse_search(struct ldb_module *module, struct ldb_request *req)
493 {
494         struct ldb_context *ldb;
495         struct rootdse_context *ac;
496         struct ldb_request *down_req;
497         int ret;
498
499         ldb = ldb_module_get_ctx(module);
500
501         /* see if its for the rootDSE - only a base search on the "" DN qualifies */
502         if (!(req->op.search.scope == LDB_SCOPE_BASE && ldb_dn_is_null(req->op.search.base))) {
503                 /* Otherwise, pass down to the rest of the stack */
504                 return ldb_next_request(module, req);
505         }
506
507         ac = rootdse_init_context(module, req);
508         if (ac == NULL) {
509                 return LDB_ERR_OPERATIONS_ERROR;
510         }
511
512         /* in our db we store the rootDSE with a DN of @ROOTDSE */
513         ret = ldb_build_search_req(&down_req, ldb, ac,
514                                         ldb_dn_new(ac, ldb, "@ROOTDSE"),
515                                         LDB_SCOPE_BASE,
516                                         NULL,
517                                         req->op.search.attrs,
518                                         NULL,/* for now skip the controls from the client */
519                                         ac, rootdse_callback,
520                                         req);
521         if (ret != LDB_SUCCESS) {
522                 return ret;
523         }
524
525         return ldb_next_request(module, down_req);
526 }
527
528 static int rootdse_register_control(struct ldb_module *module, struct ldb_request *req)
529 {
530         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
531         char **list;
532
533         list = talloc_realloc(priv, priv->controls, char *, priv->num_controls + 1);
534         if (!list) {
535                 return LDB_ERR_OPERATIONS_ERROR;
536         }
537
538         list[priv->num_controls] = talloc_strdup(list, req->op.reg_control.oid);
539         if (!list[priv->num_controls]) {
540                 return LDB_ERR_OPERATIONS_ERROR;
541         }
542
543         priv->num_controls += 1;
544         priv->controls = list;
545
546         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
547 }
548
549 static int rootdse_register_partition(struct ldb_module *module, struct ldb_request *req)
550 {
551         struct private_data *priv = talloc_get_type(ldb_module_get_private(module), struct private_data);
552         struct ldb_dn **list;
553
554         list = talloc_realloc(priv, priv->partitions, struct ldb_dn *, priv->num_partitions + 1);
555         if (!list) {
556                 return LDB_ERR_OPERATIONS_ERROR;
557         }
558
559         list[priv->num_partitions] = ldb_dn_copy(list, req->op.reg_partition.dn);
560         if (!list[priv->num_partitions]) {
561                 return LDB_ERR_OPERATIONS_ERROR;
562         }
563
564         priv->num_partitions += 1;
565         priv->partitions = list;
566
567         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);
568 }
569
570
571 static int rootdse_request(struct ldb_module *module, struct ldb_request *req)
572 {
573         switch (req->operation) {
574
575         case LDB_REQ_REGISTER_CONTROL:
576                 return rootdse_register_control(module, req);
577         case LDB_REQ_REGISTER_PARTITION:
578                 return rootdse_register_partition(module, req);
579
580         default:
581                 break;
582         }
583         return ldb_next_request(module, req);
584 }
585
586 static int rootdse_init(struct ldb_module *module)
587 {
588         int ret;
589         struct ldb_context *ldb;
590         struct ldb_result *res;
591         struct private_data *data;
592         const char *attrs[] = { "msDS-Behavior-Version", NULL };
593         const char *ds_attrs[] = { "dsServiceName", NULL };
594         TALLOC_CTX *mem_ctx;
595
596         ldb = ldb_module_get_ctx(module);
597
598         data = talloc_zero(module, struct private_data);
599         if (data == NULL) {
600                 ldb_oom(ldb);
601                 return LDB_ERR_OPERATIONS_ERROR;
602         }
603
604         data->num_controls = 0;
605         data->controls = NULL;
606         data->num_partitions = 0;
607         data->partitions = NULL;
608         ldb_module_set_private(module, data);
609
610         ldb_set_default_dns(ldb);
611
612         ret = ldb_next_init(module);
613
614         if (ret != LDB_SUCCESS) {
615                 return ret;
616         }
617
618         mem_ctx = talloc_new(data);
619         if (!mem_ctx) {
620                 ldb_oom(ldb);
621                 return LDB_ERR_OPERATIONS_ERROR;
622         }
623
624         /* Now that the partitions are set up, do a search for:
625            - domainControllerFunctionality
626            - domainFunctionality
627            - forestFunctionality
628
629            Then stuff these values into an opaque
630         */
631         ret = ldb_search(ldb, mem_ctx, &res,
632                          ldb_get_default_basedn(ldb),
633                          LDB_SCOPE_BASE, attrs, NULL);
634         if (ret == LDB_SUCCESS && res->count == 1) {
635                 int domain_behaviour_version
636                         = ldb_msg_find_attr_as_int(res->msgs[0],
637                                                    "msDS-Behavior-Version", -1);
638                 if (domain_behaviour_version != -1) {
639                         int *val = talloc(ldb, int);
640                         if (!val) {
641                                 ldb_oom(ldb);
642                                 talloc_free(mem_ctx);
643                                 return LDB_ERR_OPERATIONS_ERROR;
644                         }
645                         *val = domain_behaviour_version;
646                         ret = ldb_set_opaque(ldb, "domainFunctionality", val);
647                         if (ret != LDB_SUCCESS) {
648                                 talloc_free(mem_ctx);
649                                 return ret;
650                         }
651                 }
652         }
653
654         ret = ldb_search(ldb, mem_ctx, &res,
655                          samdb_partitions_dn(ldb, mem_ctx),
656                          LDB_SCOPE_BASE, attrs, NULL);
657         if (ret == LDB_SUCCESS && res->count == 1) {
658                 int forest_behaviour_version
659                         = ldb_msg_find_attr_as_int(res->msgs[0],
660                                                    "msDS-Behavior-Version", -1);
661                 if (forest_behaviour_version != -1) {
662                         int *val = talloc(ldb, int);
663                         if (!val) {
664                                 ldb_oom(ldb);
665                                 talloc_free(mem_ctx);
666                                 return LDB_ERR_OPERATIONS_ERROR;
667                         }
668                         *val = forest_behaviour_version;
669                         ret = ldb_set_opaque(ldb, "forestFunctionality", val);
670                         if (ret != LDB_SUCCESS) {
671                                 talloc_free(mem_ctx);
672                                 return ret;
673                         }
674                 }
675         }
676
677         ret = ldb_search(ldb, mem_ctx, &res,
678                          ldb_dn_new(mem_ctx, ldb, ""),
679                          LDB_SCOPE_BASE, ds_attrs, NULL);
680         if (ret == LDB_SUCCESS && res->count == 1) {
681                 struct ldb_dn *ds_dn
682                         = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0],
683                                                   "dsServiceName");
684                 if (ds_dn) {
685                         ret = ldb_search(ldb, mem_ctx, &res, ds_dn,
686                                          LDB_SCOPE_BASE, attrs, NULL);
687                         if (ret == LDB_SUCCESS && res->count == 1) {
688                                 int domain_controller_behaviour_version
689                                         = ldb_msg_find_attr_as_int(res->msgs[0],
690                                                                    "msDS-Behavior-Version", -1);
691                                 if (domain_controller_behaviour_version != -1) {
692                                         int *val = talloc(ldb, int);
693                                         if (!val) {
694                                                 ldb_oom(ldb);
695                                                 talloc_free(mem_ctx);
696                                         return LDB_ERR_OPERATIONS_ERROR;
697                                         }
698                                         *val = domain_controller_behaviour_version;
699                                         ret = ldb_set_opaque(ldb,
700                                                              "domainControllerFunctionality", val);
701                                         if (ret != LDB_SUCCESS) {
702                                                 talloc_free(mem_ctx);
703                                                 return ret;
704                                         }
705                                 }
706                         }
707                 }
708         }
709
710         talloc_free(mem_ctx);
711
712         return LDB_SUCCESS;
713 }
714
715 /*
716  * This function gets the string SCOPE_DN:OPTIONAL_FEATURE_GUID and parse it
717  * to a DN and a GUID object
718  */
719 static int get_optional_feature_dn_guid(struct ldb_request *req, struct ldb_context *ldb,
720                                                 TALLOC_CTX *mem_ctx,
721                                                 struct ldb_dn **op_feature_scope_dn,
722                                                 struct GUID *op_feature_guid)
723 {
724         const struct ldb_message *msg = req->op.mod.message;
725         const char *ldb_val_str;
726         char *dn, *guid;
727         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
728         NTSTATUS status;
729
730         ldb_val_str = ldb_msg_find_attr_as_string(msg, "enableOptionalFeature", NULL);
731         if (!ldb_val_str) {
732                 ldb_set_errstring(ldb,
733                                   "rootdse: unable to find 'enableOptionalFeature'!");
734                 return LDB_ERR_UNWILLING_TO_PERFORM;
735         }
736
737         guid = strchr(ldb_val_str, ':');
738         if (!guid) {
739                 ldb_set_errstring(ldb,
740                                   "rootdse: unable to find GUID in 'enableOptionalFeature'!");
741                 return LDB_ERR_UNWILLING_TO_PERFORM;
742         }
743         status = GUID_from_string(guid+1, op_feature_guid);
744         if (!NT_STATUS_IS_OK(status)) {
745                 ldb_set_errstring(ldb,
746                                   "rootdse: bad GUID in 'enableOptionalFeature'!");
747                 return LDB_ERR_UNWILLING_TO_PERFORM;
748         }
749
750         dn = talloc_strndup(tmp_ctx, ldb_val_str, guid-ldb_val_str);
751         if (!dn) {
752                 ldb_set_errstring(ldb,
753                                   "rootdse: bad DN in 'enableOptionalFeature'!");
754                 return LDB_ERR_UNWILLING_TO_PERFORM;
755         }
756
757         *op_feature_scope_dn = ldb_dn_new(mem_ctx, ldb, dn);
758
759         talloc_free(tmp_ctx);
760         return LDB_SUCCESS;
761 }
762
763 /*
764  * This function gets the OPTIONAL_FEATURE_GUID and looks for the optional feature
765  * ldb_message object.
766  */
767 static int dsdb_find_optional_feature(struct ldb_module *module, struct ldb_context *ldb,
768                                 TALLOC_CTX *mem_ctx, struct GUID op_feature_guid, struct ldb_message **msg)
769 {
770         struct ldb_result *res;
771         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
772         int ret;
773
774         ret = dsdb_module_search(module, tmp_ctx, &res, NULL, LDB_SCOPE_SUBTREE,
775                                 NULL,
776                                 DSDB_FLAG_NEXT_MODULE |
777                                 DSDB_SEARCH_SEARCH_ALL_PARTITIONS,
778                                  "(&(objectClass=msDS-OptionalFeature)"
779                                  "(msDS-OptionalFeatureGUID=%s))",GUID_string(tmp_ctx, &op_feature_guid));
780
781         if (ret != LDB_SUCCESS) {
782                 talloc_free(tmp_ctx);
783                 return ret;
784         }
785         if (res->count == 0) {
786                 talloc_free(tmp_ctx);
787                 return LDB_ERR_NO_SUCH_OBJECT;
788         }
789         if (res->count != 1) {
790                 ldb_asprintf_errstring(ldb,
791                                        "More than one object found matching optional feature GUID %s\n",
792                                        GUID_string(tmp_ctx, &op_feature_guid));
793                 talloc_free(tmp_ctx);
794                 return LDB_ERR_OPERATIONS_ERROR;
795         }
796
797         *msg = talloc_steal(mem_ctx, res->msgs[0]);
798
799         talloc_free(tmp_ctx);
800         return LDB_SUCCESS;
801 }
802
803 static int rootdse_enable_recycle_bin(struct ldb_module *module,struct ldb_context *ldb,
804                         TALLOC_CTX *mem_ctx, struct ldb_dn *op_feature_scope_dn,
805                         struct ldb_message *op_feature_msg)
806 {
807         int ret;
808         const int domain_func_level = dsdb_functional_level(ldb);
809         struct ldb_dn *ntds_settings_dn;
810         TALLOC_CTX *tmp_ctx;
811         unsigned int el_count = 0;
812         struct ldb_message *msg;
813
814         ret = ldb_msg_find_attr_as_int(op_feature_msg, "msDS-RequiredForestBehaviorVersion", 0);
815         if (domain_func_level < ret){
816                 ldb_asprintf_errstring(ldb,
817                                        "rootdse_enable_recycle_bin: Domain functional level must be at least %d\n",
818                                        ret);
819                 return LDB_ERR_UNWILLING_TO_PERFORM;
820         }
821
822         tmp_ctx = talloc_new(mem_ctx);
823         ntds_settings_dn = samdb_ntds_settings_dn(ldb);
824         if (!ntds_settings_dn) {
825                 DEBUG(0, (__location__ ": Failed to find NTDS settings DN\n"));
826                 ret = LDB_ERR_OPERATIONS_ERROR;
827                 talloc_free(tmp_ctx);
828                 return ret;
829         }
830
831         ntds_settings_dn = ldb_dn_copy(tmp_ctx, ntds_settings_dn);
832         if (!ntds_settings_dn) {
833                 DEBUG(0, (__location__ ": Failed to copy NTDS settings DN\n"));
834                 ret = LDB_ERR_OPERATIONS_ERROR;
835                 talloc_free(tmp_ctx);
836                 return ret;
837         }
838
839         msg = ldb_msg_new(tmp_ctx);
840         msg->dn = ntds_settings_dn;
841
842         ldb_msg_add_linearized_dn(msg, "msDS-EnabledFeature", op_feature_msg->dn);
843         msg->elements[el_count++].flags = LDB_FLAG_MOD_ADD;
844
845         ret = dsdb_module_modify(module, msg, DSDB_FLAG_NEXT_MODULE);
846         if (ret != LDB_SUCCESS) {
847                 ldb_asprintf_errstring(ldb,
848                                        "rootdse_enable_recycle_bin: Failed to modify object %s - %s",
849                                        ldb_dn_get_linearized(ntds_settings_dn),
850                                        ldb_errstring(ldb));
851                 talloc_free(tmp_ctx);
852                 return ret;
853         }
854
855         msg->dn = op_feature_scope_dn;
856         ret = dsdb_module_modify(module, msg, DSDB_FLAG_NEXT_MODULE);
857         if (ret != LDB_SUCCESS) {
858                 ldb_asprintf_errstring(ldb,
859                                        "rootdse_enable_recycle_bin: Failed to modify object %s - %s",
860                                        ldb_dn_get_linearized(op_feature_scope_dn),
861                                        ldb_errstring(ldb));
862                 talloc_free(tmp_ctx);
863                 return ret;
864         }
865
866         return LDB_SUCCESS;
867 }
868
869 static int rootdse_enableoptionalfeature(struct ldb_module *module, struct ldb_request *req)
870 {
871         /*
872           steps:
873                - check for system (only system can enable features)
874                - extract GUID from the request
875                - find the feature object
876                - check functional level, must be at least msDS-RequiredForestBehaviorVersion
877                - check if it is already enabled (if enabled return LDAP_ATTRIBUTE_OR_VALUE_EXISTS) - probably not needed, just return error from the add/modify
878                - add/modify objects (see ntdsconnection code for an example)
879          */
880
881         struct ldb_context *ldb = ldb_module_get_ctx(module);
882         struct GUID op_feature_guid;
883         struct ldb_dn *op_feature_scope_dn;
884         struct ldb_message *op_feature_msg;
885         struct auth_session_info *session_info =
886                                 (struct auth_session_info *)ldb_get_opaque(ldb, "sessionInfo");
887         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
888         int ret;
889         const char *guid_string;
890
891         if (security_session_user_level(session_info, NULL) != SECURITY_SYSTEM) {
892                 ldb_set_errstring(ldb, "rootdse: Insufficient rights for enableoptionalfeature");
893                 return LDB_ERR_UNWILLING_TO_PERFORM;
894         }
895
896         ret = get_optional_feature_dn_guid(req, ldb, tmp_ctx, &op_feature_scope_dn, &op_feature_guid);
897         if (ret != LDB_SUCCESS) {
898                 talloc_free(tmp_ctx);
899                 return ret;
900         }
901
902         guid_string = GUID_string(tmp_ctx, &op_feature_guid);
903         if (!guid_string) {
904                 ldb_set_errstring(ldb, "rootdse: bad optional feature GUID");
905                 return LDB_ERR_UNWILLING_TO_PERFORM;
906         }
907
908         ret = dsdb_find_optional_feature(module, ldb, tmp_ctx, op_feature_guid, &op_feature_msg);
909         if (ret != LDB_SUCCESS) {
910                 ldb_asprintf_errstring(ldb,
911                                        "rootdse: unable to find optional feature for %s - %s",
912                                        guid_string, ldb_errstring(ldb));
913                 talloc_free(tmp_ctx);
914                 return ret;
915         }
916
917         if (strcasecmp(DS_GUID_FEATURE_RECYCLE_BIN, guid_string) == 0) {
918                         ret = rootdse_enable_recycle_bin(module, ldb,
919                                                          tmp_ctx, op_feature_scope_dn,
920                                                          op_feature_msg);
921         } else {
922                 ldb_asprintf_errstring(ldb,
923                                        "rootdse: unknown optional feature %s",
924                                        guid_string);
925                 talloc_free(tmp_ctx);
926                 return LDB_ERR_UNWILLING_TO_PERFORM;
927         }
928         if (ret != LDB_SUCCESS) {
929                 ldb_asprintf_errstring(ldb,
930                                        "rootdse: failed to set optional feature for %s - %s",
931                                        guid_string, ldb_errstring(ldb));
932                 talloc_free(tmp_ctx);
933                 return ret;
934         }
935
936         talloc_free(tmp_ctx);
937         return ldb_module_done(req, NULL, NULL, LDB_SUCCESS);;
938 }
939
940 static int rootdse_schemaupdatenow(struct ldb_module *module, struct ldb_request *req)
941 {
942         struct ldb_context *ldb = ldb_module_get_ctx(module);
943         struct ldb_result *ext_res;
944         int ret;
945         struct ldb_dn *schema_dn;
946
947         schema_dn = ldb_get_schema_basedn(ldb);
948         if (!schema_dn) {
949                 ldb_reset_err_string(ldb);
950                 ldb_debug(ldb, LDB_DEBUG_WARNING,
951                           "rootdse_modify: no schema dn present: (skip ldb_extended call)\n");
952                 return ldb_next_request(module, req);
953         }
954
955         ret = ldb_extended(ldb, DSDB_EXTENDED_SCHEMA_UPDATE_NOW_OID, schema_dn, &ext_res);
956         if (ret != LDB_SUCCESS) {
957                 return LDB_ERR_OPERATIONS_ERROR;
958         }
959
960         talloc_free(ext_res);
961         return ldb_module_done(req, NULL, NULL, ret);
962 }
963
964 static int rootdse_add(struct ldb_module *module, struct ldb_request *req)
965 {
966         struct ldb_context *ldb = ldb_module_get_ctx(module);
967
968         /*
969                 If dn is not "" we should let it pass through
970         */
971         if (!ldb_dn_is_null(req->op.add.message->dn)) {
972                 return ldb_next_request(module, req);
973         }
974
975         ldb_set_errstring(ldb, "rootdse_add: you cannot add a new rootdse entry!");
976         return LDB_ERR_NAMING_VIOLATION;
977 }
978
979 static int rootdse_modify(struct ldb_module *module, struct ldb_request *req)
980 {
981         struct ldb_context *ldb = ldb_module_get_ctx(module);
982
983         /*
984                 If dn is not "" we should let it pass through
985         */
986         if (!ldb_dn_is_null(req->op.mod.message->dn)) {
987                 return ldb_next_request(module, req);
988         }
989
990         /*
991                 dn is empty so check for schemaUpdateNow attribute
992                 "The type of modification and values specified in the LDAP modify operation do not matter." MSDN
993         */
994         if (ldb_msg_find_element(req->op.mod.message, "schemaUpdateNow")) {
995                 return rootdse_schemaupdatenow(module, req);
996         }
997
998         if (ldb_msg_find_element(req->op.mod.message, "enableOptionalFeature")) {
999                 return rootdse_enableoptionalfeature(module, req);
1000         }
1001
1002         ldb_set_errstring(ldb, "rootdse_modify: unknown attribute to change!");
1003         return LDB_ERR_UNWILLING_TO_PERFORM;
1004 }
1005
1006 static int rootdse_delete(struct ldb_module *module, struct ldb_request *req)
1007 {
1008         struct ldb_context *ldb = ldb_module_get_ctx(module);
1009
1010         /*
1011                 If dn is not "" we should let it pass through
1012         */
1013         if (!ldb_dn_is_null(req->op.del.dn)) {
1014                 return ldb_next_request(module, req);
1015         }
1016
1017         ldb_set_errstring(ldb, "rootdse_remove: you cannot delete the rootdse entry!");
1018         return LDB_ERR_NO_SUCH_OBJECT;
1019 }
1020
1021 _PUBLIC_ const struct ldb_module_ops ldb_rootdse_module_ops = {
1022         .name           = "rootdse",
1023         .init_context   = rootdse_init,
1024         .search         = rootdse_search,
1025         .request        = rootdse_request,
1026         .add            = rootdse_add,
1027         .modify         = rootdse_modify,
1028         .del            = rootdse_delete
1029 };