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