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