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