1# Samba common functions
2#
3# Copyright (C) Matthieu Patou <mat@matws.net>
4#
5# This program is free software; you can redistribute it and/or modify
6# it under the terms of the GNU General Public License as published by
7# the Free Software Foundation; either version 3 of the License, or
8# (at your option) any later version.
9#
10# This program is distributed in the hope that it will be useful,
11# but WITHOUT ANY WARRANTY; without even the implied warranty of
12# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13# GNU General Public License for more details.
14#
15# You should have received a copy of the GNU General Public License
16# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17#
18
19
20import ldb
21from samba import dsdb
22from samba.ndr import ndr_pack
23from samba.dcerpc import misc
24import binascii
25
26from samba.compat import PY3
27
28
29if PY3:
30    # cmp() exists only in Python 2
31    def cmp(a, b):
32        return (a > b) - (a < b)
33
34    raw_input = input
35
36
37def confirm(msg, forced=False, allow_all=False):
38    """confirm an action with the user
39
40    :param msg: A string to print to the user
41    :param forced: Are the answer forced
42    """
43    if forced:
44        print("%s [YES]" % msg)
45        return True
46
47    mapping = {
48        'Y': True,
49        'YES': True,
50        '': False,
51        'N': False,
52        'NO': False,
53    }
54
55    prompt = '[y/N]'
56
57    if allow_all:
58        mapping['ALL'] = 'ALL'
59        mapping['NONE'] = 'NONE'
60        prompt = '[y/N/all/none]'
61
62    while True:
63        v = raw_input(msg + ' %s ' % prompt)
64        v = v.upper()
65        if v in mapping:
66            return mapping[v]
67        print("Unknown response '%s'" % v)
68
69
70def normalise_int32(ivalue):
71    '''normalise a ldap integer to signed 32 bit'''
72    if int(ivalue) & 0x80000000 and int(ivalue) > 0:
73        return str(int(ivalue) - 0x100000000)
74    return str(ivalue)
75
76
77class dsdb_Dn(object):
78    '''a class for binary DN'''
79
80    def __init__(self, samdb, dnstring, syntax_oid=None):
81        '''create a dsdb_Dn'''
82        if syntax_oid is None:
83            # auto-detect based on string
84            if dnstring.startswith("B:"):
85                syntax_oid = dsdb.DSDB_SYNTAX_BINARY_DN
86            elif dnstring.startswith("S:"):
87                syntax_oid = dsdb.DSDB_SYNTAX_STRING_DN
88            else:
89                syntax_oid = dsdb.DSDB_SYNTAX_OR_NAME
90        if syntax_oid in [dsdb.DSDB_SYNTAX_BINARY_DN, dsdb.DSDB_SYNTAX_STRING_DN]:
91            # it is a binary DN
92            colons = dnstring.split(':')
93            if len(colons) < 4:
94                raise RuntimeError("Invalid DN %s" % dnstring)
95            prefix_len = 4 + len(colons[1]) + int(colons[1])
96            self.prefix = dnstring[0:prefix_len]
97            self.binary = self.prefix[3 + len(colons[1]):-1]
98            self.dnstring = dnstring[prefix_len:]
99        else:
100            self.dnstring = dnstring
101            self.prefix = ''
102            self.binary = ''
103        self.dn = ldb.Dn(samdb, self.dnstring)
104
105    def __str__(self):
106        return self.prefix + str(self.dn.extended_str(mode=1))
107
108    def __cmp__(self, other):
109        ''' compare dsdb_Dn values similar to parsed_dn_compare()'''
110        dn1 = self
111        dn2 = other
112        guid1 = dn1.dn.get_extended_component("GUID")
113        guid2 = dn2.dn.get_extended_component("GUID")
114
115        v = cmp(guid1, guid2)
116        if v != 0:
117            return v
118        v = cmp(dn1.binary, dn2.binary)
119        return v
120
121    # In Python3, __cmp__ is replaced by these 6 methods
122    def __eq__(self, other):
123        return self.__cmp__(other) == 0
124
125    def __ne__(self, other):
126        return self.__cmp__(other) != 0
127
128    def __lt__(self, other):
129        return self.__cmp__(other) < 0
130
131    def __le__(self, other):
132        return self.__cmp__(other) <= 0
133
134    def __gt__(self, other):
135        return self.__cmp__(other) > 0
136
137    def __ge__(self, other):
138        return self.__cmp__(other) >= 0
139
140    def get_binary_integer(self):
141        '''return binary part of a dsdb_Dn as an integer, or None'''
142        if self.prefix == '':
143            return None
144        return int(self.binary, 16)
145
146    def get_bytes(self):
147        '''return binary as a byte string'''
148        return binascii.unhexlify(self.binary)
149