forked from turnkeylinux/tklbam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
userdb.py
279 lines (202 loc) · 7.36 KB
/
userdb.py
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
#
# Copyright (c) 2010-2016 Liraz Siri <[email protected]>
#
# This file is part of TKLBAM (TurnKey GNU/Linux BAckup and Migration).
#
# TKLBAM is open source 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.
#
class Error(Exception):
pass
from collections import OrderedDict
class Base(OrderedDict):
class Ent(list):
LEN = None
def _field(self, index, val=None):
if val is not None:
self[index] = str(val)
else:
return self[index]
def name(self, val=None):
return self._field(0, val)
name = property(name, name)
def id(self, val=None):
val = self._field(2, val)
if val is not None:
return int(val)
id = property(id, id)
def copy(self):
return type(self)(self[:])
def _fix_missing_root(self):
if 'root' in self:
return
def get_altroot(db):
for name in db:
if db[name].id == 0:
altroot = db[name].copy()
break
else:
names = db.keys()
if not names:
return # empty db, nothing we can do.
altroot = db[names.pop()].copy()
altroot.id = 0
altroot.name = 'root'
return altroot
self['root'] = get_altroot(self)
def __init__(self, arg=None):
OrderedDict.__init__(self)
if not arg:
return
if isinstance(arg, str):
for line in arg.strip().split('\n'):
vals = line.split(':')
if self.Ent.LEN:
if len(vals) != self.Ent.LEN:
raise Error("line with incorrect field count (%d != %d) '%s'" % (len(vals), self.Ent.LEN, line))
name = vals[0]
self[name] = self.Ent(vals)
self._fix_missing_root()
elif isinstance(arg, dict):
OrderedDict.__init__(self, arg)
def __str__(self):
ents = self.values()
ents.sort(lambda a,b: cmp(a.id, b.id))
return "\n".join([ ':'.join(ent) for ent in ents ]) + "\n"
def ids(self):
return [ self[name].id for name in self ]
ids = property(ids)
def new_id(self, extra_ids=[], old_id=1000):
"""find first new id in the same number range as old id"""
ids = set(self.ids + extra_ids)
_range = None
if old_id < 100:
_range = (1, 100)
elif old_id < 1000:
_range = (100, 1000)
if _range:
for id in range(*_range):
if id not in ids:
return id
for id in range(1000, 65534):
if id not in ids:
return id
raise Error("can't find slot for new id")
def aliases(self, name):
if name not in self:
return []
name_id = self[name].id
aliases = []
for other in self:
if other == name:
continue
if self[other].id == name_id:
aliases.append(other)
return aliases
@staticmethod
def _merge_get_entry(name, db_old, db_new, merged_ids=[]):
"""get merged db entry (without side effects)"""
oldent = db_old[name].copy() if name in db_old else None
newent = db_new[name].copy() if name in db_new else None
# entry exists in neither
if oldent is None and newent is None:
return
# entry exists only in new db
if newent and oldent is None:
return newent
# entry exists in old db
ent = oldent
# entry exists in both new and old dbs
if oldent and newent:
if ent.id != newent.id:
ent.id = newent.id
# entry exists only in old db
if oldent and newent is None:
used_ids = db_new.ids + merged_ids
if ent.id in used_ids:
ent.id = db_old.new_id(used_ids)
return ent
@classmethod
def merge(cls, db_old, db_new):
db_merged = cls()
old2newids = {}
aliased = []
names = set(db_old) | set(db_new)
def merge_entry(name):
ent = cls._merge_get_entry(name, db_old, db_new, db_merged.ids)
if name in db_old and db_old[name].id != ent.id:
old2newids[db_old[name].id] = ent.id
db_merged[name] = ent
# merge non-aliased entries first
for name in names:
if db_old.aliases(name):
aliased.append(name)
continue
merge_entry(name)
def aliased_sort(a, b):
# sorting order:
# 1) common entry with common uid first
# 2) common entry without common uid
# 3) uncommon entry
a_has_common_uid = a in db_new and db_new[a].id == db_old[a].id
b_has_common_uid = b in db_new and db_new[b].id == db_old[b].id
comparison = cmp(b_has_common_uid, a_has_common_uid)
if comparison != 0:
return comparison
# if we're here, neither a or b has a common uid
# check if a or b are common to both db_old and db_new
a_is_common = a in db_old and a in db_new
b_is_common = b in db_old and b in db_new
return cmp(b_is_common, a_is_common)
aliased.sort(aliased_sort)
def get_merged_alias_id(name):
for alias in db_old.aliases(name):
if alias not in db_merged:
continue
return db_merged[alias].id
return None
for name in aliased:
ent = cls.Ent(db_old[name])
merged_id = get_merged_alias_id(name)
if merged_id is None:
merge_entry(name)
else:
# merge alias entry with the id of any previously merged alias
ent.id = merged_id
db_merged[name] = ent
if name in db_new and db_new[name].id != ent.id:
# we can't remap ids in new, so merge new entry as *_copy of itself
new_ent = cls.Ent(db_new[name])
new_ent.name = new_ent.name + '_orig'
db_merged[new_ent.name] = new_ent
return db_merged, old2newids
class EtcGroup(Base):
class Ent(Base.Ent):
LEN = 4
gid = Base.Ent.id
class EtcPasswd(Base):
class Ent(Base.Ent):
LEN = 7
uid = Base.Ent.id
def gid(self, val=None):
if val:
self[3] = str(val)
else:
return int(self[3])
gid = property(gid, gid)
def fixgids(self, gidmap):
for name in self:
oldgid = self[name].gid
if oldgid in gidmap:
self[name].gid = gidmap[oldgid]
def merge(old_passwd, old_group, new_passwd, new_group):
g1 = EtcGroup(old_group)
g2 = EtcGroup(new_group)
group, gidmap = EtcGroup.merge(g1, g2)
p1 = EtcPasswd(old_passwd)
p2 = EtcPasswd(new_passwd)
p1.fixgids(gidmap)
passwd, uidmap = EtcPasswd.merge(p1, p2)
return passwd, group, uidmap, gidmap