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