samba-tool: domain info - add basic exception handling
[ira/wip.git] / source4 / scripting / python / samba / netcmd / domain.py
1 #!/usr/bin/env python
2 #
3 # domain management
4 #
5 # Copyright Matthias Dieter Wallnoefer 2009
6 # Copyright Andrew Kroeger 2009
7 # Copyright Jelmer Vernooij 2009
8 # Copyright Giampaolo Lauria 2011
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 #
23
24
25
26 import samba.getopt as options
27 import ldb
28 import os
29 import tempfile
30 import logging
31 from samba import Ldb
32 from samba.net import Net, LIBNET_JOIN_AUTOMATIC
33 import samba.ntacls
34 from samba.join import join_RODC, join_DC, join_subdomain
35 from samba.auth import system_session
36 from samba.samdb import SamDB
37 from samba.dcerpc.samr import DOMAIN_PASSWORD_COMPLEX, DOMAIN_PASSWORD_STORE_CLEARTEXT
38 from samba.netcmd import (
39     Command,
40     CommandError,
41     SuperCommand,
42     Option
43     )
44 from samba.netcmd.common import netcmd_get_domain_infos_via_cldap
45 from samba.samba3 import Samba3
46 from samba.samba3 import param as s3param
47 from samba.upgrade import upgrade_from_samba3
48
49 from samba.dsdb import (
50     DS_DOMAIN_FUNCTION_2000,
51     DS_DOMAIN_FUNCTION_2003,
52     DS_DOMAIN_FUNCTION_2003_MIXED,
53     DS_DOMAIN_FUNCTION_2008,
54     DS_DOMAIN_FUNCTION_2008_R2,
55     )
56
57 def get_testparm_var(testparm, smbconf, varname):
58     cmd = "%s -s -l --parameter-name='%s' %s 2>/dev/null" % (testparm, varname, smbconf)
59     output = os.popen(cmd, 'r').readline()
60     return output.strip()
61
62
63 class cmd_domain_export_keytab(Command):
64     """Dumps kerberos keys of the domain into a keytab"""
65
66     synopsis = "%prog <keytab> [options]"
67
68     takes_options = [
69         ]
70
71     takes_args = ["keytab"]
72
73     def run(self, keytab, credopts=None, sambaopts=None, versionopts=None):
74         lp = sambaopts.get_loadparm()
75         net = Net(None, lp, server=credopts.ipaddress)
76         net.export_keytab(keytab=keytab)
77
78 class cmd_domain_info(Command):
79     """Print basic info about a domain and the DC passed as parameter"""
80
81     synopsis = "%prog domain info <ip_address> [options]"
82
83     takes_options = [
84         ]
85
86     takes_args = ["address"]
87
88     def run(self, address, credopts=None, sambaopts=None, versionopts=None):
89         lp = sambaopts.get_loadparm()
90         try:
91             res = netcmd_get_domain_infos_via_cldap(lp, None, address)
92             print "Forest           : %s" % res.forest
93             print "Domain           : %s" % res.dns_domain
94             print "Netbios domain   : %s" % res.domain_name
95             print "DC name          : %s" % res.pdc_dns_name
96             print "DC netbios name  : %s" % res.pdc_name
97             print "Server site      : %s" % res.server_site
98             print "Client site      : %s" % res.client_site
99         except RuntimeError:
100             raise CommandError("Invalid IP address '" + address + "'!")
101
102
103
104 class cmd_domain_join(Command):
105     """Joins domain as either member or backup domain controller"""
106
107     synopsis = "%prog <dnsdomain> [DC|RODC|MEMBER|SUBDOMAIN] [options]"
108
109     takes_options = [
110         Option("--server", help="DC to join", type=str),
111         Option("--site", help="site to join", type=str),
112         Option("--targetdir", help="where to store provision", type=str),
113         Option("--parent-domain", help="parent domain to create subdomain under", type=str),
114         Option("--domain-critical-only",
115                help="only replicate critical domain objects",
116                action="store_true"),
117         ]
118
119     takes_args = ["domain", "role?"]
120
121     def run(self, domain, role=None, sambaopts=None, credopts=None,
122             versionopts=None, server=None, site=None, targetdir=None,
123             domain_critical_only=False, parent_domain=None):
124         lp = sambaopts.get_loadparm()
125         creds = credopts.get_credentials(lp)
126         net = Net(creds, lp, server=credopts.ipaddress)
127
128         if site is None:
129             site = "Default-First-Site-Name"
130
131         netbios_name = lp.get("netbios name")
132
133         if not role is None:
134             role = role.upper()
135
136         if role is None or role == "MEMBER":
137             (join_password, sid, domain_name) = net.join_member(domain,
138                                                                 netbios_name,
139                                                                 LIBNET_JOIN_AUTOMATIC)
140
141             self.outf.write("Joined domain %s (%s)\n" % (domain_name, sid))
142             return
143         elif role == "DC":
144             join_DC(server=server, creds=creds, lp=lp, domain=domain,
145                     site=site, netbios_name=netbios_name, targetdir=targetdir,
146                     domain_critical_only=domain_critical_only)
147             return
148         elif role == "RODC":
149             join_RODC(server=server, creds=creds, lp=lp, domain=domain,
150                       site=site, netbios_name=netbios_name, targetdir=targetdir,
151                       domain_critical_only=domain_critical_only)
152             return
153         elif role == "SUBDOMAIN":
154             netbios_domain = lp.get("workgroup")
155             if parent_domain is None:
156                 parent_domain = ".".join(domain.split(".")[1:])
157             join_subdomain(server=server, creds=creds, lp=lp, dnsdomain=domain, parent_domain=parent_domain,
158                            site=site, netbios_name=netbios_name, netbios_domain=netbios_domain, targetdir=targetdir)
159             return
160         else:
161             raise CommandError("Invalid role '%s' (possible values: MEMBER, DC, RODC, SUBDOMAIN)" % role)
162
163
164
165 class cmd_domain_level(Command):
166     """Raises domain and forest function levels"""
167
168     synopsis = "%prog (show|raise <options>) [options]"
169
170     takes_options = [
171         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
172                metavar="URL", dest="H"),
173         Option("--quiet", help="Be quiet", action="store_true"),
174         Option("--forest-level", type="choice", choices=["2003", "2008", "2008_R2"],
175             help="The forest function level (2003 | 2008 | 2008_R2)"),
176         Option("--domain-level", type="choice", choices=["2003", "2008", "2008_R2"],
177             help="The domain function level (2003 | 2008 | 2008_R2)")
178             ]
179
180     takes_args = ["subcommand"]
181
182     def run(self, subcommand, H=None, forest_level=None, domain_level=None,
183             quiet=False, credopts=None, sambaopts=None, versionopts=None):
184         lp = sambaopts.get_loadparm()
185         creds = credopts.get_credentials(lp, fallback_machine=True)
186
187         samdb = SamDB(url=H, session_info=system_session(),
188             credentials=creds, lp=lp)
189
190         domain_dn = samdb.domain_dn()
191
192         res_forest = samdb.search("CN=Partitions,%s" % samdb.get_config_basedn(),
193           scope=ldb.SCOPE_BASE, attrs=["msDS-Behavior-Version"])
194         assert len(res_forest) == 1
195
196         res_domain = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
197           attrs=["msDS-Behavior-Version", "nTMixedDomain"])
198         assert len(res_domain) == 1
199
200         res_dc_s = samdb.search("CN=Sites,%s" % samdb.get_config_basedn(),
201           scope=ldb.SCOPE_SUBTREE, expression="(objectClass=nTDSDSA)",
202           attrs=["msDS-Behavior-Version"])
203         assert len(res_dc_s) >= 1
204
205         try:
206             level_forest = int(res_forest[0]["msDS-Behavior-Version"][0])
207             level_domain = int(res_domain[0]["msDS-Behavior-Version"][0])
208             level_domain_mixed = int(res_domain[0]["nTMixedDomain"][0])
209
210             min_level_dc = int(res_dc_s[0]["msDS-Behavior-Version"][0]) # Init value
211             for msg in res_dc_s:
212                 if int(msg["msDS-Behavior-Version"][0]) < min_level_dc:
213                     min_level_dc = int(msg["msDS-Behavior-Version"][0])
214
215             if level_forest < 0 or level_domain < 0:
216                 raise CommandError("Domain and/or forest function level(s) is/are invalid. Correct them or reprovision!")
217             if min_level_dc < 0:
218                 raise CommandError("Lowest function level of a DC is invalid. Correct this or reprovision!")
219             if level_forest > level_domain:
220                 raise CommandError("Forest function level is higher than the domain level(s). Correct this or reprovision!")
221             if level_domain > min_level_dc:
222                 raise CommandError("Domain function level is higher than the lowest function level of a DC. Correct this or reprovision!")
223
224         except KeyError:
225             raise CommandError("Could not retrieve the actual domain, forest level and/or lowest DC function level!")
226
227         if subcommand == "show":
228             self.message("Domain and forest function level for domain '%s'" % domain_dn)
229             if level_forest == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
230                 self.message("\nATTENTION: You run SAMBA 4 on a forest function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
231             if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
232                 self.message("\nATTENTION: You run SAMBA 4 on a domain function level lower than Windows 2000 (Native). This isn't supported! Please raise!")
233             if min_level_dc == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
234                 self.message("\nATTENTION: You run SAMBA 4 on a lowest function level of a DC lower than Windows 2003. This isn't supported! Please step-up or upgrade the concerning DC(s)!")
235
236             self.message("")
237
238             if level_forest == DS_DOMAIN_FUNCTION_2000:
239                 outstr = "2000"
240             elif level_forest == DS_DOMAIN_FUNCTION_2003_MIXED:
241                 outstr = "2003 with mixed domains/interim (NT4 DC support)"
242             elif level_forest == DS_DOMAIN_FUNCTION_2003:
243                 outstr = "2003"
244             elif level_forest == DS_DOMAIN_FUNCTION_2008:
245                 outstr = "2008"
246             elif level_forest == DS_DOMAIN_FUNCTION_2008_R2:
247                 outstr = "2008 R2"
248             else:
249                 outstr = "higher than 2008 R2"
250             self.message("Forest function level: (Windows) " + outstr)
251
252             if level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed != 0:
253                 outstr = "2000 mixed (NT4 DC support)"
254             elif level_domain == DS_DOMAIN_FUNCTION_2000 and level_domain_mixed == 0:
255                 outstr = "2000"
256             elif level_domain == DS_DOMAIN_FUNCTION_2003_MIXED:
257                 outstr = "2003 with mixed domains/interim (NT4 DC support)"
258             elif level_domain == DS_DOMAIN_FUNCTION_2003:
259                 outstr = "2003"
260             elif level_domain == DS_DOMAIN_FUNCTION_2008:
261                 outstr = "2008"
262             elif level_domain == DS_DOMAIN_FUNCTION_2008_R2:
263                 outstr = "2008 R2"
264             else:
265                 outstr = "higher than 2008 R2"
266             self.message("Domain function level: (Windows) " + outstr)
267
268             if min_level_dc == DS_DOMAIN_FUNCTION_2000:
269                 outstr = "2000"
270             elif min_level_dc == DS_DOMAIN_FUNCTION_2003:
271                 outstr = "2003"
272             elif min_level_dc == DS_DOMAIN_FUNCTION_2008:
273                 outstr = "2008"
274             elif min_level_dc == DS_DOMAIN_FUNCTION_2008_R2:
275                 outstr = "2008 R2"
276             else:
277                 outstr = "higher than 2008 R2"
278             self.message("Lowest function level of a DC: (Windows) " + outstr)
279
280         elif subcommand == "raise":
281             msgs = []
282
283             if domain_level is not None:
284                 if domain_level == "2003":
285                     new_level_domain = DS_DOMAIN_FUNCTION_2003
286                 elif domain_level == "2008":
287                     new_level_domain = DS_DOMAIN_FUNCTION_2008
288                 elif domain_level == "2008_R2":
289                     new_level_domain = DS_DOMAIN_FUNCTION_2008_R2
290
291                 if new_level_domain <= level_domain and level_domain_mixed == 0:
292                     raise CommandError("Domain function level can't be smaller than or equal to the actual one!")
293
294                 if new_level_domain > min_level_dc:
295                     raise CommandError("Domain function level can't be higher than the lowest function level of a DC!")
296
297                 # Deactivate mixed/interim domain support
298                 if level_domain_mixed != 0:
299                     # Directly on the base DN
300                     m = ldb.Message()
301                     m.dn = ldb.Dn(samdb, domain_dn)
302                     m["nTMixedDomain"] = ldb.MessageElement("0",
303                       ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
304                     samdb.modify(m)
305                     # Under partitions
306                     m = ldb.Message()
307                     m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup") + ",CN=Partitions,%s" % ldb.get_config_basedn())
308                     m["nTMixedDomain"] = ldb.MessageElement("0",
309                       ldb.FLAG_MOD_REPLACE, "nTMixedDomain")
310                     try:
311                         samdb.modify(m)
312                     except ldb.LdbError, (enum, emsg):
313                         if enum != ldb.ERR_UNWILLING_TO_PERFORM:
314                             raise
315
316                 # Directly on the base DN
317                 m = ldb.Message()
318                 m.dn = ldb.Dn(samdb, domain_dn)
319                 m["msDS-Behavior-Version"]= ldb.MessageElement(
320                   str(new_level_domain), ldb.FLAG_MOD_REPLACE,
321                             "msDS-Behavior-Version")
322                 samdb.modify(m)
323                 # Under partitions
324                 m = ldb.Message()
325                 m.dn = ldb.Dn(samdb, "CN=" + lp.get("workgroup")
326                   + ",CN=Partitions,%s" % ldb.get_config_basedn())
327                 m["msDS-Behavior-Version"]= ldb.MessageElement(
328                   str(new_level_domain), ldb.FLAG_MOD_REPLACE,
329                           "msDS-Behavior-Version")
330                 try:
331                     samdb.modify(m)
332                 except ldb.LdbError, (enum, emsg):
333                     if enum != ldb.ERR_UNWILLING_TO_PERFORM:
334                         raise
335
336                 level_domain = new_level_domain
337                 msgs.append("Domain function level changed!")
338
339             if forest_level is not None:
340                 if forest_level == "2003":
341                     new_level_forest = DS_DOMAIN_FUNCTION_2003
342                 elif forest_level == "2008":
343                     new_level_forest = DS_DOMAIN_FUNCTION_2008
344                 elif forest_level == "2008_R2":
345                     new_level_forest = DS_DOMAIN_FUNCTION_2008_R2
346                 if new_level_forest <= level_forest:
347                     raise CommandError("Forest function level can't be smaller than or equal to the actual one!")
348                 if new_level_forest > level_domain:
349                     raise CommandError("Forest function level can't be higher than the domain function level(s). Please raise it/them first!")
350                 m = ldb.Message()
351                 m.dn = ldb.Dn(samdb, "CN=Partitions,%s" % ldb.get_config_basedn())
352                 m["msDS-Behavior-Version"]= ldb.MessageElement(
353                   str(new_level_forest), ldb.FLAG_MOD_REPLACE,
354                           "msDS-Behavior-Version")
355                 samdb.modify(m)
356                 msgs.append("Forest function level changed!")
357             msgs.append("All changes applied successfully!")
358             self.message("\n".join(msgs))
359         else:
360             raise CommandError("invalid argument: '%s' (choose from 'show', 'raise')" % subcommand)
361
362
363
364 class cmd_domain_passwordsettings(Command):
365     """Sets password settings
366
367     Password complexity, history length, minimum password length, the minimum
368     and maximum password age) on a Samba4 server.
369     """
370
371     synopsis = "%prog (show|set <options>) [options]"
372
373     takes_options = [
374         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
375                metavar="URL", dest="H"),
376         Option("--quiet", help="Be quiet", action="store_true"),
377         Option("--complexity", type="choice", choices=["on","off","default"],
378           help="The password complexity (on | off | default). Default is 'on'"),
379         Option("--store-plaintext", type="choice", choices=["on","off","default"],
380           help="Store plaintext passwords where account have 'store passwords with reversible encryption' set (on | off | default). Default is 'off'"),
381         Option("--history-length",
382           help="The password history length (<integer> | default).  Default is 24.", type=str),
383         Option("--min-pwd-length",
384           help="The minimum password length (<integer> | default).  Default is 7.", type=str),
385         Option("--min-pwd-age",
386           help="The minimum password age (<integer in days> | default).  Default is 1.", type=str),
387         Option("--max-pwd-age",
388           help="The maximum password age (<integer in days> | default).  Default is 43.", type=str),
389           ]
390
391     takes_args = ["subcommand"]
392
393     def run(self, subcommand, H=None, min_pwd_age=None, max_pwd_age=None,
394             quiet=False, complexity=None, store_plaintext=None, history_length=None,
395             min_pwd_length=None, credopts=None, sambaopts=None,
396             versionopts=None):
397         lp = sambaopts.get_loadparm()
398         creds = credopts.get_credentials(lp)
399
400         samdb = SamDB(url=H, session_info=system_session(),
401             credentials=creds, lp=lp)
402
403         domain_dn = samdb.domain_dn()
404         res = samdb.search(domain_dn, scope=ldb.SCOPE_BASE,
405           attrs=["pwdProperties", "pwdHistoryLength", "minPwdLength",
406                  "minPwdAge", "maxPwdAge"])
407         assert(len(res) == 1)
408         try:
409             pwd_props = int(res[0]["pwdProperties"][0])
410             pwd_hist_len = int(res[0]["pwdHistoryLength"][0])
411             cur_min_pwd_len = int(res[0]["minPwdLength"][0])
412             # ticks -> days
413             cur_min_pwd_age = int(abs(int(res[0]["minPwdAge"][0])) / (1e7 * 60 * 60 * 24))
414             if int(res[0]["maxPwdAge"][0]) == -0x8000000000000000:
415                 cur_max_pwd_age = 0
416             else:
417                 cur_max_pwd_age = int(abs(int(res[0]["maxPwdAge"][0])) / (1e7 * 60 * 60 * 24))
418         except Exception, e:
419             raise CommandError("Could not retrieve password properties!", e)
420
421         if subcommand == "show":
422             self.message("Password informations for domain '%s'" % domain_dn)
423             self.message("")
424             if pwd_props & DOMAIN_PASSWORD_COMPLEX != 0:
425                 self.message("Password complexity: on")
426             else:
427                 self.message("Password complexity: off")
428             if pwd_props & DOMAIN_PASSWORD_STORE_CLEARTEXT != 0:
429                 self.message("Store plaintext passwords: on")
430             else:
431                 self.message("Store plaintext passwords: off")
432             self.message("Password history length: %d" % pwd_hist_len)
433             self.message("Minimum password length: %d" % cur_min_pwd_len)
434             self.message("Minimum password age (days): %d" % cur_min_pwd_age)
435             self.message("Maximum password age (days): %d" % cur_max_pwd_age)
436         elif subcommand == "set":
437             msgs = []
438             m = ldb.Message()
439             m.dn = ldb.Dn(samdb, domain_dn)
440
441             if complexity is not None:
442                 if complexity == "on" or complexity == "default":
443                     pwd_props = pwd_props | DOMAIN_PASSWORD_COMPLEX
444                     msgs.append("Password complexity activated!")
445                 elif complexity == "off":
446                     pwd_props = pwd_props & (~DOMAIN_PASSWORD_COMPLEX)
447                     msgs.append("Password complexity deactivated!")
448
449             if store_plaintext is not None:
450                 if store_plaintext == "on" or store_plaintext == "default":
451                     pwd_props = pwd_props | DOMAIN_PASSWORD_STORE_CLEARTEXT
452                     msgs.append("Plaintext password storage for changed passwords activated!")
453                 elif store_plaintext == "off":
454                     pwd_props = pwd_props & (~DOMAIN_PASSWORD_STORE_CLEARTEXT)
455                     msgs.append("Plaintext password storage for changed passwords deactivated!")
456
457             if complexity is not None or store_plaintext is not None:
458                 m["pwdProperties"] = ldb.MessageElement(str(pwd_props),
459                   ldb.FLAG_MOD_REPLACE, "pwdProperties")
460
461             if history_length is not None:
462                 if history_length == "default":
463                     pwd_hist_len = 24
464                 else:
465                     pwd_hist_len = int(history_length)
466
467                 if pwd_hist_len < 0 or pwd_hist_len > 24:
468                     raise CommandError("Password history length must be in the range of 0 to 24!")
469
470                 m["pwdHistoryLength"] = ldb.MessageElement(str(pwd_hist_len),
471                   ldb.FLAG_MOD_REPLACE, "pwdHistoryLength")
472                 msgs.append("Password history length changed!")
473
474             if min_pwd_length is not None:
475                 if min_pwd_length == "default":
476                     min_pwd_len = 7
477                 else:
478                     min_pwd_len = int(min_pwd_length)
479
480                 if min_pwd_len < 0 or min_pwd_len > 14:
481                     raise CommandError("Minimum password length must be in the range of 0 to 14!")
482
483                 m["minPwdLength"] = ldb.MessageElement(str(min_pwd_len),
484                   ldb.FLAG_MOD_REPLACE, "minPwdLength")
485                 msgs.append("Minimum password length changed!")
486
487             if min_pwd_age is not None:
488                 if min_pwd_age == "default":
489                     min_pwd_age = 1
490                 else:
491                     min_pwd_age = int(min_pwd_age)
492
493                 if min_pwd_age < 0 or min_pwd_age > 998:
494                     raise CommandError("Minimum password age must be in the range of 0 to 998!")
495
496                 # days -> ticks
497                 min_pwd_age_ticks = -int(min_pwd_age * (24 * 60 * 60 * 1e7))
498
499                 m["minPwdAge"] = ldb.MessageElement(str(min_pwd_age_ticks),
500                   ldb.FLAG_MOD_REPLACE, "minPwdAge")
501                 msgs.append("Minimum password age changed!")
502
503             if max_pwd_age is not None:
504                 if max_pwd_age == "default":
505                     max_pwd_age = 43
506                 else:
507                     max_pwd_age = int(max_pwd_age)
508
509                 if max_pwd_age < 0 or max_pwd_age > 999:
510                     raise CommandError("Maximum password age must be in the range of 0 to 999!")
511
512                 # days -> ticks
513                 if max_pwd_age == 0:
514                     max_pwd_age_ticks = -0x8000000000000000
515                 else:
516                     max_pwd_age_ticks = -int(max_pwd_age * (24 * 60 * 60 * 1e7))
517
518                 m["maxPwdAge"] = ldb.MessageElement(str(max_pwd_age_ticks),
519                   ldb.FLAG_MOD_REPLACE, "maxPwdAge")
520                 msgs.append("Maximum password age changed!")
521
522             if max_pwd_age > 0 and min_pwd_age >= max_pwd_age:
523                 raise CommandError("Maximum password age (%d) must be greater than minimum password age (%d)!" % (max_pwd_age, min_pwd_age))
524
525             if len(m) == 0:
526                 raise CommandError("You must specify at least one option to set. Try --help")
527             samdb.modify(m)
528             msgs.append("All changes applied successfully!")
529             self.message("\n".join(msgs))
530         else:
531             raise CommandError("Wrong argument '%s'!" % subcommand)
532
533
534 class cmd_domain_samba3upgrade(Command):
535     """Upgrade from Samba3 database to Samba4 AD database.
536
537     Specify either a directory with all samba3 databases and state files (with --dbdir) or
538     samba3 testparm utility (with --testparm).
539     """
540
541     synopsis = "%prog [options] <samba3_smb_conf>"
542
543     takes_optiongroups = {
544         "sambaopts": options.SambaOptions,
545         "versionopts": options.VersionOptions
546     }
547
548     takes_options = [
549         Option("--dbdir", type="string", metavar="DIR",
550                   help="Path to samba3 database directory"),
551         Option("--testparm", type="string", metavar="PATH",
552                   help="Path to samba3 testparm utility from the previous installation.  This allows the default paths of the previous installation to be followed"),
553         Option("--targetdir", type="string", metavar="DIR",
554                   help="Path prefix where the new Samba 4.0 AD domain should be initialised"),
555         Option("--quiet", help="Be quiet", action="store_true"),
556         Option("--verbose", help="Be verbose", action="store_true"),
557         Option("--use-xattrs", type="choice", choices=["yes","no","auto"], metavar="[yes|no|auto]",
558                    help="Define if we should use the native fs capabilities or a tdb file for storing attributes likes ntacl, auto tries to make an inteligent guess based on the user rights and system capabilities", default="auto"),
559     ]
560
561     takes_args = ["smbconf"]
562
563     def run(self, smbconf=None, targetdir=None, dbdir=None, testparm=None, 
564             quiet=False, verbose=False, use_xattrs=None, sambaopts=None, versionopts=None):
565
566         if not os.path.exists(smbconf):
567             raise CommandError("File %s does not exist" % smbconf)
568         
569         if testparm and not os.path.exists(testparm):
570             raise CommandError("Testparm utility %s does not exist" % testparm)
571
572         if dbdir and not os.path.exists(dbdir):
573             raise CommandError("Directory %s does not exist" % dbdir)
574
575         if not dbdir and not testparm:
576             raise CommandError("Please specify either dbdir or testparm")
577
578         logger = self.get_logger()
579         if verbose:
580             logger.setLevel(logging.DEBUG)
581         elif quiet:
582             logger.setLevel(logging.WARNING)
583         else:
584             logger.setLevel(logging.INFO)
585
586         if dbdir and testparm:
587             logger.warning("both dbdir and testparm specified, ignoring dbdir.")
588             dbdir = None
589
590         lp = sambaopts.get_loadparm()
591
592         s3conf = s3param.get_context()
593
594         if sambaopts.realm:
595             s3conf.set("realm", sambaopts.realm)
596
597         eadb = True
598         if use_xattrs == "yes":
599             eadb = False
600         elif use_xattrs == "auto" and not s3conf.get("posix:eadb"):
601             if targetdir:
602                 tmpfile = tempfile.NamedTemporaryFile(prefix=os.path.abspath(targetdir))
603             else:
604                 tmpfile = tempfile.NamedTemporaryFile(prefix=os.path.abspath(os.path.dirname(lp.get("private dir"))))
605             try:
606                 samba.ntacls.setntacl(lp, tmpfile.name,
607                             "O:S-1-5-32G:S-1-5-32", "S-1-5-32", "native")
608                 eadb = False
609             except:
610                 # FIXME: Don't catch all exceptions here
611                 logger.info("You are not root or your system do not support xattr, using tdb backend for attributes. "
612                             "If you intend to use this provision in production, rerun the script as root on a system supporting xattrs.")
613             tmpfile.close()
614
615         # Set correct default values from dbdir or testparm
616         paths = {}
617         if dbdir:
618             paths["state directory"] = dbdir
619             paths["private dir"] = dbdir
620             paths["lock directory"] = dbdir
621         else:
622             paths["state directory"] = get_testparm_var(testparm, smbconf, "state directory")
623             paths["private dir"] = get_testparm_var(testparm, smbconf, "private dir")
624             paths["lock directory"] = get_testparm_var(testparm, smbconf, "lock directory")
625             # "testparm" from Samba 3 < 3.4.x is not aware of the parameter
626             # "state directory", instead make use of "lock directory"
627             if len(paths["state directory"]) == 0:
628                 paths["state directory"] = paths["lock directory"]
629
630         for p in paths:
631             s3conf.set(p, paths[p])
632     
633         # load smb.conf parameters
634         logger.info("Reading smb.conf")
635         s3conf.load(smbconf)
636         samba3 = Samba3(smbconf, s3conf)
637     
638         logger.info("Provisioning")
639         upgrade_from_samba3(samba3, logger, targetdir, session_info=system_session(), 
640                             useeadb=eadb)
641
642 class cmd_domain(SuperCommand):
643     """Domain management"""
644
645     subcommands = {}
646     subcommands["exportkeytab"] = cmd_domain_export_keytab()
647     subcommands["info"] = cmd_domain_info()
648     subcommands["join"] = cmd_domain_join()
649     subcommands["level"] = cmd_domain_level()
650     subcommands["passwordsettings"] = cmd_domain_passwordsettings()
651     subcommands["samba3upgrade"] = cmd_domain_samba3upgrade()