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