67733aca53d426a5f21690aab48c016aa1f2106b
[samba.git] / python / samba / netcmd / drs.py
1 # implement samba_tool drs commands
2 #
3 # Copyright Andrew Tridgell 2010
4 #
5 # based on C implementation by Kamen Mazdrashki <kamen.mazdrashki@postpath.com>
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20
21 import samba.getopt as options
22 import ldb
23 import logging
24
25 from samba.auth import system_session
26 from samba.netcmd import (
27     Command,
28     CommandError,
29     Option,
30     SuperCommand,
31     )
32 from samba.samdb import SamDB
33 from samba import drs_utils, nttime2string, dsdb
34 from samba.dcerpc import drsuapi, misc
35 import common
36 from samba.join import join_clone
37
38 def drsuapi_connect(ctx):
39     '''make a DRSUAPI connection to the server'''
40     try:
41         (ctx.drsuapi, ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drsuapi_connect(ctx.server, ctx.lp, ctx.creds)
42     except Exception, e:
43         raise CommandError("DRS connection to %s failed" % ctx.server, e)
44
45 def samdb_connect(ctx):
46     '''make a ldap connection to the server'''
47     try:
48         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
49                           session_info=system_session(),
50                           credentials=ctx.creds, lp=ctx.lp)
51     except Exception, e:
52         raise CommandError("LDAP connection to %s failed" % ctx.server, e)
53
54 def drs_errmsg(werr):
55     '''return "was successful" or an error string'''
56     (ecode, estring) = werr
57     if ecode == 0:
58         return "was successful"
59     return "failed, result %u (%s)" % (ecode, estring)
60
61
62
63 def attr_default(msg, attrname, default):
64     '''get an attribute from a ldap msg with a default'''
65     if attrname in msg:
66         return msg[attrname][0]
67     return default
68
69
70
71 def drs_parse_ntds_dn(ntds_dn):
72     '''parse a NTDS DN returning a site and server'''
73     a = ntds_dn.split(',')
74     if a[0] != "CN=NTDS Settings" or a[2] != "CN=Servers" or a[4] != 'CN=Sites':
75         raise RuntimeError("bad NTDS DN %s" % ntds_dn)
76     server = a[1].split('=')[1]
77     site   = a[3].split('=')[1]
78     return (site, server)
79
80
81
82
83
84 class cmd_drs_showrepl(Command):
85     """Show replication status."""
86
87     synopsis = "%prog [<DC>] [options]"
88
89     takes_optiongroups = {
90         "sambaopts": options.SambaOptions,
91         "versionopts": options.VersionOptions,
92         "credopts": options.CredentialsOptions,
93     }
94
95     takes_args = ["DC?"]
96
97     def print_neighbour(self, n):
98         '''print one set of neighbour information'''
99         self.message("%s" % n.naming_context_dn)
100         try:
101             (site, server) = drs_parse_ntds_dn(n.source_dsa_obj_dn)
102             self.message("\t%s\%s via RPC" % (site, server))
103         except RuntimeError:
104             self.message("\tNTDS DN: %s" % n.source_dsa_obj_dn)
105         self.message("\t\tDSA object GUID: %s" % n.source_dsa_obj_guid)
106         self.message("\t\tLast attempt @ %s %s" % (nttime2string(n.last_attempt),
107                                                    drs_errmsg(n.result_last_attempt)))
108         self.message("\t\t%u consecutive failure(s)." % n.consecutive_sync_failures)
109         self.message("\t\tLast success @ %s" % nttime2string(n.last_success))
110         self.message("")
111
112     def drsuapi_ReplicaInfo(ctx, info_type):
113         '''call a DsReplicaInfo'''
114
115         req1 = drsuapi.DsReplicaGetInfoRequest1()
116         req1.info_type = info_type
117         try:
118             (info_type, info) = ctx.drsuapi.DsReplicaGetInfo(ctx.drsuapi_handle, 1, req1)
119         except Exception, e:
120             raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
121         return (info_type, info)
122
123     def run(self, DC=None, sambaopts=None,
124             credopts=None, versionopts=None, server=None):
125
126         self.lp = sambaopts.get_loadparm()
127         if DC is None:
128             DC = common.netcmd_dnsname(self.lp)
129         self.server = DC
130         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
131
132         drsuapi_connect(self)
133         samdb_connect(self)
134
135         # show domain information
136         ntds_dn = self.samdb.get_dsServiceName()
137         server_dns = self.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])[0]['dnsHostName'][0]
138
139         (site, server) = drs_parse_ntds_dn(ntds_dn)
140         try:
141             ntds = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=['options', 'objectGUID', 'invocationId'])
142         except Exception, e:
143             raise CommandError("Failed to search NTDS DN %s" % ntds_dn)
144         conn = self.samdb.search(base=ntds_dn, expression="(objectClass=nTDSConnection)")
145
146         self.message("%s\\%s" % (site, server))
147         self.message("DSA Options: 0x%08x" % int(attr_default(ntds[0], "options", 0)))
148         self.message("DSA object GUID: %s" % self.samdb.schema_format_value("objectGUID", ntds[0]["objectGUID"][0]))
149         self.message("DSA invocationId: %s\n" % self.samdb.schema_format_value("objectGUID", ntds[0]["invocationId"][0]))
150
151         self.message("==== INBOUND NEIGHBORS ====\n")
152         (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS)
153         for n in info.array:
154             self.print_neighbour(n)
155
156
157         self.message("==== OUTBOUND NEIGHBORS ====\n")
158         (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_REPSTO)
159         for n in info.array:
160             self.print_neighbour(n)
161
162         reasons = ['NTDSCONN_KCC_GC_TOPOLOGY',
163                    'NTDSCONN_KCC_RING_TOPOLOGY',
164                    'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
165                    'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
166                    'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
167                    'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
168                    'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
169                    'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
170                    'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
171                    'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
172
173         self.message("==== KCC CONNECTION OBJECTS ====\n")
174         for c in conn:
175             self.message("Connection --")
176
177             c_rdn, sep, c_server_dn = c['fromServer'][0].partition(',')
178             try:
179                 c_server_res = self.samdb.search(base=c_server_dn, scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
180                 c_server_dns = c_server_res[0]["dnsHostName"][0]
181             except ldb.LdbError, (errno, _):
182                 if errno == ldb.ERR_NO_SUCH_OBJECT:
183                     self.message("\tWARNING: Connection to DELETED server!")
184                 c_server_dns = ""
185             except KeyError:
186                 c_server_dns = ""
187
188             self.message("\tConnection name: %s" % c['name'][0])
189             self.message("\tEnabled        : %s" % attr_default(c, 'enabledConnection', 'TRUE'))
190             self.message("\tServer DNS name : %s" % c_server_dns)
191             self.message("\tServer DN name  : %s" % c['fromServer'][0])
192             self.message("\t\tTransportType: RPC")
193             self.message("\t\toptions: 0x%08X" % int(attr_default(c, 'options', 0)))
194             if not 'mS-DS-ReplicatesNCReason' in c:
195                 self.message("Warning: No NC replicated for Connection!")
196                 continue
197             for r in c['mS-DS-ReplicatesNCReason']:
198                 a = str(r).split(':')
199                 self.message("\t\tReplicatesNC: %s" % a[3])
200                 self.message("\t\tReason: 0x%08x" % int(a[2]))
201                 for s in reasons:
202                     if getattr(dsdb, s, 0) & int(a[2]):
203                         self.message("\t\t\t%s" % s)
204
205
206
207 class cmd_drs_kcc(Command):
208     """Trigger knowledge consistency center run."""
209
210     synopsis = "%prog [<DC>] [options]"
211
212     takes_optiongroups = {
213         "sambaopts": options.SambaOptions,
214         "versionopts": options.VersionOptions,
215         "credopts": options.CredentialsOptions,
216     }
217
218     takes_args = ["DC?"]
219
220     def run(self, DC=None, sambaopts=None,
221             credopts=None, versionopts=None, server=None):
222
223         self.lp = sambaopts.get_loadparm()
224         if DC is None:
225             DC = common.netcmd_dnsname(self.lp)
226         self.server = DC
227
228         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
229
230         drsuapi_connect(self)
231
232         req1 = drsuapi.DsExecuteKCC1()
233         try:
234             self.drsuapi.DsExecuteKCC(self.drsuapi_handle, 1, req1)
235         except Exception, e:
236             raise CommandError("DsExecuteKCC failed", e)
237         self.message("Consistency check on %s successful." % DC)
238
239
240
241 def drs_local_replicate(self, SOURCE_DC, NC):
242     '''replicate from a source DC to the local SAM'''
243
244     self.server = SOURCE_DC
245     drsuapi_connect(self)
246
247     self.local_samdb = SamDB(session_info=system_session(), url=None,
248                              credentials=self.creds, lp=self.lp)
249
250     self.samdb = SamDB(url="ldap://%s" % self.server,
251                        session_info=system_session(),
252                        credentials=self.creds, lp=self.lp)
253
254     # work out the source and destination GUIDs
255     res = self.local_samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
256     self.ntds_dn = res[0]["dsServiceName"][0]
257
258     res = self.local_samdb.search(base=self.ntds_dn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
259     self.ntds_guid = misc.GUID(self.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
260
261
262     source_dsa_invocation_id = misc.GUID(self.samdb.get_invocation_id())
263     dest_dsa_invocation_id = misc.GUID(self.local_samdb.get_invocation_id())
264     destination_dsa_guid = self.ntds_guid
265
266     self.samdb.transaction_start()
267     repl = drs_utils.drs_Replicate("ncacn_ip_tcp:%s[seal]" % self.server, self.lp,
268                                    self.creds, self.local_samdb, dest_dsa_invocation_id)
269
270     # Work out if we are an RODC, so that a forced local replicate
271     # with the admin pw does not sync passwords
272     rodc = self.local_samdb.am_rodc()
273     try:
274         repl.replicate(NC, source_dsa_invocation_id, destination_dsa_guid, rodc=rodc)
275     except Exception, e:
276         raise CommandError("Error replicating DN %s" % NC, e)
277     self.samdb.transaction_commit()
278
279     self.message("Replicate from %s to %s was successful." % (SOURCE_DC, self.local_samdb.url))
280
281
282
283 class cmd_drs_replicate(Command):
284     """Replicate a naming context between two DCs."""
285
286     synopsis = "%prog <destinationDC> <sourceDC> <NC> [options]"
287
288     takes_optiongroups = {
289         "sambaopts": options.SambaOptions,
290         "versionopts": options.VersionOptions,
291         "credopts": options.CredentialsOptions,
292     }
293
294     takes_args = ["DEST_DC", "SOURCE_DC", "NC"]
295
296     takes_options = [
297         Option("--add-ref", help="use ADD_REF to add to repsTo on source", action="store_true"),
298         Option("--sync-forced", help="use SYNC_FORCED to force inbound replication", action="store_true"),
299         Option("--sync-all", help="use SYNC_ALL to replicate from all DCs", action="store_true"),
300         Option("--full-sync", help="resync all objects", action="store_true"),
301         Option("--local", help="pull changes directly into the local database (destination DC is ignored)", action="store_true"),
302         Option("--local-online", help="pull changes into the local database (destination DC is ignored) as a normal online replication", action="store_true"),
303         Option("--async-op", help="use ASYNC_OP for the replication", action="store_true"),
304         ]
305
306     def run(self, DEST_DC, SOURCE_DC, NC,
307             add_ref=False, sync_forced=False, sync_all=False, full_sync=False,
308             local=False, local_online=False, async_op=False,
309             sambaopts=None, credopts=None, versionopts=None, server=None):
310
311         self.server = DEST_DC
312         self.lp = sambaopts.get_loadparm()
313
314         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
315
316         if local:
317             drs_local_replicate(self, SOURCE_DC, NC)
318             return
319
320         if local_online:
321             server_bind = drsuapi.drsuapi("irpc:dreplsrv", lp_ctx=self.lp)
322             server_bind_handle = misc.policy_handle()
323         else:
324             drsuapi_connect(self)
325             server_bind = self.drsuapi
326             server_bind_handle = self.drsuapi_handle
327
328         if not async_op:
329             # Give the sync replication 5 minutes time
330             server_bind.request_timeout = 5 * 60
331
332         samdb_connect(self)
333
334         # we need to find the NTDS GUID of the source DC
335         msg = self.samdb.search(base=self.samdb.get_config_basedn(),
336                                 expression="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (
337             ldb.binary_encode(SOURCE_DC),
338             ldb.binary_encode(SOURCE_DC)),
339                                 attrs=[])
340         if len(msg) == 0:
341             raise CommandError("Failed to find source DC %s" % SOURCE_DC)
342         server_dn = msg[0]['dn']
343
344         msg = self.samdb.search(base=server_dn, scope=ldb.SCOPE_ONELEVEL,
345                                 expression="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
346                                 attrs=['objectGUID', 'options'])
347         if len(msg) == 0:
348             raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC)
349         source_dsa_guid = msg[0]['objectGUID'][0]
350         dsa_options = int(attr_default(msg, 'options', 0))
351
352
353         req_options = 0
354         if not (dsa_options & dsdb.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL):
355             req_options |= drsuapi.DRSUAPI_DRS_WRIT_REP
356         if add_ref:
357             req_options |= drsuapi.DRSUAPI_DRS_ADD_REF
358         if sync_forced:
359             req_options |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
360         if sync_all:
361             req_options |= drsuapi.DRSUAPI_DRS_SYNC_ALL
362         if full_sync:
363             req_options |= drsuapi.DRSUAPI_DRS_FULL_SYNC_NOW
364         if async_op:
365             req_options |= drsuapi.DRSUAPI_DRS_ASYNC_OP
366
367         try:
368             drs_utils.sendDsReplicaSync(server_bind, server_bind_handle, source_dsa_guid, NC, req_options)
369         except drs_utils.drsException, estr:
370             raise CommandError("DsReplicaSync failed", estr)
371         if async_op:
372             self.message("Replicate from %s to %s was started." % (SOURCE_DC, DEST_DC))
373         else:
374             self.message("Replicate from %s to %s was successful." % (SOURCE_DC, DEST_DC))
375
376
377
378 class cmd_drs_bind(Command):
379     """Show DRS capabilities of a server."""
380
381     synopsis = "%prog [<DC>] [options]"
382
383     takes_optiongroups = {
384         "sambaopts": options.SambaOptions,
385         "versionopts": options.VersionOptions,
386         "credopts": options.CredentialsOptions,
387     }
388
389     takes_args = ["DC?"]
390
391     def run(self, DC=None, sambaopts=None,
392             credopts=None, versionopts=None, server=None):
393
394         self.lp = sambaopts.get_loadparm()
395         if DC is None:
396             DC = common.netcmd_dnsname(self.lp)
397         self.server = DC
398         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
399
400         drsuapi_connect(self)
401
402         bind_info = drsuapi.DsBindInfoCtr()
403         bind_info.length = 28
404         bind_info.info = drsuapi.DsBindInfo28()
405         (info, handle) = self.drsuapi.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
406
407         optmap = [
408             ("DRSUAPI_SUPPORTED_EXTENSION_BASE",     "DRS_EXT_BASE"),
409             ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION",   "DRS_EXT_ASYNCREPL"),
410             ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI",    "DRS_EXT_REMOVEAPI"),
411             ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2",   "DRS_EXT_MOVEREQ_V2"),
412             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS",   "DRS_EXT_GETCHG_DEFLATE"),
413             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1",    "DRS_EXT_DCINFO_V1"),
414             ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION",   "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
415             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY",    "DRS_EXT_ADDENTRY"),
416             ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE",   "DRS_EXT_KCC_EXECUTE"),
417             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2",   "DRS_EXT_ADDENTRY_V2"),
418             ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION",   "DRS_EXT_LINKED_VALUE_REPLICATION"),
419             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2",    "DRS_EXT_DCINFO_V2"),
420             ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD","DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
421             ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND",   "DRS_EXT_CRYPTO_BIND"),
422             ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO",   "DRS_EXT_GET_REPL_INFO"),
423             ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION",   "DRS_EXT_STRONG_ENCRYPTION"),
424             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01",   "DRS_EXT_DCINFO_VFFFFFFFF"),
425             ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP",  "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
426             ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY",   "DRS_EXT_ADD_SID_HISTORY"),
427             ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3",   "DRS_EXT_POST_BETA3"),
428             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5",   "DRS_EXT_GETCHGREQ_V5"),
429             ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2",   "DRS_EXT_GETMEMBERSHIPS2"),
430             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6",   "DRS_EXT_GETCHGREQ_V6"),
431             ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS",   "DRS_EXT_NONDOMAIN_NCS"),
432             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8",   "DRS_EXT_GETCHGREQ_V8"),
433             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5",   "DRS_EXT_GETCHGREPLY_V5"),
434             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6",   "DRS_EXT_GETCHGREPLY_V6"),
435             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3",   "DRS_EXT_WHISTLER_BETA3"),
436             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7",   "DRS_EXT_WHISTLER_BETA3"),
437             ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT",   "DRS_EXT_WHISTLER_BETA3"),
438             ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS",   "DRS_EXT_W2K3_DEFLATE"),
439             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10",   "DRS_EXT_GETCHGREQ_V10"),
440             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2",   "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
441             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
442             ]
443
444         optmap_ext = [
445             ("DRSUAPI_SUPPORTED_EXTENSION_ADAM", "DRS_EXT_ADAM"),
446             ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2", "DRS_EXT_LH_BETA2"),
447             ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN", "DRS_EXT_RECYCLE_BIN")]
448
449         self.message("Bind to %s succeeded." % DC)
450         self.message("Extensions supported:")
451         for (opt, str) in optmap:
452             optval = getattr(drsuapi, opt, 0)
453             if info.info.supported_extensions & optval:
454                 yesno = "Yes"
455             else:
456                 yesno = "No "
457             self.message("  %-60s: %s (%s)" % (opt, yesno, str))
458
459         if isinstance(info.info, drsuapi.DsBindInfo48):
460             self.message("\nExtended Extensions supported:")
461             for (opt, str) in optmap_ext:
462                 optval = getattr(drsuapi, opt, 0)
463                 if info.info.supported_extensions_ext & optval:
464                     yesno = "Yes"
465                 else:
466                     yesno = "No "
467                 self.message("  %-60s: %s (%s)" % (opt, yesno, str))
468
469         self.message("\nSite GUID: %s" % info.info.site_guid)
470         self.message("Repl epoch: %u" % info.info.repl_epoch)
471         if isinstance(info.info, drsuapi.DsBindInfo48):
472             self.message("Forest GUID: %s" % info.info.config_dn_guid)
473
474
475
476 class cmd_drs_options(Command):
477     """Query or change 'options' for NTDS Settings object of a Domain Controller."""
478
479     synopsis = "%prog [<DC>] [options]"
480
481     takes_optiongroups = {
482         "sambaopts": options.SambaOptions,
483         "versionopts": options.VersionOptions,
484         "credopts": options.CredentialsOptions,
485     }
486
487     takes_args = ["DC?"]
488
489     takes_options = [
490         Option("--dsa-option", help="DSA option to enable/disable", type="str",
491                metavar="{+|-}IS_GC | {+|-}DISABLE_INBOUND_REPL | {+|-}DISABLE_OUTBOUND_REPL | {+|-}DISABLE_NTDSCONN_XLATE" ),
492         ]
493
494     option_map = {"IS_GC": 0x00000001,
495                   "DISABLE_INBOUND_REPL": 0x00000002,
496                   "DISABLE_OUTBOUND_REPL": 0x00000004,
497                   "DISABLE_NTDSCONN_XLATE": 0x00000008}
498
499     def run(self, DC=None, dsa_option=None,
500             sambaopts=None, credopts=None, versionopts=None):
501
502         self.lp = sambaopts.get_loadparm()
503         if DC is None:
504             DC = common.netcmd_dnsname(self.lp)
505         self.server = DC
506         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
507
508         samdb_connect(self)
509
510         ntds_dn = self.samdb.get_dsServiceName()
511         res = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=["options"])
512         dsa_opts = int(res[0]["options"][0])
513
514         # print out current DSA options
515         cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
516         self.message("Current DSA options: " + ", ".join(cur_opts))
517
518         # modify options
519         if dsa_option:
520             if dsa_option[:1] not in ("+", "-"):
521                 raise CommandError("Unknown option %s" % dsa_option)
522             flag = dsa_option[1:]
523             if flag not in self.option_map.keys():
524                 raise CommandError("Unknown option %s" % dsa_option)
525             if dsa_option[:1] == "+":
526                 dsa_opts |= self.option_map[flag]
527             else:
528                 dsa_opts &= ~self.option_map[flag]
529             #save new options
530             m = ldb.Message()
531             m.dn = ldb.Dn(self.samdb, ntds_dn)
532             m["options"]= ldb.MessageElement(str(dsa_opts), ldb.FLAG_MOD_REPLACE, "options")
533             self.samdb.modify(m)
534             # print out new DSA options
535             cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
536             self.message("New DSA options: " + ", ".join(cur_opts))
537
538
539 class cmd_drs_clone_dc_database(Command):
540     """Replicate an initial clone of domain, but DO NOT JOIN it."""
541
542     synopsis = "%prog <dnsdomain> [options]"
543
544     takes_optiongroups = {
545         "sambaopts": options.SambaOptions,
546         "versionopts": options.VersionOptions,
547         "credopts": options.CredentialsOptions,
548     }
549
550     takes_options = [
551         Option("--server", help="DC to join", type=str),
552         Option("--targetdir", help="where to store provision (required)", type=str),
553         Option("--quiet", help="Be quiet", action="store_true"),
554         Option("--include-secrets", help="Also replicate secret values", action="store_true"),
555         Option("--verbose", help="Be verbose", action="store_true")
556        ]
557
558     takes_args = ["domain"]
559
560     def run(self, domain, sambaopts=None, credopts=None,
561             versionopts=None, server=None, targetdir=None,
562             quiet=False, verbose=False, include_secrets=False):
563         lp = sambaopts.get_loadparm()
564         creds = credopts.get_credentials(lp)
565
566         logger = self.get_logger()
567         if verbose:
568             logger.setLevel(logging.DEBUG)
569         elif quiet:
570             logger.setLevel(logging.WARNING)
571         else:
572             logger.setLevel(logging.INFO)
573
574         if targetdir is None:
575             raise CommandError("--targetdir option must be specified")
576
577
578         join_clone(logger=logger, server=server, creds=creds, lp=lp, domain=domain,
579                    targetdir=targetdir, include_secrets=include_secrets)
580
581
582 class cmd_drs(SuperCommand):
583     """Directory Replication Services (DRS) management."""
584
585     subcommands = {}
586     subcommands["bind"] = cmd_drs_bind()
587     subcommands["kcc"] = cmd_drs_kcc()
588     subcommands["replicate"] = cmd_drs_replicate()
589     subcommands["showrepl"] = cmd_drs_showrepl()
590     subcommands["options"] = cmd_drs_options()
591     subcommands["clone-dc-database"] = cmd_drs_clone_dc_database()