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