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