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