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