r20922: use the show_deleted module by default
[bbaumbach/samba-autobuild/.git] / source4 / torture / libnet / libnet_BecomeDC.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    libnet_BecomeDC() tests
5
6    Copyright (C) Stefan (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   = \"test\";\n"
204                 "subobj.MACHINEPASS  = \"test\";\n"
205                 "subobj.ADMINPASS    = \"test\";\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                 TORTURE_SAMDB_LDB,              /* paths.samdb */
226                 TORTURE_SECRETS_LDB,            /* paths.secrets */
227                 TORTURE_SECRETS_KEYTAB);        /* paths.keytab */
228         NT_STATUS_HAVE_NO_MEMORY(ejs);
229
230         ret = test_run_ejs(ejs);
231         if (ret != 0) {
232                 DEBUG(0,("Failed to run ejs script: %d:\n%s",
233                         ret, ejs));
234                 talloc_free(ejs);
235                 return NT_STATUS_FOOBAR;
236         }
237         talloc_free(ejs);
238
239         talloc_free(s->ldb);
240
241         DEBUG(0,("Open the SAM LDB with system credentials: %s\n", TORTURE_SAMDB_LDB));
242
243         s->ldb = ldb_wrap_connect(s, TORTURE_SAMDB_LDB,
244                                   system_session(s),
245                                   NULL, 0, NULL);
246         if (!s->ldb) {
247                 DEBUG(0,("Failed to open '%s'\n",
248                         TORTURE_SAMDB_LDB));
249                 return NT_STATUS_INTERNAL_DB_ERROR;
250         }
251
252         ok = samdb_set_ntds_invocation_id(s->ldb, &p->dest_dsa->invocation_id);
253         if (!ok) {
254                 DEBUG(0,("Failed to set cached ntds invocationId\n"));
255                 return NT_STATUS_FOOBAR;
256         }
257         ok = samdb_set_ntds_objectGUID(s->ldb, &p->dest_dsa->ntds_guid);
258         if (!ok) {
259                 DEBUG(0,("Failed to set cached ntds objectGUID\n"));
260                 return NT_STATUS_FOOBAR;
261         }
262
263         return NT_STATUS_OK;
264 }
265
266 static NTSTATUS test_apply_schema(struct test_become_dc_state *s,
267                                   const struct libnet_BecomeDC_StoreChunk *c)
268 {
269         WERROR status;
270         const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr;
271         uint32_t total_object_count;
272         uint32_t object_count;
273         struct drsuapi_DsReplicaObjectListItemEx *first_object;
274         struct drsuapi_DsReplicaObjectListItemEx *cur;
275         uint32_t linked_attributes_count;
276         struct drsuapi_DsReplicaLinkedAttribute *linked_attributes;
277         const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector;
278         struct dsdb_extended_replicated_objects *objs;
279         struct repsFromTo1 *s_dsa;
280         char *tmp_dns_name;
281         struct ldb_message *msg;
282         struct ldb_val prefixMap_val;
283         struct ldb_message_element *prefixMap_el;
284         struct ldb_val schemaInfo_val;
285         uint32_t i;
286         int ret;
287         bool ok;
288
289         DEBUG(0,("Analyze and apply schema objects\n"));
290
291         s_dsa                   = talloc_zero(s, struct repsFromTo1);
292         NT_STATUS_HAVE_NO_MEMORY(s_dsa);
293         s_dsa->other_info       = talloc(s_dsa, struct repsFromTo1OtherInfo);
294         NT_STATUS_HAVE_NO_MEMORY(s_dsa->other_info);
295
296         switch (c->ctr_level) {
297         case 1:
298                 mapping_ctr                     = &c->ctr1->mapping_ctr;
299                 total_object_count              = c->ctr1->total_object_count;
300                 object_count                    = s->schema_part.object_count;
301                 first_object                    = s->schema_part.first_object;
302                 linked_attributes_count         = 0;
303                 linked_attributes               = NULL;
304                 s_dsa->highwatermark            = c->ctr1->new_highwatermark;
305                 s_dsa->source_dsa_obj_guid      = c->ctr1->source_dsa_guid;
306                 s_dsa->source_dsa_invocation_id = c->ctr1->source_dsa_invocation_id;
307                 uptodateness_vector             = NULL; /* TODO: map it */
308                 break;
309         case 6:
310                 mapping_ctr                     = &c->ctr6->mapping_ctr;
311                 total_object_count              = c->ctr6->total_object_count;
312                 object_count                    = s->schema_part.object_count;
313                 first_object                    = s->schema_part.first_object;
314                 linked_attributes_count         = 0; /* TODO: ! */
315                 linked_attributes               = NULL; /* TODO: ! */;
316                 s_dsa->highwatermark            = c->ctr6->new_highwatermark;
317                 s_dsa->source_dsa_obj_guid      = c->ctr6->source_dsa_guid;
318                 s_dsa->source_dsa_invocation_id = c->ctr6->source_dsa_invocation_id;
319                 uptodateness_vector             = c->ctr6->uptodateness_vector;
320                 break;
321         default:
322                 return NT_STATUS_INVALID_PARAMETER;
323         }
324
325         s_dsa->replica_flags            = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
326                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
327                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS;
328         memset(s_dsa->schedule, 0x11, sizeof(s_dsa->schedule));
329
330         tmp_dns_name    = GUID_string(s_dsa->other_info, &s_dsa->source_dsa_obj_guid);
331         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
332         tmp_dns_name    = talloc_asprintf_append(tmp_dns_name, "._msdcs.%s", c->forest->dns_name);
333         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
334         s_dsa->other_info->dns_name = tmp_dns_name;
335
336         for (cur = first_object; cur; cur = cur->next_object) {
337                 bool is_attr = false;
338                 bool is_class = false;
339
340                 for (i=0; i < cur->object.attribute_ctr.num_attributes; i++) {
341                         struct drsuapi_DsReplicaAttribute *a;
342                         uint32_t j;
343                         const char *oid = NULL;
344
345                         a = &cur->object.attribute_ctr.attributes[i];
346                         status = dsdb_map_int2oid(s->self_made_schema, a->attid, s, &oid);
347                         if (!W_ERROR_IS_OK(status)) {
348                                 return werror_to_ntstatus(status);
349                         }
350
351                         switch (a->attid) {
352                         case DRSUAPI_ATTRIBUTE_objectClass:
353                                 for (j=0; j < a->value_ctr.num_values; j++) {
354                                         uint32_t val = 0xFFFFFFFF;
355
356                                         if (a->value_ctr.values[i].blob
357                                             && a->value_ctr.values[i].blob->length == 4) {
358                                                 val = IVAL(a->value_ctr.values[i].blob->data,0);
359                                         }
360
361                                         if (val == DRSUAPI_OBJECTCLASS_attributeSchema) {
362                                                 is_attr = true;
363                                         }
364                                         if (val == DRSUAPI_OBJECTCLASS_classSchema) {
365                                                 is_class = true;
366                                         }
367                                 }
368
369                                 break;
370                         default:
371                                 break;
372                         }
373                 }
374
375                 if (is_attr) {
376                         struct dsdb_attribute *sa;
377
378                         sa = talloc_zero(s->self_made_schema, struct dsdb_attribute);
379                         NT_STATUS_HAVE_NO_MEMORY(sa);
380
381                         status = dsdb_attribute_from_drsuapi(s->self_made_schema, &cur->object, s, sa);
382                         if (!W_ERROR_IS_OK(status)) {
383                                 return werror_to_ntstatus(status);
384                         }
385
386                         DLIST_ADD_END(s->self_made_schema->attributes, sa, struct dsdb_attribute *);
387                 }
388
389                 if (is_class) {
390                         struct dsdb_class *sc;
391
392                         sc = talloc_zero(s->self_made_schema, struct dsdb_class);
393                         NT_STATUS_HAVE_NO_MEMORY(sc);
394
395                         status = dsdb_class_from_drsuapi(s->self_made_schema, &cur->object, s, sc);
396                         if (!W_ERROR_IS_OK(status)) {
397                                 return werror_to_ntstatus(status);
398                         }
399
400                         DLIST_ADD_END(s->self_made_schema->classes, sc, struct dsdb_class *);
401                 }
402         }
403
404         /* attach the schema to the ldb */
405         ret = dsdb_set_schema(s->ldb, s->self_made_schema);
406         if (ret != LDB_SUCCESS) {
407                 return NT_STATUS_FOOBAR;
408         }
409         /* we don't want to access the self made schema anymore */
410         s->self_made_schema = NULL;
411         s->schema = dsdb_get_schema(s->ldb);
412
413         status = dsdb_extended_replicated_objects_commit(s->ldb,
414                                                          c->partition->nc.dn,
415                                                          mapping_ctr,
416                                                          object_count,
417                                                          first_object,
418                                                          linked_attributes_count,
419                                                          linked_attributes,
420                                                          s_dsa,
421                                                          uptodateness_vector,
422                                                          s, &objs);
423         if (!W_ERROR_IS_OK(status)) {
424                 DEBUG(0,("Failed to commit objects: %s\n", win_errstr(status)));
425                 return werror_to_ntstatus(status);
426         }
427
428         if (lp_parm_bool(-1, "become dc", "dump objects", False)) {
429                 for (i=0; i < objs->num_objects; i++) {
430                         struct ldb_ldif ldif;
431                         fprintf(stdout, "#\n");
432                         ldif.changetype = LDB_CHANGETYPE_NONE;
433                         ldif.msg = objs->objects[i].msg;
434                         ldb_ldif_write_file(s->ldb, stdout, &ldif);
435                         NDR_PRINT_DEBUG(replPropertyMetaDataBlob, objs->objects[i].meta_data);
436                 }
437         }
438
439         msg = ldb_msg_new(objs);
440         NT_STATUS_HAVE_NO_MEMORY(msg);
441         msg->dn = objs->partition_dn;
442
443         status = dsdb_get_oid_mappings_ldb(s->schema, msg, &prefixMap_val, &schemaInfo_val);
444         if (!W_ERROR_IS_OK(status)) {
445                 DEBUG(0,("Failed dsdb_get_oid_mappings_ldb(%s)\n", win_errstr(status)));
446                 return werror_to_ntstatus(status);
447         }
448
449         /* we only add prefixMap here, because schemaInfo is a replicated attribute and already applied */
450         ret = ldb_msg_add_value(msg, "prefixMap", &prefixMap_val, &prefixMap_el);
451         if (ret != LDB_SUCCESS) {
452                 return NT_STATUS_FOOBAR;
453         }
454         prefixMap_el->flags = LDB_FLAG_MOD_REPLACE;
455
456         ret = ldb_modify(s->ldb, msg);
457         if (ret != LDB_SUCCESS) {
458                 DEBUG(0,("Failed to add prefixMap and schemaInfo %s\n", ldb_strerror(ret)));
459                 return NT_STATUS_FOOBAR;
460         }
461
462         talloc_free(s_dsa);
463         talloc_free(objs);
464
465         /* reopen the ldb */
466         talloc_free(s->ldb); /* this also free's the s->schema, because dsdb_set_schema() steals it */
467         s->schema = NULL;
468
469         DEBUG(0,("Reopen the SAM LDB with system credentials and a already stored schema: %s\n", TORTURE_SAMDB_LDB));
470         s->ldb = ldb_wrap_connect(s, TORTURE_SAMDB_LDB,
471                                   system_session(s),
472                                   NULL, 0, NULL);
473         if (!s->ldb) {
474                 DEBUG(0,("Failed to open '%s'\n",
475                         TORTURE_SAMDB_LDB));
476                 return NT_STATUS_INTERNAL_DB_ERROR;
477         }
478
479         ok = samdb_set_ntds_invocation_id(s->ldb, &c->dest_dsa->invocation_id);
480         if (!ok) {
481                 DEBUG(0,("Failed to set cached ntds invocationId\n"));
482                 return NT_STATUS_FOOBAR;
483         }
484         ok = samdb_set_ntds_objectGUID(s->ldb, &c->dest_dsa->ntds_guid);
485         if (!ok) {
486                 DEBUG(0,("Failed to set cached ntds objectGUID\n"));
487                 return NT_STATUS_FOOBAR;
488         }
489
490         s->schema = dsdb_get_schema(s->ldb);
491         if (!s->schema) {
492                 DEBUG(0,("Failed to get loaded dsdb_schema\n"));
493                 return NT_STATUS_FOOBAR;
494         }
495
496         return NT_STATUS_OK;
497 }
498
499 static NTSTATUS test_become_dc_schema_chunk(void *private_data,
500                                             const struct libnet_BecomeDC_StoreChunk *c)
501 {
502         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
503         WERROR status;
504         const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr;
505         uint32_t total_object_count;
506         uint32_t object_count;
507         struct drsuapi_DsReplicaObjectListItemEx *first_object;
508         struct drsuapi_DsReplicaObjectListItemEx *cur;
509
510         switch (c->ctr_level) {
511         case 1:
512                 mapping_ctr             = &c->ctr1->mapping_ctr;
513                 total_object_count      = c->ctr1->total_object_count;
514                 object_count            = c->ctr1->object_count;
515                 first_object            = c->ctr1->first_object;
516                 break;
517         case 6:
518                 mapping_ctr             = &c->ctr6->mapping_ctr;
519                 total_object_count      = c->ctr6->total_object_count;
520                 object_count            = c->ctr6->object_count;
521                 first_object            = c->ctr6->first_object;
522                 break;
523         default:
524                 return NT_STATUS_INVALID_PARAMETER;
525         }
526
527         if (total_object_count) {
528                 DEBUG(0,("Schema-DN[%s] objects[%u/%u]\n",
529                         c->partition->nc.dn, object_count, total_object_count));
530         } else {
531                 DEBUG(0,("Schema-DN[%s] objects[%u]\n",
532                 c->partition->nc.dn, object_count));
533         }
534
535         if (!s->schema) {
536                 s->self_made_schema = talloc_zero(s, struct dsdb_schema);
537                 NT_STATUS_HAVE_NO_MEMORY(s->self_made_schema);
538
539                 status = dsdb_load_oid_mappings_drsuapi(s->self_made_schema, mapping_ctr);
540                 if (!W_ERROR_IS_OK(status)) {
541                         return werror_to_ntstatus(status);
542                 }
543
544                 s->schema = s->self_made_schema;
545         } else {
546                 status = dsdb_verify_oid_mappings_drsuapi(s->schema, mapping_ctr);
547                 if (!W_ERROR_IS_OK(status)) {
548                         return werror_to_ntstatus(status);
549                 }
550         }
551
552         if (!s->schema_part.first_object) {
553                 s->schema_part.object_count = object_count;
554                 s->schema_part.first_object = talloc_steal(s, first_object);
555         } else {
556                 s->schema_part.object_count             += object_count;
557                 s->schema_part.last_object->next_object = talloc_steal(s->schema_part.last_object,
558                                                                        first_object);
559         }
560         for (cur = first_object; cur->next_object; cur = cur->next_object) {}
561         s->schema_part.last_object = cur;
562
563         if (c->partition->highwatermark.tmp_highest_usn == c->partition->highwatermark.highest_usn) {
564                 return test_apply_schema(s, c);
565         }
566
567         return NT_STATUS_OK;
568 }
569
570 static NTSTATUS test_become_dc_store_chunk(void *private_data,
571                                            const struct libnet_BecomeDC_StoreChunk *c)
572 {
573         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
574         WERROR status;
575         const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr;
576         uint32_t total_object_count;
577         uint32_t object_count;
578         struct drsuapi_DsReplicaObjectListItemEx *first_object;
579         uint32_t linked_attributes_count;
580         struct drsuapi_DsReplicaLinkedAttribute *linked_attributes;
581         const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector;
582         struct dsdb_extended_replicated_objects *objs;
583         struct repsFromTo1 *s_dsa;
584         char *tmp_dns_name;
585         uint32_t i;
586
587         s_dsa                   = talloc_zero(s, struct repsFromTo1);
588         NT_STATUS_HAVE_NO_MEMORY(s_dsa);
589         s_dsa->other_info       = talloc(s_dsa, struct repsFromTo1OtherInfo);
590         NT_STATUS_HAVE_NO_MEMORY(s_dsa->other_info);
591
592         switch (c->ctr_level) {
593         case 1:
594                 mapping_ctr                     = &c->ctr1->mapping_ctr;
595                 total_object_count              = c->ctr1->total_object_count;
596                 object_count                    = c->ctr1->object_count;
597                 first_object                    = c->ctr1->first_object;
598                 linked_attributes_count         = 0;
599                 linked_attributes               = NULL;
600                 s_dsa->highwatermark            = c->ctr1->new_highwatermark;
601                 s_dsa->source_dsa_obj_guid      = c->ctr1->source_dsa_guid;
602                 s_dsa->source_dsa_invocation_id = c->ctr1->source_dsa_invocation_id;
603                 uptodateness_vector             = NULL; /* TODO: map it */
604                 break;
605         case 6:
606                 mapping_ctr                     = &c->ctr6->mapping_ctr;
607                 total_object_count              = c->ctr6->total_object_count;
608                 object_count                    = c->ctr6->object_count;
609                 first_object                    = c->ctr6->first_object;
610                 linked_attributes_count         = c->ctr6->linked_attributes_count;
611                 linked_attributes               = c->ctr6->linked_attributes;
612                 s_dsa->highwatermark            = c->ctr6->new_highwatermark;
613                 s_dsa->source_dsa_obj_guid      = c->ctr6->source_dsa_guid;
614                 s_dsa->source_dsa_invocation_id = c->ctr6->source_dsa_invocation_id;
615                 uptodateness_vector             = c->ctr6->uptodateness_vector;
616                 break;
617         default:
618                 return NT_STATUS_INVALID_PARAMETER;
619         }
620
621         s_dsa->replica_flags            = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
622                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
623                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS;
624         memset(s_dsa->schedule, 0x11, sizeof(s_dsa->schedule));
625
626         tmp_dns_name    = GUID_string(s_dsa->other_info, &s_dsa->source_dsa_obj_guid);
627         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
628         tmp_dns_name    = talloc_asprintf_append(tmp_dns_name, "._msdcs.%s", c->forest->dns_name);
629         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
630         s_dsa->other_info->dns_name = tmp_dns_name;
631
632         if (total_object_count) {
633                 DEBUG(0,("Partition[%s] objects[%u/%u]\n",
634                         c->partition->nc.dn, object_count, total_object_count));
635         } else {
636                 DEBUG(0,("Partition[%s] objects[%u]\n",
637                 c->partition->nc.dn, object_count));
638         }
639
640         status = dsdb_extended_replicated_objects_commit(s->ldb,
641                                                          c->partition->nc.dn,
642                                                          mapping_ctr,
643                                                          object_count,
644                                                          first_object,
645                                                          linked_attributes_count,
646                                                          linked_attributes,
647                                                          s_dsa,
648                                                          uptodateness_vector,
649                                                          s, &objs);
650         if (!W_ERROR_IS_OK(status)) {
651                 DEBUG(0,("Failed to commit objects: %s\n", win_errstr(status)));
652                 return werror_to_ntstatus(status);
653         }
654
655         if (lp_parm_bool(-1, "become dc", "dump objects", False)) {
656                 for (i=0; i < objs->num_objects; i++) {
657                         struct ldb_ldif ldif;
658                         fprintf(stdout, "#\n");
659                         ldif.changetype = LDB_CHANGETYPE_NONE;
660                         ldif.msg = objs->objects[i].msg;
661                         ldb_ldif_write_file(s->ldb, stdout, &ldif);
662                         NDR_PRINT_DEBUG(replPropertyMetaDataBlob, objs->objects[i].meta_data);
663                 }
664         }
665         talloc_free(s_dsa);
666         talloc_free(objs);
667
668         for (i=0; i < linked_attributes_count; i++) {
669                 const struct dsdb_attribute *sa;
670
671                 if (!linked_attributes[i].identifier) {
672                         return NT_STATUS_FOOBAR;                
673                 }
674
675                 if (!linked_attributes[i].value.blob) {
676                         return NT_STATUS_FOOBAR;                
677                 }
678
679                 sa = dsdb_attribute_by_attributeID_id(s->schema,
680                                                       linked_attributes[i].attid);
681                 if (!sa) {
682                         return NT_STATUS_FOOBAR;
683                 }
684
685                 if (lp_parm_bool(-1, "become dc", "dump objects", False)) {
686                         DEBUG(0,("# %s\n", sa->lDAPDisplayName));
687                         NDR_PRINT_DEBUG(drsuapi_DsReplicaLinkedAttribute, &linked_attributes[i]);
688                         dump_data(0,
689                                 linked_attributes[i].value.blob->data,
690                                 linked_attributes[i].value.blob->length);
691                 }
692         }
693
694         return NT_STATUS_OK;
695 }
696
697 static NTSTATUS test_become_dc_domain_chunk(void *private_data,
698                                            const struct libnet_BecomeDC_StoreChunk *c)
699 {
700         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
701
702         s->computer_dn = talloc_strdup(s, c->dest_dsa->computer_dn_str);
703         NT_STATUS_HAVE_NO_MEMORY(s->computer_dn);
704
705         return test_become_dc_store_chunk(private_data, c);
706 }
707
708 static BOOL test_become_dc_set_test_passwords(struct test_become_dc_state *s)
709 {
710         struct ldb_message *msg;
711         int ret;
712
713         printf("Set up \"test\" as password for the krbtgt, machine and administrator accounts\n");
714
715         /*
716          * first krbtgt password
717          */
718         msg = ldb_msg_new(s);
719         if (!msg) return False;
720
721         msg->dn = ldb_dn_new_fmt(msg, s->ldb, "CN=krbtgt,CN=Users,%s",
722                                  ldb_dn_get_linearized(samdb_base_dn(s->ldb)));
723         if (!msg) return False;
724
725         ret = ldb_msg_add_string(msg, "sambaPassword", "test");
726         if (ret != LDB_SUCCESS) return False;
727
728         ret = samdb_replace(s->ldb, s, msg);
729         if (ret != LDB_SUCCESS) {
730                 printf("failed to replace sambaPassword for '%s': %s\n",
731                        ldb_dn_get_linearized(msg->dn),
732                        ldb_strerror(ret));
733                 return False;
734         }
735         talloc_free(msg);
736
737         /*
738          * our machine account password
739          */
740         msg = ldb_msg_new(s);
741         if (!msg) return False;
742
743         msg->dn = ldb_dn_new(msg, s->ldb, s->computer_dn);
744         if (!msg) return False;
745
746         ret = ldb_msg_add_string(msg, "sambaPassword", "test");
747         if (ret != LDB_SUCCESS) return False;
748
749         ret = samdb_replace(s->ldb, s, msg);
750         if (ret != LDB_SUCCESS) {
751                 printf("failed to replace sambaPassword for '%s': %s\n",
752                        ldb_dn_get_linearized(msg->dn),
753                        ldb_strerror(ret));
754                 return False;
755         }
756         talloc_free(msg);
757
758         /*
759          * the Administrator account password
760          */
761         msg = ldb_msg_new(s);
762         if (!msg) return False;
763
764         msg->dn = ldb_dn_new_fmt(msg, s->ldb, "CN=Administrator,CN=Users,%s",
765                                  ldb_dn_get_linearized(samdb_base_dn(s->ldb)));
766         if (!msg) return False;
767
768         ret = ldb_msg_add_string(msg, "sambaPassword", "test");
769         if (ret != LDB_SUCCESS) return False;
770
771         ret = samdb_replace(s->ldb, s, msg);
772         if (ret != LDB_SUCCESS) {
773                 printf("failed to replace sambaPassword for '%s': %s\n",
774                        ldb_dn_get_linearized(msg->dn),
775                        ldb_strerror(ret));
776                 return False;
777         }
778         talloc_free(msg);
779
780         return True;
781 }
782
783 BOOL torture_net_become_dc(struct torture_context *torture)
784 {
785         BOOL ret = True;
786         NTSTATUS status;
787         struct libnet_BecomeDC b;
788         struct libnet_UnbecomeDC u;
789         struct test_become_dc_state *s;
790         struct ldb_message *msg;
791         int ldb_ret;
792         uint32_t i;
793
794         s = talloc_zero(torture, struct test_become_dc_state);
795         if (!s) return False;
796
797         /* Join domain as a member server. */
798         s->tj = torture_join_domain(TORTURE_NETBIOS_NAME,
799                                  ACB_WSTRUST,
800                                  &s->machine_account);
801         if (!s->tj) {
802                 DEBUG(0, ("%s failed to join domain as workstation\n",
803                           TORTURE_NETBIOS_NAME));
804                 return False;
805         }
806
807         s->ctx = libnet_context_init(event_context_init(s));
808         s->ctx->cred = cmdline_credentials;
809
810         s->ldb = ldb_init(s);
811
812         ZERO_STRUCT(b);
813         b.in.domain_dns_name            = torture_join_dom_dns_name(s->tj);
814         b.in.domain_netbios_name        = torture_join_dom_netbios_name(s->tj);
815         b.in.domain_sid                 = torture_join_sid(s->tj);
816         b.in.source_dsa_address         = lp_parm_string(-1, "torture", "host");
817         b.in.dest_dsa_netbios_name      = TORTURE_NETBIOS_NAME;
818
819         b.in.callbacks.private_data     = s;
820         b.in.callbacks.check_options    = test_become_dc_check_options;
821         b.in.callbacks.prepare_db       = test_become_dc_prepare_db;
822         b.in.callbacks.schema_chunk     = test_become_dc_schema_chunk;
823         b.in.callbacks.config_chunk     = test_become_dc_store_chunk;
824         b.in.callbacks.domain_chunk     = test_become_dc_domain_chunk;
825
826         status = libnet_BecomeDC(s->ctx, s, &b);
827         if (!NT_STATUS_IS_OK(status)) {
828                 printf("libnet_BecomeDC() failed - %s\n", nt_errstr(status));
829                 ret = False;
830                 goto cleanup;
831         }
832
833         msg = ldb_msg_new(s);
834         if (!msg) {
835                 printf("ldb_msg_new() failed\n");
836                 ret = False;
837                 goto cleanup;
838         }
839         msg->dn = ldb_dn_new(msg, s->ldb, "cn=ROOTDSE");
840         if (!msg->dn) {
841                 printf("ldb_msg_new(cn=ROOTDSE) failed\n");
842                 ret = False;
843                 goto cleanup;
844         }
845
846         ldb_ret = ldb_msg_add_string(msg, "isSynchronized", "TRUE");
847         if (ldb_ret != LDB_SUCCESS) {
848                 printf("ldb_msg_add_string(msg, isSynchronized, TRUE) failed: %d\n", ldb_ret);
849                 ret = False;
850                 goto cleanup;
851         }
852
853         for (i=0; i < msg->num_elements; i++) {
854                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
855         }
856
857         printf("mark ROOTDSE with isSynchronized=TRUE\n");
858         ldb_ret = ldb_modify(s->ldb, msg);
859         if (ldb_ret != LDB_SUCCESS) {
860                 printf("ldb_modify() failed: %d\n", ldb_ret);
861                 ret = False;
862                 goto cleanup;
863         }
864         
865         /* reopen the ldb */
866         talloc_free(s->ldb); /* this also free's the s->schema, because dsdb_set_schema() steals it */
867         s->schema = NULL;
868
869         DEBUG(0,("Reopen the SAM LDB with system credentials and all replicated data: %s\n", TORTURE_SAMDB_LDB));
870         s->ldb = ldb_wrap_connect(s, TORTURE_SAMDB_LDB,
871                                   system_session(s),
872                                   NULL, 0, NULL);
873         if (!s->ldb) {
874                 DEBUG(0,("Failed to open '%s'\n",
875                         TORTURE_SAMDB_LDB));
876                 ret = False;
877                 goto cleanup;
878         }
879
880         s->schema = dsdb_get_schema(s->ldb);
881         if (!s->schema) {
882                 DEBUG(0,("Failed to get loaded dsdb_schema\n"));
883                 ret = False;
884                 goto cleanup;
885         }
886
887         ret &= test_become_dc_set_test_passwords(s);
888
889 cleanup:
890         ZERO_STRUCT(u);
891         u.in.domain_dns_name            = torture_join_dom_dns_name(s->tj);
892         u.in.domain_netbios_name        = torture_join_dom_netbios_name(s->tj);
893         u.in.source_dsa_address         = lp_parm_string(-1, "torture", "host");
894         u.in.dest_dsa_netbios_name      = TORTURE_NETBIOS_NAME;
895
896         status = libnet_UnbecomeDC(s->ctx, s, &u);
897         if (!NT_STATUS_IS_OK(status)) {
898                 printf("libnet_UnbecomeDC() failed - %s\n", nt_errstr(status));
899                 ret = False;
900         }
901
902         /* Leave domain. */                          
903         torture_leave_domain(s->tj);
904
905         talloc_free(s);
906         return ret;
907 }