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