r26599: Attempt to also support provisioning using Python in the BECOME-DC test.
[ira/wip.git] / source / torture / libnet / libnet_BecomeDC.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    libnet_BecomeDC() tests
5
6    Copyright (C) Stefan Metzmacher <metze@samba.org> 2006
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "lib/cmdline/popt_common.h"
24 #include "torture/torture.h"
25 #include "torture/rpc/rpc.h"
26 #include "libnet/libnet.h"
27 #include "lib/events/events.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "lib/util/dlinklist.h"
30 #include "lib/ldb/include/ldb.h"
31 #include "lib/ldb/include/ldb_errors.h"
32 #include "librpc/ndr/libndr.h"
33 #include "librpc/gen_ndr/ndr_drsuapi.h"
34 #include "librpc/gen_ndr/ndr_drsblobs.h"
35 #include "librpc/gen_ndr/ndr_misc.h"
36 #include "system/time.h"
37 #include "auth/auth.h"
38 #include "lib/ldb_wrap.h"
39
40 struct test_become_dc_state {
41         struct libnet_context *ctx;
42         struct torture_context *tctx;
43         const char *netbios_name;
44         struct test_join *tj;
45         struct cli_credentials *machine_account;
46         struct dsdb_schema *self_made_schema;
47         const struct dsdb_schema *schema;
48
49         struct ldb_context *ldb;
50
51         struct {
52                 uint32_t object_count;
53                 struct drsuapi_DsReplicaObjectListItemEx *first_object;
54                 struct drsuapi_DsReplicaObjectListItemEx *last_object;
55         } schema_part;
56
57         struct {
58                 const char *samdb_ldb;
59                 const char *domaindn_ldb;
60                 const char *configdn_ldb;
61                 const char *schemadn_ldb;
62                 const char *secrets_ldb;
63                 const char *secrets_keytab;
64         } path;
65 };
66
67 static NTSTATUS test_become_dc_check_options(void *private_data,
68                                              const struct libnet_BecomeDC_CheckOptions *o)
69 {
70         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
71
72         DEBUG(0,("Become DC [%s] of Domain[%s]/[%s]\n",
73                 s->netbios_name,
74                 o->domain->netbios_name, o->domain->dns_name));
75
76         DEBUG(0,("Promotion Partner is Server[%s] from Site[%s]\n",
77                 o->source_dsa->dns_name, o->source_dsa->site_name));
78
79         DEBUG(0,("Options:crossRef behavior_version[%u]\n"
80                        "\tschema object_version[%u]\n"
81                        "\tdomain behavior_version[%u]\n"
82                        "\tdomain w2k3_update_revision[%u]\n", 
83                 o->forest->crossref_behavior_version,
84                 o->forest->schema_object_version,
85                 o->domain->behavior_version,
86                 o->domain->w2k3_update_revision));
87
88         return NT_STATUS_OK;
89 }
90
91 #ifndef PROVISION_PYTHON
92 #include "lib/appweb/ejs/ejs.h"
93 #include "lib/appweb/ejs/ejsInternal.h"
94 #include "scripting/ejs/smbcalls.h"
95
96 static EjsId eid;
97 static int ejs_error;
98
99 static void test_ejs_exception(const char *reason)
100 {
101         Ejs *ep = ejsPtr(eid);
102         ejsSetErrorMsg(eid, "%s", reason);
103         fprintf(stderr, "%s", ep->error);
104         ejs_error = 127;
105 }
106
107 static int test_run_ejs(char *script)
108 {
109         EjsHandle handle = 0;
110         MprVar result;
111         char *emsg;
112         TALLOC_CTX *mem_ctx = talloc_new(NULL);
113         struct MprVar *return_var;
114
115         mprSetCtx(mem_ctx);
116
117         if (ejsOpen(NULL, NULL, NULL) != 0) {
118                 d_printf("ejsOpen(): unable to initialise EJS subsystem\n");
119                 ejs_error = 127;
120                 goto failed;
121         }
122
123         smb_setup_ejs_functions(test_ejs_exception);
124
125         if ((eid = ejsOpenEngine(handle, 0)) == (EjsId)-1) {
126                 d_printf("smbscript: ejsOpenEngine(): unable to initialise an EJS engine\n");
127                 ejs_error = 127;
128                 goto failed;
129         }
130
131         mprSetVar(ejsGetGlobalObject(eid), "ARGV", mprList("ARGV", NULL));
132
133         /* run the script */
134         if (ejsEvalScript(eid, script, &result, &emsg) == -1) {
135                 d_printf("smbscript: ejsEvalScript(): %s\n", emsg);
136                 if (ejs_error == 0) ejs_error = 127;
137                 goto failed;
138         }
139
140         return_var = ejsGetReturnValue(eid);
141         ejs_error = mprVarToNumber(return_var);
142
143 failed:
144         ejsClose();
145         talloc_free(mem_ctx);
146         return ejs_error;
147 }
148
149 static NTSTATUS test_become_dc_prepare_db(void *private_data,
150                                           const struct libnet_BecomeDC_PrepareDB *p)
151 {
152         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
153         char *ejs;
154         int ret;
155         bool ok;
156
157         DEBUG(0,("New Server[%s] in Site[%s]\n",
158                 p->dest_dsa->dns_name, p->dest_dsa->site_name));
159
160         DEBUG(0,("DSA Instance [%s]\n"
161                 "\tobjectGUID[%s]\n"
162                 "\tinvocationId[%s]\n",
163                 p->dest_dsa->ntds_dn_str,
164                 GUID_string(s, &p->dest_dsa->ntds_guid),
165                 GUID_string(s, &p->dest_dsa->invocation_id)));
166
167         DEBUG(0,("Pathes under PRIVATEDIR[%s]\n"
168                  "SAMDB[%s] SECRETS[%s] KEYTAB[%s]\n",
169                 lp_private_dir(s->tctx->lp_ctx),
170                 s->path.samdb_ldb,
171                 s->path.secrets_ldb,
172                 s->path.secrets_keytab));
173
174         DEBUG(0,("Schema Partition[%s => %s]\n",
175                 p->forest->schema_dn_str, s->path.schemadn_ldb));
176
177         DEBUG(0,("Config Partition[%s => %s]\n",
178                 p->forest->config_dn_str, s->path.configdn_ldb));
179
180         DEBUG(0,("Domain Partition[%s => %s]\n",
181                 p->domain->dn_str, s->path.domaindn_ldb));
182
183         ejs = talloc_asprintf(s,
184                 "libinclude(\"base.js\");\n"
185                 "libinclude(\"provision.js\");\n"
186                 "\n"
187                 "function message() { print(vsprintf(arguments)); }\n"
188                 "\n"
189                 "var subobj = provision_guess();\n"
190                 "subobj.ROOTDN       = \"%s\";\n"
191                 "subobj.DOMAINDN     = \"%s\";\n"
192                 "subobj.DOMAINDN_LDB = \"%s\";\n"
193                 "subobj.CONFIGDN     = \"%s\";\n"
194                 "subobj.CONFIGDN_LDB = \"%s\";\n"
195                 "subobj.SCHEMADN     = \"%s\";\n"
196                 "subobj.SCHEMADN_LDB = \"%s\";\n"
197                 "subobj.HOSTNAME     = \"%s\";\n"
198                 "subobj.DNSNAME      = \"%s\";\n"
199                 "subobj.DEFAULTSITE  = \"%s\";\n"
200                 "\n"
201                 "modules_list        = new Array(\"rootdse\",\n"
202                 "                                \"kludge_acl\",\n"
203                 "                                \"paged_results\",\n"
204                 "                                \"server_sort\",\n"
205                 "                                \"extended_dn\",\n"
206                 "                                \"asq\",\n"
207                 "                                \"samldb\",\n"
208                 "                                \"operational\",\n"
209                 "                                \"objectclass\",\n"
210                 "                                \"rdn_name\",\n"
211                 "                                \"show_deleted\",\n"
212                 "                                \"partition\");\n"
213                 "subobj.MODULES_LIST = join(\",\", modules_list);\n"
214                 "subobj.DOMAINDN_MOD = \"pdc_fsmo,password_hash,repl_meta_data\";\n"
215                 "subobj.CONFIGDN_MOD = \"naming_fsmo,repl_meta_data\";\n"
216                 "subobj.SCHEMADN_MOD = \"schema_fsmo,repl_meta_data\";\n"
217                 "\n"
218                 "subobj.KRBTGTPASS   = \"_NOT_USED_\";\n"
219                 "subobj.MACHINEPASS  = \"%s\";\n"
220                 "subobj.ADMINPASS    = \"_NOT_USED_\";\n"
221                 "\n"
222                 "var paths = provision_default_paths(subobj);\n"
223                 "paths.samdb = \"%s\";\n"
224                 "paths.secrets = \"%s\";\n"
225                 "paths.keytab = \"%s\";\n"
226                 "\n"
227                 "var system_session = system_session();\n"
228                 "\n"
229                 "var ok = provision_become_dc(subobj, message, true, paths, system_session);\n"
230                 "assert(ok);\n"
231                 "\n"
232                 "return 0;\n",
233                 p->forest->root_dn_str,         /* subobj.ROOTDN */
234                 p->domain->dn_str,              /* subobj.DOMAINDN */
235                 s->path.domaindn_ldb,           /* subobj.DOMAINDN_LDB */
236                 p->forest->config_dn_str,       /* subobj.CONFIGDN */
237                 s->path.configdn_ldb,           /* subobj.CONFIGDN_LDB */
238                 p->forest->schema_dn_str,       /* subobj.SCHEMADN */
239                 s->path.schemadn_ldb,           /* subobj.SCHEMADN_LDB */
240                 p->dest_dsa->netbios_name,      /* subobj.HOSTNAME */
241                 p->dest_dsa->dns_name,          /* subobj.DNSNAME */
242                 p->dest_dsa->site_name,         /* subobj.DEFAULTSITE */
243                 cli_credentials_get_password(s->machine_account),/* subobj.MACHINEPASS */
244                 s->path.samdb_ldb,              /* paths.samdb */
245                 s->path.secrets_ldb,            /* paths.secrets */
246                 s->path.secrets_keytab);        /* paths.keytab */
247         NT_STATUS_HAVE_NO_MEMORY(ejs);
248
249         ret = test_run_ejs(ejs);
250         if (ret != 0) {
251                 DEBUG(0,("Failed to run ejs script: %d:\n%s",
252                         ret, ejs));
253                 talloc_free(ejs);
254                 return NT_STATUS_FOOBAR;
255         }
256         talloc_free(ejs);
257
258         talloc_free(s->ldb);
259
260         DEBUG(0,("Open the SAM LDB with system credentials: %s\n", 
261                  s->path.samdb_ldb));
262
263         s->ldb = ldb_wrap_connect(s, s->tctx->lp_ctx, s->path.samdb_ldb,
264                                   system_session(s, s->tctx->lp_ctx),
265                                   NULL, 0, NULL);
266         if (!s->ldb) {
267                 DEBUG(0,("Failed to open '%s'\n",
268                         s->path.samdb_ldb));
269                 return NT_STATUS_INTERNAL_DB_ERROR;
270         }
271
272         ok = samdb_set_ntds_invocation_id(s->ldb, &p->dest_dsa->invocation_id);
273         if (!ok) {
274                 DEBUG(0,("Failed to set cached ntds invocationId\n"));
275                 return NT_STATUS_FOOBAR;
276         }
277         ok = samdb_set_ntds_objectGUID(s->ldb, &p->dest_dsa->ntds_guid);
278         if (!ok) {
279                 DEBUG(0,("Failed to set cached ntds objectGUID\n"));
280                 return NT_STATUS_FOOBAR;
281         }
282
283         return NT_STATUS_OK;
284 }
285
286 #else 
287 #include "param/param.h"
288 #include <Python.h>
289 #include "scripting/python/modules.h"
290
291 static NTSTATUS test_become_dc_prepare_db(void *private_data,
292                                           const struct libnet_BecomeDC_PrepareDB *p)
293 {
294         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
295         bool ok;
296         PyObject *provision_fn, *result, *parameters;
297
298         py_load_samba_modules();
299         Py_Initialize();
300
301         py_update_path("bin"); /* FIXME: Can't assume this always runs in source/... */
302
303         provision_fn = PyImport_Import(PyString_FromString("samba.provision.provision"));
304
305         if (provision_fn == NULL) {
306                 DEBUG(0, ("Unable to import provision Python module.\n"));
307                 return NT_STATUS_UNSUCCESSFUL;
308         }
309         
310         DEBUG(0,("New Server[%s] in Site[%s]\n",
311                 p->dest_dsa->dns_name, p->dest_dsa->site_name));
312
313         DEBUG(0,("DSA Instance [%s]\n"
314                 "\tobjectGUID[%s]\n"
315                 "\tinvocationId[%s]\n",
316                 p->dest_dsa->ntds_dn_str,
317                 GUID_string(s, &p->dest_dsa->ntds_guid),
318                 GUID_string(s, &p->dest_dsa->invocation_id)));
319
320         DEBUG(0,("Pathes under PRIVATEDIR[%s]\n"
321                  "SAMDB[%s] SECRETS[%s] KEYTAB[%s]\n",
322                 lp_private_dir(s->tctx->lp_ctx),
323                 s->path.samdb_ldb,
324                 s->path.secrets_ldb,
325                 s->path.secrets_keytab));
326
327         DEBUG(0,("Schema Partition[%s => %s]\n",
328                 p->forest->schema_dn_str, s->path.schemadn_ldb));
329
330         DEBUG(0,("Config Partition[%s => %s]\n",
331                 p->forest->config_dn_str, s->path.configdn_ldb));
332
333         DEBUG(0,("Domain Partition[%s => %s]\n",
334                 p->domain->dn_str, s->path.domaindn_ldb));
335
336         parameters = PyDict_New();
337
338         PyDict_SetItemString(parameters, "rootdn", PyString_FromString(p->forest->root_dn_str));
339         PyDict_SetItemString(parameters, "domaindn", PyString_FromString(p->domain->dn_str));
340         PyDict_SetItemString(parameters, "domaindn_ldb", PyString_FromString(s->path.domaindn_ldb));
341         PyDict_SetItemString(parameters, "configdn", PyString_FromString(p->forest->config_dn_str));
342         PyDict_SetItemString(parameters, "configdn_ldb", PyString_FromString(s->path.configdn_ldb));
343         PyDict_SetItemString(parameters, "schema_dn_str", PyString_FromString(p->forest->schema_dn_str));
344         PyDict_SetItemString(parameters, "schemadn_ldb", PyString_FromString(s->path.schemadn_ldb));
345         PyDict_SetItemString(parameters, "netbios_name", PyString_FromString(p->dest_dsa->netbios_name));
346         PyDict_SetItemString(parameters, "dnsname", PyString_FromString(p->dest_dsa->dns_name));
347         PyDict_SetItemString(parameters, "defaultsite", PyString_FromString(p->dest_dsa->site_name));
348         PyDict_SetItemString(parameters, "machinepass", PyString_FromString(cli_credentials_get_password(s->machine_account)));
349         PyDict_SetItemString(parameters, "samdb", PyString_FromString(s->path.samdb_ldb));
350         PyDict_SetItemString(parameters, "secrets_ldb", PyString_FromString(s->path.secrets_ldb));
351         PyDict_SetItemString(parameters, "secrets_keytab", PyString_FromString(s->path.secrets_keytab));
352
353         result = PyEval_CallObjectWithKeywords(provision_fn, NULL, parameters);
354
355         Py_DECREF(parameters);
356
357         if (result == NULL) {
358                 PyErr_Print();
359                 PyErr_Clear();
360                 return NT_STATUS_UNSUCCESSFUL;
361         }
362
363         talloc_free(s->ldb);
364
365         DEBUG(0,("Open the SAM LDB with system credentials: %s\n", 
366                  s->path.samdb_ldb));
367
368         s->ldb = ldb_wrap_connect(s, s->tctx->lp_ctx, s->path.samdb_ldb,
369                                   system_session(s, s->tctx->lp_ctx),
370                                   NULL, 0, NULL);
371         if (!s->ldb) {
372                 DEBUG(0,("Failed to open '%s'\n",
373                         s->path.samdb_ldb));
374                 return NT_STATUS_INTERNAL_DB_ERROR;
375         }
376
377         ok = samdb_set_ntds_invocation_id(s->ldb, &p->dest_dsa->invocation_id);
378         if (!ok) {
379                 DEBUG(0,("Failed to set cached ntds invocationId\n"));
380                 return NT_STATUS_FOOBAR;
381         }
382         ok = samdb_set_ntds_objectGUID(s->ldb, &p->dest_dsa->ntds_guid);
383         if (!ok) {
384                 DEBUG(0,("Failed to set cached ntds objectGUID\n"));
385                 return NT_STATUS_FOOBAR;
386         }
387
388         return NT_STATUS_OK;
389 }
390
391 #endif
392
393 static NTSTATUS test_apply_schema(struct test_become_dc_state *s,
394                                   const struct libnet_BecomeDC_StoreChunk *c)
395 {
396         WERROR status;
397         const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr;
398         uint32_t total_object_count;
399         uint32_t object_count;
400         struct drsuapi_DsReplicaObjectListItemEx *first_object;
401         struct drsuapi_DsReplicaObjectListItemEx *cur;
402         uint32_t linked_attributes_count;
403         struct drsuapi_DsReplicaLinkedAttribute *linked_attributes;
404         const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector;
405         struct dsdb_extended_replicated_objects *objs;
406         struct repsFromTo1 *s_dsa;
407         char *tmp_dns_name;
408         struct ldb_message *msg;
409         struct ldb_val prefixMap_val;
410         struct ldb_message_element *prefixMap_el;
411         struct ldb_val schemaInfo_val;
412         uint32_t i;
413         int ret;
414         bool ok;
415
416         DEBUG(0,("Analyze and apply schema objects\n"));
417
418         s_dsa                   = talloc_zero(s, struct repsFromTo1);
419         NT_STATUS_HAVE_NO_MEMORY(s_dsa);
420         s_dsa->other_info       = talloc(s_dsa, struct repsFromTo1OtherInfo);
421         NT_STATUS_HAVE_NO_MEMORY(s_dsa->other_info);
422
423         switch (c->ctr_level) {
424         case 1:
425                 mapping_ctr                     = &c->ctr1->mapping_ctr;
426                 total_object_count              = c->ctr1->total_object_count;
427                 object_count                    = s->schema_part.object_count;
428                 first_object                    = s->schema_part.first_object;
429                 linked_attributes_count         = 0;
430                 linked_attributes               = NULL;
431                 s_dsa->highwatermark            = c->ctr1->new_highwatermark;
432                 s_dsa->source_dsa_obj_guid      = c->ctr1->source_dsa_guid;
433                 s_dsa->source_dsa_invocation_id = c->ctr1->source_dsa_invocation_id;
434                 uptodateness_vector             = NULL; /* TODO: map it */
435                 break;
436         case 6:
437                 mapping_ctr                     = &c->ctr6->mapping_ctr;
438                 total_object_count              = c->ctr6->total_object_count;
439                 object_count                    = s->schema_part.object_count;
440                 first_object                    = s->schema_part.first_object;
441                 linked_attributes_count         = 0; /* TODO: ! */
442                 linked_attributes               = NULL; /* TODO: ! */;
443                 s_dsa->highwatermark            = c->ctr6->new_highwatermark;
444                 s_dsa->source_dsa_obj_guid      = c->ctr6->source_dsa_guid;
445                 s_dsa->source_dsa_invocation_id = c->ctr6->source_dsa_invocation_id;
446                 uptodateness_vector             = c->ctr6->uptodateness_vector;
447                 break;
448         default:
449                 return NT_STATUS_INVALID_PARAMETER;
450         }
451
452         s_dsa->replica_flags            = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
453                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
454                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS;
455         memset(s_dsa->schedule, 0x11, sizeof(s_dsa->schedule));
456
457         tmp_dns_name    = GUID_string(s_dsa->other_info, &s_dsa->source_dsa_obj_guid);
458         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
459         tmp_dns_name    = talloc_asprintf_append_buffer(tmp_dns_name, "._msdcs.%s", c->forest->dns_name);
460         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
461         s_dsa->other_info->dns_name = tmp_dns_name;
462
463         for (cur = first_object; cur; cur = cur->next_object) {
464                 bool is_attr = false;
465                 bool is_class = false;
466
467                 for (i=0; i < cur->object.attribute_ctr.num_attributes; i++) {
468                         struct drsuapi_DsReplicaAttribute *a;
469                         uint32_t j;
470                         const char *oid = NULL;
471
472                         a = &cur->object.attribute_ctr.attributes[i];
473                         status = dsdb_map_int2oid(s->self_made_schema, a->attid, s, &oid);
474                         if (!W_ERROR_IS_OK(status)) {
475                                 return werror_to_ntstatus(status);
476                         }
477
478                         switch (a->attid) {
479                         case DRSUAPI_ATTRIBUTE_objectClass:
480                                 for (j=0; j < a->value_ctr.num_values; j++) {
481                                         uint32_t val = 0xFFFFFFFF;
482
483                                         if (a->value_ctr.values[i].blob
484                                             && a->value_ctr.values[i].blob->length == 4) {
485                                                 val = IVAL(a->value_ctr.values[i].blob->data,0);
486                                         }
487
488                                         if (val == DRSUAPI_OBJECTCLASS_attributeSchema) {
489                                                 is_attr = true;
490                                         }
491                                         if (val == DRSUAPI_OBJECTCLASS_classSchema) {
492                                                 is_class = true;
493                                         }
494                                 }
495
496                                 break;
497                         default:
498                                 break;
499                         }
500                 }
501
502                 if (is_attr) {
503                         struct dsdb_attribute *sa;
504
505                         sa = talloc_zero(s->self_made_schema, struct dsdb_attribute);
506                         NT_STATUS_HAVE_NO_MEMORY(sa);
507
508                         status = dsdb_attribute_from_drsuapi(s->self_made_schema, &cur->object, s, sa);
509                         if (!W_ERROR_IS_OK(status)) {
510                                 return werror_to_ntstatus(status);
511                         }
512
513                         DLIST_ADD_END(s->self_made_schema->attributes, sa, struct dsdb_attribute *);
514                 }
515
516                 if (is_class) {
517                         struct dsdb_class *sc;
518
519                         sc = talloc_zero(s->self_made_schema, struct dsdb_class);
520                         NT_STATUS_HAVE_NO_MEMORY(sc);
521
522                         status = dsdb_class_from_drsuapi(s->self_made_schema, &cur->object, s, sc);
523                         if (!W_ERROR_IS_OK(status)) {
524                                 return werror_to_ntstatus(status);
525                         }
526
527                         DLIST_ADD_END(s->self_made_schema->classes, sc, struct dsdb_class *);
528                 }
529         }
530
531         /* attach the schema to the ldb */
532         ret = dsdb_set_schema(s->ldb, s->self_made_schema);
533         if (ret != LDB_SUCCESS) {
534                 return NT_STATUS_FOOBAR;
535         }
536         /* we don't want to access the self made schema anymore */
537         s->self_made_schema = NULL;
538         s->schema = dsdb_get_schema(s->ldb);
539
540         status = dsdb_extended_replicated_objects_commit(s->ldb,
541                                                          c->partition->nc.dn,
542                                                          mapping_ctr,
543                                                          object_count,
544                                                          first_object,
545                                                          linked_attributes_count,
546                                                          linked_attributes,
547                                                          s_dsa,
548                                                          uptodateness_vector,
549                                                          c->gensec_skey,
550                                                          s, &objs);
551         if (!W_ERROR_IS_OK(status)) {
552                 DEBUG(0,("Failed to commit objects: %s\n", win_errstr(status)));
553                 return werror_to_ntstatus(status);
554         }
555
556         if (lp_parm_bool(s->tctx->lp_ctx, NULL, "become dc", "dump objects", false)) {
557                 for (i=0; i < objs->num_objects; i++) {
558                         struct ldb_ldif ldif;
559                         fprintf(stdout, "#\n");
560                         ldif.changetype = LDB_CHANGETYPE_NONE;
561                         ldif.msg = objs->objects[i].msg;
562                         ldb_ldif_write_file(s->ldb, stdout, &ldif);
563                         NDR_PRINT_DEBUG(replPropertyMetaDataBlob, objs->objects[i].meta_data);
564                 }
565         }
566
567         msg = ldb_msg_new(objs);
568         NT_STATUS_HAVE_NO_MEMORY(msg);
569         msg->dn = objs->partition_dn;
570
571         status = dsdb_get_oid_mappings_ldb(s->schema, msg, &prefixMap_val, &schemaInfo_val);
572         if (!W_ERROR_IS_OK(status)) {
573                 DEBUG(0,("Failed dsdb_get_oid_mappings_ldb(%s)\n", win_errstr(status)));
574                 return werror_to_ntstatus(status);
575         }
576
577         /* we only add prefixMap here, because schemaInfo is a replicated attribute and already applied */
578         ret = ldb_msg_add_value(msg, "prefixMap", &prefixMap_val, &prefixMap_el);
579         if (ret != LDB_SUCCESS) {
580                 return NT_STATUS_FOOBAR;
581         }
582         prefixMap_el->flags = LDB_FLAG_MOD_REPLACE;
583
584         ret = ldb_modify(s->ldb, msg);
585         if (ret != LDB_SUCCESS) {
586                 DEBUG(0,("Failed to add prefixMap and schemaInfo %s\n", ldb_strerror(ret)));
587                 return NT_STATUS_FOOBAR;
588         }
589
590         talloc_free(s_dsa);
591         talloc_free(objs);
592
593         /* reopen the ldb */
594         talloc_free(s->ldb); /* this also free's the s->schema, because dsdb_set_schema() steals it */
595         s->schema = NULL;
596
597         DEBUG(0,("Reopen the SAM LDB with system credentials and a already stored schema: %s\n", s->path.samdb_ldb));
598         s->ldb = ldb_wrap_connect(s, s->tctx->lp_ctx, s->path.samdb_ldb,
599                                   system_session(s, s->tctx->lp_ctx),
600                                   NULL, 0, NULL);
601         if (!s->ldb) {
602                 DEBUG(0,("Failed to open '%s'\n",
603                         s->path.samdb_ldb));
604                 return NT_STATUS_INTERNAL_DB_ERROR;
605         }
606
607         ok = samdb_set_ntds_invocation_id(s->ldb, &c->dest_dsa->invocation_id);
608         if (!ok) {
609                 DEBUG(0,("Failed to set cached ntds invocationId\n"));
610                 return NT_STATUS_FOOBAR;
611         }
612         ok = samdb_set_ntds_objectGUID(s->ldb, &c->dest_dsa->ntds_guid);
613         if (!ok) {
614                 DEBUG(0,("Failed to set cached ntds objectGUID\n"));
615                 return NT_STATUS_FOOBAR;
616         }
617
618         s->schema = dsdb_get_schema(s->ldb);
619         if (!s->schema) {
620                 DEBUG(0,("Failed to get loaded dsdb_schema\n"));
621                 return NT_STATUS_FOOBAR;
622         }
623
624         return NT_STATUS_OK;
625 }
626
627 static NTSTATUS test_become_dc_schema_chunk(void *private_data,
628                                             const struct libnet_BecomeDC_StoreChunk *c)
629 {
630         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
631         WERROR status;
632         const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr;
633         uint32_t total_object_count;
634         uint32_t object_count;
635         struct drsuapi_DsReplicaObjectListItemEx *first_object;
636         struct drsuapi_DsReplicaObjectListItemEx *cur;
637
638         switch (c->ctr_level) {
639         case 1:
640                 mapping_ctr             = &c->ctr1->mapping_ctr;
641                 total_object_count      = c->ctr1->total_object_count;
642                 object_count            = c->ctr1->object_count;
643                 first_object            = c->ctr1->first_object;
644                 break;
645         case 6:
646                 mapping_ctr             = &c->ctr6->mapping_ctr;
647                 total_object_count      = c->ctr6->total_object_count;
648                 object_count            = c->ctr6->object_count;
649                 first_object            = c->ctr6->first_object;
650                 break;
651         default:
652                 return NT_STATUS_INVALID_PARAMETER;
653         }
654
655         if (total_object_count) {
656                 DEBUG(0,("Schema-DN[%s] objects[%u/%u]\n",
657                         c->partition->nc.dn, object_count, total_object_count));
658         } else {
659                 DEBUG(0,("Schema-DN[%s] objects[%u]\n",
660                 c->partition->nc.dn, object_count));
661         }
662
663         if (!s->schema) {
664                 s->self_made_schema = talloc_zero(s, struct dsdb_schema);
665                 NT_STATUS_HAVE_NO_MEMORY(s->self_made_schema);
666
667                 status = dsdb_load_oid_mappings_drsuapi(s->self_made_schema, mapping_ctr);
668                 if (!W_ERROR_IS_OK(status)) {
669                         return werror_to_ntstatus(status);
670                 }
671
672                 s->schema = s->self_made_schema;
673         } else {
674                 status = dsdb_verify_oid_mappings_drsuapi(s->schema, mapping_ctr);
675                 if (!W_ERROR_IS_OK(status)) {
676                         return werror_to_ntstatus(status);
677                 }
678         }
679
680         if (!s->schema_part.first_object) {
681                 s->schema_part.object_count = object_count;
682                 s->schema_part.first_object = talloc_steal(s, first_object);
683         } else {
684                 s->schema_part.object_count             += object_count;
685                 s->schema_part.last_object->next_object = talloc_steal(s->schema_part.last_object,
686                                                                        first_object);
687         }
688         for (cur = first_object; cur->next_object; cur = cur->next_object) {}
689         s->schema_part.last_object = cur;
690
691         if (c->partition->highwatermark.tmp_highest_usn == c->partition->highwatermark.highest_usn) {
692                 return test_apply_schema(s, c);
693         }
694
695         return NT_STATUS_OK;
696 }
697
698 static NTSTATUS test_become_dc_store_chunk(void *private_data,
699                                            const struct libnet_BecomeDC_StoreChunk *c)
700 {
701         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
702         WERROR status;
703         const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr;
704         uint32_t total_object_count;
705         uint32_t object_count;
706         struct drsuapi_DsReplicaObjectListItemEx *first_object;
707         uint32_t linked_attributes_count;
708         struct drsuapi_DsReplicaLinkedAttribute *linked_attributes;
709         const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector;
710         struct dsdb_extended_replicated_objects *objs;
711         struct repsFromTo1 *s_dsa;
712         char *tmp_dns_name;
713         uint32_t i;
714
715         s_dsa                   = talloc_zero(s, struct repsFromTo1);
716         NT_STATUS_HAVE_NO_MEMORY(s_dsa);
717         s_dsa->other_info       = talloc(s_dsa, struct repsFromTo1OtherInfo);
718         NT_STATUS_HAVE_NO_MEMORY(s_dsa->other_info);
719
720         switch (c->ctr_level) {
721         case 1:
722                 mapping_ctr                     = &c->ctr1->mapping_ctr;
723                 total_object_count              = c->ctr1->total_object_count;
724                 object_count                    = c->ctr1->object_count;
725                 first_object                    = c->ctr1->first_object;
726                 linked_attributes_count         = 0;
727                 linked_attributes               = NULL;
728                 s_dsa->highwatermark            = c->ctr1->new_highwatermark;
729                 s_dsa->source_dsa_obj_guid      = c->ctr1->source_dsa_guid;
730                 s_dsa->source_dsa_invocation_id = c->ctr1->source_dsa_invocation_id;
731                 uptodateness_vector             = NULL; /* TODO: map it */
732                 break;
733         case 6:
734                 mapping_ctr                     = &c->ctr6->mapping_ctr;
735                 total_object_count              = c->ctr6->total_object_count;
736                 object_count                    = c->ctr6->object_count;
737                 first_object                    = c->ctr6->first_object;
738                 linked_attributes_count         = c->ctr6->linked_attributes_count;
739                 linked_attributes               = c->ctr6->linked_attributes;
740                 s_dsa->highwatermark            = c->ctr6->new_highwatermark;
741                 s_dsa->source_dsa_obj_guid      = c->ctr6->source_dsa_guid;
742                 s_dsa->source_dsa_invocation_id = c->ctr6->source_dsa_invocation_id;
743                 uptodateness_vector             = c->ctr6->uptodateness_vector;
744                 break;
745         default:
746                 return NT_STATUS_INVALID_PARAMETER;
747         }
748
749         s_dsa->replica_flags            = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
750                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
751                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS;
752         memset(s_dsa->schedule, 0x11, sizeof(s_dsa->schedule));
753
754         tmp_dns_name    = GUID_string(s_dsa->other_info, &s_dsa->source_dsa_obj_guid);
755         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
756         tmp_dns_name    = talloc_asprintf_append_buffer(tmp_dns_name, "._msdcs.%s", c->forest->dns_name);
757         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
758         s_dsa->other_info->dns_name = tmp_dns_name;
759
760         if (total_object_count) {
761                 DEBUG(0,("Partition[%s] objects[%u/%u]\n",
762                         c->partition->nc.dn, object_count, total_object_count));
763         } else {
764                 DEBUG(0,("Partition[%s] objects[%u]\n",
765                 c->partition->nc.dn, object_count));
766         }
767
768         status = dsdb_extended_replicated_objects_commit(s->ldb,
769                                                          c->partition->nc.dn,
770                                                          mapping_ctr,
771                                                          object_count,
772                                                          first_object,
773                                                          linked_attributes_count,
774                                                          linked_attributes,
775                                                          s_dsa,
776                                                          uptodateness_vector,
777                                                          c->gensec_skey,
778                                                          s, &objs);
779         if (!W_ERROR_IS_OK(status)) {
780                 DEBUG(0,("Failed to commit objects: %s\n", win_errstr(status)));
781                 return werror_to_ntstatus(status);
782         }
783
784         if (lp_parm_bool(s->tctx->lp_ctx, NULL, "become dc", "dump objects", false)) {
785                 for (i=0; i < objs->num_objects; i++) {
786                         struct ldb_ldif ldif;
787                         fprintf(stdout, "#\n");
788                         ldif.changetype = LDB_CHANGETYPE_NONE;
789                         ldif.msg = objs->objects[i].msg;
790                         ldb_ldif_write_file(s->ldb, stdout, &ldif);
791                         NDR_PRINT_DEBUG(replPropertyMetaDataBlob, objs->objects[i].meta_data);
792                 }
793         }
794         talloc_free(s_dsa);
795         talloc_free(objs);
796
797         for (i=0; i < linked_attributes_count; i++) {
798                 const struct dsdb_attribute *sa;
799
800                 if (!linked_attributes[i].identifier) {
801                         return NT_STATUS_FOOBAR;                
802                 }
803
804                 if (!linked_attributes[i].value.blob) {
805                         return NT_STATUS_FOOBAR;                
806                 }
807
808                 sa = dsdb_attribute_by_attributeID_id(s->schema,
809                                                       linked_attributes[i].attid);
810                 if (!sa) {
811                         return NT_STATUS_FOOBAR;
812                 }
813
814                 if (lp_parm_bool(s->tctx->lp_ctx, NULL, "become dc", "dump objects", false)) {
815                         DEBUG(0,("# %s\n", sa->lDAPDisplayName));
816                         NDR_PRINT_DEBUG(drsuapi_DsReplicaLinkedAttribute, &linked_attributes[i]);
817                         dump_data(0,
818                                 linked_attributes[i].value.blob->data,
819                                 linked_attributes[i].value.blob->length);
820                 }
821         }
822
823         return NT_STATUS_OK;
824 }
825
826 bool torture_net_become_dc(struct torture_context *torture)
827 {
828         bool ret = true;
829         NTSTATUS status;
830         struct libnet_BecomeDC b;
831         struct libnet_UnbecomeDC u;
832         struct test_become_dc_state *s;
833         struct ldb_message *msg;
834         int ldb_ret;
835         uint32_t i;
836
837         s = talloc_zero(torture, struct test_become_dc_state);
838         if (!s) return false;
839
840         s->tctx = torture;
841
842         s->netbios_name = lp_parm_string(torture->lp_ctx, NULL, "become dc", "smbtorture dc");
843         if (!s->netbios_name || !s->netbios_name[0]) {
844                 s->netbios_name = "smbtorturedc";
845         }
846
847         s->path.samdb_ldb       = talloc_asprintf(s, "%s_samdb.ldb", s->netbios_name);
848         if (!s->path.samdb_ldb) return false;
849         s->path.domaindn_ldb    = talloc_asprintf(s, "%s_domain.ldb", s->netbios_name);
850         if (!s->path.domaindn_ldb) return false;
851         s->path.configdn_ldb    = talloc_asprintf(s, "%s_config.ldb", s->netbios_name);
852         if (!s->path.configdn_ldb) return false;
853         s->path.schemadn_ldb    = talloc_asprintf(s, "%s_schema.ldb", s->netbios_name);
854         if (!s->path.schemadn_ldb) return false;
855         s->path.secrets_ldb     = talloc_asprintf(s, "%s_secrets.ldb", s->netbios_name);
856         if (!s->path.secrets_ldb) return false;
857         s->path.secrets_keytab  = talloc_asprintf(s, "%s_secrets.keytab", s->netbios_name);
858         if (!s->path.secrets_keytab) return false;
859
860         /* Join domain as a member server. */
861         s->tj = torture_join_domain(torture, s->netbios_name,
862                                  ACB_WSTRUST,
863                                  &s->machine_account);
864         if (!s->tj) {
865                 DEBUG(0, ("%s failed to join domain as workstation\n",
866                           s->netbios_name));
867                 return false;
868         }
869
870         s->ctx = libnet_context_init(torture->ev, torture->lp_ctx);
871         s->ctx->cred = cmdline_credentials;
872
873         s->ldb = ldb_init(s);
874
875         ZERO_STRUCT(b);
876         b.in.domain_dns_name            = torture_join_dom_dns_name(s->tj);
877         b.in.domain_netbios_name        = torture_join_dom_netbios_name(s->tj);
878         b.in.domain_sid                 = torture_join_sid(s->tj);
879         b.in.source_dsa_address         = torture_setting_string(torture, "host", NULL);
880         b.in.dest_dsa_netbios_name      = s->netbios_name;
881
882         b.in.callbacks.private_data     = s;
883         b.in.callbacks.check_options    = test_become_dc_check_options;
884         b.in.callbacks.prepare_db       = test_become_dc_prepare_db;
885         b.in.callbacks.schema_chunk     = test_become_dc_schema_chunk;
886         b.in.callbacks.config_chunk     = test_become_dc_store_chunk;
887         b.in.callbacks.domain_chunk     = test_become_dc_store_chunk;
888
889         status = libnet_BecomeDC(s->ctx, s, &b);
890         if (!NT_STATUS_IS_OK(status)) {
891                 printf("libnet_BecomeDC() failed - %s\n", nt_errstr(status));
892                 ret = false;
893                 goto cleanup;
894         }
895
896         msg = ldb_msg_new(s);
897         if (!msg) {
898                 printf("ldb_msg_new() failed\n");
899                 ret = false;
900                 goto cleanup;
901         }
902         msg->dn = ldb_dn_new(msg, s->ldb, "@ROOTDSE");
903         if (!msg->dn) {
904                 printf("ldb_msg_new(@ROOTDSE) failed\n");
905                 ret = false;
906                 goto cleanup;
907         }
908
909         ldb_ret = ldb_msg_add_string(msg, "isSynchronized", "TRUE");
910         if (ldb_ret != LDB_SUCCESS) {
911                 printf("ldb_msg_add_string(msg, isSynchronized, TRUE) failed: %d\n", ldb_ret);
912                 ret = false;
913                 goto cleanup;
914         }
915
916         for (i=0; i < msg->num_elements; i++) {
917                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
918         }
919
920         printf("mark ROOTDSE with isSynchronized=TRUE\n");
921         ldb_ret = ldb_modify(s->ldb, msg);
922         if (ldb_ret != LDB_SUCCESS) {
923                 printf("ldb_modify() failed: %d\n", ldb_ret);
924                 ret = false;
925                 goto cleanup;
926         }
927         
928         /* reopen the ldb */
929         talloc_free(s->ldb); /* this also free's the s->schema, because dsdb_set_schema() steals it */
930         s->schema = NULL;
931
932         DEBUG(0,("Reopen the SAM LDB with system credentials and all replicated data: %s\n", s->path.samdb_ldb));
933         s->ldb = ldb_wrap_connect(s, torture->lp_ctx, s->path.samdb_ldb,
934                                   system_session(s, torture->lp_ctx),
935                                   NULL, 0, NULL);
936         if (!s->ldb) {
937                 DEBUG(0,("Failed to open '%s'\n",
938                         s->path.samdb_ldb));
939                 ret = false;
940                 goto cleanup;
941         }
942
943         s->schema = dsdb_get_schema(s->ldb);
944         if (!s->schema) {
945                 DEBUG(0,("Failed to get loaded dsdb_schema\n"));
946                 ret = false;
947                 goto cleanup;
948         }
949
950         if (lp_parm_bool(torture->lp_ctx, NULL, "become dc", "do not unjoin", false)) {
951                 talloc_free(s);
952                 return ret;
953         }
954
955 cleanup:
956         ZERO_STRUCT(u);
957         u.in.domain_dns_name            = torture_join_dom_dns_name(s->tj);
958         u.in.domain_netbios_name        = torture_join_dom_netbios_name(s->tj);
959         u.in.source_dsa_address         = torture_setting_string(torture, "host", NULL);
960         u.in.dest_dsa_netbios_name      = s->netbios_name;
961
962         status = libnet_UnbecomeDC(s->ctx, s, &u);
963         if (!NT_STATUS_IS_OK(status)) {
964                 printf("libnet_UnbecomeDC() failed - %s\n", nt_errstr(status));
965                 ret = false;
966         }
967
968         /* Leave domain. */                          
969         torture_leave_domain(s->tj);
970
971         talloc_free(s);
972         return ret;
973 }