summaryrefslogtreecommitdiffstats
path: root/python/samba/netcmd/dbcheck.py
blob: 657881b5eea120a99b9a97494d732fbea5555111 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# Samba4 AD database checker
#
# Copyright (C) Andrew Tridgell 2011
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

import optparse
import sys

import ldb
import samba.getopt as options
from samba import colour
from samba.auth import system_session
from samba.dbchecker import dbcheck
from samba.samdb import SamDB

from . import Command, CommandError, Option


class cmd_dbcheck(Command):
    """Check local AD database for errors."""
    synopsis = "%prog [<DN>] [options]"

    takes_optiongroups = {
        "sambaopts": options.SambaOptions,
        "versionopts": options.VersionOptions,
        "credopts": options.CredentialsOptionsDouble,
    }

    def process_yes(option, opt, value, parser):
        assert value is None
        rargs = parser.rargs
        if rargs:
            arg = rargs[0]
            if ((arg[:2] == "--" and len(arg) > 2) or
                (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
                setattr(parser.values, "yes", True)
            else:
                setattr(parser.values, "yes_rules", arg.split())
                del rargs[0]
        else:
            setattr(parser.values, "yes", True)

    takes_args = ["DN?"]

    takes_options = [
        Option("--scope", dest="scope", default="SUB",
               help="Pass search scope that builds DN list. Options: SUB, ONE, BASE"),
        Option("--fix", dest="fix", default=False, action='store_true',
               help='Fix any errors found'),
        Option("--yes", action='callback', callback=process_yes,
               help="don't confirm changes individually. Applies all as a single transaction (will not succeed if any errors are found)"),
        Option("--cross-ncs", dest="cross_ncs", default=False, action='store_true',
               help="cross naming context boundaries"),
        Option("-v", "--verbose", dest="verbose", action="store_true", default=False,
               help="Print more details of checking"),
        Option("-q", "--quiet", action="store_true", default=False,
               help="don't print details of checking"),
        Option("--attrs", dest="attrs", default=None, help="list of attributes to check (space separated)"),
        Option("--reindex", dest="reindex", default=False, action="store_true", help="force database re-index"),
        Option("--force-modules", dest="force_modules", default=False, action="store_true", help="force loading of Samba modules and ignore the @MODULES record (for very old databases)"),
        Option("--reset-well-known-acls",
               dest="reset_well_known_acls",
               default=False, action="store_true",
               help=("reset ACLs on objects with well known default values"
                     " (for updating from early 4.0.x)")),
        Option("--quick-membership-checks", dest="quick_membership_checks",
               help=("Skips missing/orphaned memberOf backlinks checks, "
                     "but speeds up dbcheck dramatically for domains with "
                     "large groups"),
               default=False, action="store_true"),
        Option("-H", "--URL", help="LDB URL for database or target server (defaults to local SAM database)",
               type=str, metavar="URL", dest="H"),
        Option("--selftest-check-expired-tombstones",
               dest="selftest_check_expired_tombstones", default=False, action="store_true",
               help=optparse.SUPPRESS_HELP),  # This is only used by tests
    ]

    def run(self, DN=None, H=None, verbose=False, fix=False, yes=False,
            cross_ncs=False, quiet=False,
            scope="SUB", credopts=None, sambaopts=None, versionopts=None,
            attrs=None, reindex=False, force_modules=False,
            quick_membership_checks=False,
            reset_well_known_acls=False,
            selftest_check_expired_tombstones=False,
            yes_rules=None):

        if yes_rules is None:
            yes_rules = []

        lp = sambaopts.get_loadparm()

        over_ldap = H is not None and H.startswith('ldap')

        if over_ldap:
            creds = credopts.get_credentials(lp, fallback_machine=True)
        else:
            creds = None

        if force_modules:
            samdb = SamDB(session_info=system_session(), url=H,
                          credentials=creds, lp=lp, options=["modules=samba_dsdb"])
        else:
            try:
                samdb = SamDB(session_info=system_session(), url=H,
                              credentials=creds, lp=lp)
            except:
                raise CommandError("Failed to connect to DB at %s.  If this is a really old sam.ldb (before alpha9), then try again with --force-modules" % H)

        if H is None or not over_ldap:
            samdb_schema = samdb
        else:
            samdb_schema = SamDB(session_info=system_session(), url=None,
                                 credentials=creds, lp=lp)

        scope_map = {"SUB": ldb.SCOPE_SUBTREE, "BASE": ldb.SCOPE_BASE, "ONE": ldb.SCOPE_ONELEVEL}
        scope = scope.upper()
        if scope not in scope_map:
            raise CommandError("Unknown scope %s" % scope)
        search_scope = scope_map[scope]

        controls = ['show_deleted:1']
        if over_ldap:
            controls.append('paged_results:1:1000')
        if cross_ncs:
            controls.append("search_options:1:2")

        if not attrs:
            attrs = ['*']
        else:
            attrs = attrs.split()

        # The dbcheck module always prints to stdout, not our self.outf
        # (yes, maybe FIXME).
        stdout_colour = colour.colour_if_wanted(sys.stdout,
                                                hint=self.requested_colour)

        started_transaction = False
        if yes and fix:
            samdb.transaction_start()
            started_transaction = True
        try:
            chk = dbcheck(samdb, samdb_schema=samdb_schema, verbose=verbose,
                          fix=fix, yes=yes, quiet=quiet,
                          in_transaction=started_transaction,
                          quick_membership_checks=quick_membership_checks,
                          reset_well_known_acls=reset_well_known_acls,
                          check_expired_tombstones=selftest_check_expired_tombstones,
                          colour=stdout_colour)

            for option in yes_rules:
                if hasattr(chk, option):
                    setattr(chk, option, 'ALL')
                else:
                    raise CommandError("Invalid fix rule %s" % option)

            if reindex:
                self.outf.write("Re-indexing...\n")
                error_count = 0
                if chk.reindex_database():
                    self.outf.write("completed re-index OK\n")

            elif force_modules:
                self.outf.write("Resetting @MODULES...\n")
                error_count = 0
                if chk.reset_modules():
                    self.outf.write("completed @MODULES reset OK\n")

            else:
                error_count = chk.check_database(DN=DN, scope=search_scope,
                                                 controls=controls, attrs=attrs)
        except:
            if started_transaction:
                samdb.transaction_cancel()
            raise

        if started_transaction:
            samdb.transaction_commit()

        if error_count != 0:
            sys.exit(1)