| 1 |
import base64 |
| 2 |
import io |
| 3 |
import os |
| 4 |
from collections import defaultdict |
| 5 |
from itertools import groupby |
| 6 |
from typing import ( |
| 7 |
Dict, |
| 8 |
TextIO, |
| 9 |
Iterable, |
| 10 |
Iterator, |
| 11 |
Any, |
| 12 |
Optional, |
| 13 |
List, |
| 14 |
Union, |
| 15 |
Mapping, |
| 16 |
Callable, |
| 17 |
KeysView |
| 18 |
) |
| 19 |
|
| 20 |
from .ldapentry import LDAPEntry, LDAPModOp |
| 21 |
from .ldapvaluelist import LDAPValueList |
| 22 |
|
| 23 |
from .errors import LDAPError |
| 24 |
|
| 25 |
|
| 26 |
class LDIFError(LDAPError): |
| 27 |
"""General exception that is raised during reading or writing an LDIF file.""" |
| 28 |
|
| 29 |
code = -300 |
| 30 |
|
| 31 |
|
| 32 |
class LDIFReader: |
| 33 |
""" |
| 34 |
Create an object for reading LDAP entries from an LDIF format file \ |
| 35 |
as described in RFC 2849. |
| 36 |
|
| 37 |
:param TextIO input_file: a file-like input object in text mode. |
| 38 |
:param bool autoload: allow to automatically load external \ |
| 39 |
sources from URL. |
| 40 |
:param int max_length: the maximal line length of the LDIF file. |
| 41 |
:raises TypeError: if the input_file is not a file-like object \ |
| 42 |
or max_length is not an int. |
| 43 |
""" |
| 44 |
|
| 45 |
def __init__( |
| 46 |
self, input_file: TextIO, autoload: bool = True, max_length: int = 76 |
| 47 |
) -> None: |
| 48 |
"""Init method.""" |
| 49 |
if not isinstance(max_length, int): |
| 50 |
raise TypeError("The max_length must be int.") |
| 51 |
self.__file: TextIO |
| 52 |
self.input_file = input_file |
| 53 |
self.autoload = autoload |
| 54 |
self.max_length = max_length |
| 55 |
self.version: Optional[int] = None |
| 56 |
self.__entries = self.__read_attributes() |
| 57 |
self.__num_of_entries = 0 |
| 58 |
self.__resource_handlers = {"file": self.__load_file} |
| 59 |
|
| 60 |
def __read_attributes(self) -> Iterator[List[str]]: |
| 61 |
buffer: List[str] = [] |
| 62 |
comment = False |
| 63 |
for num, line in enumerate(self.__file): |
| 64 |
try: |
| 65 |
if len(line) > self.max_length: |
| 66 |
raise LDIFError(f"Line {num + 1} is too long.") |
| 67 |
if len(line.strip()) == 0: |
| 68 |
yield buffer |
| 69 |
buffer.clear() |
| 70 |
continue |
| 71 |
if line[0] == " ": |
| 72 |
if not comment: |
| 73 |
|
| 74 |
buffer[-1] = "".join((buffer[-1], line[1:].rstrip())) |
| 75 |
continue |
| 76 |
elif line[0] == "#": |
| 77 |
comment = True |
| 78 |
else: |
| 79 |
comment = False |
| 80 |
if comment: |
| 81 |
|
| 82 |
continue |
| 83 |
else: |
| 84 |
buffer.append(line.rstrip()) |
| 85 |
except IndexError: |
| 86 |
raise LDIFError(f"Parser error at line: {num + 1}.") from None |
| 87 |
if buffer: |
| 88 |
yield buffer |
| 89 |
|
| 90 |
@staticmethod |
| 91 |
def __convert(val: Union[str, bytes]) -> Union[str, bytes, int]: |
| 92 |
try: |
| 93 |
return int(val) |
| 94 |
except ValueError: |
| 95 |
try: |
| 96 |
return val.decode("UTF-8") |
| 97 |
except (ValueError, AttributeError): |
| 98 |
pass |
| 99 |
return val |
| 100 |
|
| 101 |
@staticmethod |
| 102 |
def __find_key(searched_key: str, keylist: KeysView[str]) -> Optional[str]: |
| 103 |
for key in keylist: |
| 104 |
if key.lower() == searched_key.lower(): |
| 105 |
return key |
| 106 |
else: |
| 107 |
raise KeyError(searched_key) |
| 108 |
|
| 109 |
def __load_file(self, url: str) -> bytes: |
| 110 |
_, path = url.split("file://") |
| 111 |
abs_filepath = os.path.normpath( |
| 112 |
os.path.join(os.path.dirname(os.path.abspath(self.__file.name)), path) |
| 113 |
) |
| 114 |
with open(abs_filepath, "rb") as resource: |
| 115 |
return resource.read() |
| 116 |
|
| 117 |
def load_resource(self, url: str) -> bytes: |
| 118 |
try: |
| 119 |
scheme, _ = url.split(":", maxsplit=1) |
| 120 |
return self.__resource_handlers[scheme](url) |
| 121 |
except (KeyError, ValueError): |
| 122 |
raise LDIFError(f"Unsupported URL format: {url}.") from None |
| 123 |
|
| 124 |
def __iter__(self) -> "LDIFReader": |
| 125 |
return self |
| 126 |
|
| 127 |
def __next__(self) -> LDAPEntry: |
| 128 |
entry = LDAPEntry("") |
| 129 |
change_type = "add" |
| 130 |
attr_blocks = [ |
| 131 |
list(group) |
| 132 |
for key, group in groupby(next(self.__entries), lambda line: line == "-") |
| 133 |
if not key |
| 134 |
] |
| 135 |
self.__num_of_entries += 1 |
| 136 |
for block in attr_blocks: |
| 137 |
attr_dict: Dict[str, LDAPValueList] = defaultdict(LDAPValueList) |
| 138 |
for attrval in block: |
| 139 |
try: |
| 140 |
if ":: " in attrval: |
| 141 |
attr, val = attrval.split(":: ") |
| 142 |
val = base64.b64decode(val) |
| 143 |
elif ": " in attrval: |
| 144 |
attr, val = attrval.split(": ", maxsplit=1) |
| 145 |
if ord(val[0]) > 127 or val[0] in ( |
| 146 |
"\0", |
| 147 |
"\n", |
| 148 |
"\r", |
| 149 |
" ", |
| 150 |
":", |
| 151 |
"<", |
| 152 |
): |
| 153 |
raise ValueError("Not a safe first character in value.") |
| 154 |
elif ":< " in attrval: |
| 155 |
attr, val = attrval.split(":< ") |
| 156 |
if self.__autoload: |
| 157 |
val = self.load_resource(val) |
| 158 |
else: |
| 159 |
raise ValueError("Missing valid attribute value separator.") |
| 160 |
except ValueError as err: |
| 161 |
raise LDIFError( |
| 162 |
f"Invalid attribute value pair: '{attrval}'" |
| 163 |
f" for entry #{self.__num_of_entries}." |
| 164 |
) from err |
| 165 |
if attr.lower() == "changetype": |
| 166 |
change_type = val.lower() |
| 167 |
elif attr.lower() == "dn": |
| 168 |
entry.dn = self.__convert(val) |
| 169 |
elif attr.lower() == "version": |
| 170 |
self.version = self.__convert(val) |
| 171 |
else: |
| 172 |
attr_dict[attr].append(self.__convert(val)) |
| 173 |
if change_type == "modify": |
| 174 |
try: |
| 175 |
for key in attr_dict.pop("add", []): |
| 176 |
key = self.__find_key(key, attr_dict.keys()) |
| 177 |
entry.change_attribute(key, LDAPModOp.ADD, *attr_dict[key]) |
| 178 |
for key in attr_dict.pop("replace", []): |
| 179 |
key = self.__find_key(key, attr_dict.keys()) |
| 180 |
entry.change_attribute(key, LDAPModOp.REPLACE, *attr_dict[key]) |
| 181 |
for key in attr_dict.pop("delete", []): |
| 182 |
try: |
| 183 |
key = self.__find_key(key, attr_dict.keys()) |
| 184 |
except KeyError: |
| 185 |
pass |
| 186 |
entry.change_attribute(key, LDAPModOp.DELETE, *attr_dict[key]) |
| 187 |
except KeyError as err: |
| 188 |
raise LDIFError( |
| 189 |
f"Missing attribute: '{err.args[0]}' for entry #{self.__num_of_entries}." |
| 190 |
) |
| 191 |
elif change_type == "add": |
| 192 |
for key, vals in attr_dict.items(): |
| 193 |
entry[key] = vals |
| 194 |
if entry.dn == "": |
| 195 |
raise LDIFError( |
| 196 |
f"Missing distinguished name for entry #{self.__num_of_entries}." |
| 197 |
) |
| 198 |
return entry |
| 199 |
|
| 200 |
@property |
| 201 |
def input_file(self) -> TextIO: |
| 202 |
"""The file-like object of an LDIF file.""" |
| 203 |
return self.__file |
| 204 |
|
| 205 |
@input_file.setter |
| 206 |
def input_file(self, value: TextIO) -> None: |
| 207 |
if not isinstance(value, io.TextIOBase): |
| 208 |
raise TypeError("The input_file must be file-like object in text mode.") |
| 209 |
self.__file = value |
| 210 |
|
| 211 |
@property |
| 212 |
def autoload(self) -> bool: |
| 213 |
"""Enable/disable autoloading resources in LDIF files.""" |
| 214 |
return self.__autoload |
| 215 |
|
| 216 |
@autoload.setter |
| 217 |
def autoload(self, value: bool) -> None: |
| 218 |
if not isinstance(value, bool): |
| 219 |
raise TypeError("The autoload property must be bool.") |
| 220 |
self.__autoload = value |
| 221 |
|
| 222 |
@property |
| 223 |
def resource_handlers(self) -> Mapping[str, Callable[[str], bytes]]: |
| 224 |
""" |
| 225 |
A dictionary of supported resource types. The keys are the schemes, |
| 226 |
while the values are functions that expect the full URL parameters |
| 227 |
and return the loaded content in preferably bytes format. |
| 228 |
""" |
| 229 |
return self.__resource_handlers |
| 230 |
|
| 231 |
|
| 232 |
class LDIFWriter: |
| 233 |
""" |
| 234 |
Create an object for serialising LDAP entries in LDIF format as |
| 235 |
described in RFC 2849. |
| 236 |
|
| 237 |
:param TextIO output_file: a file-like output object in text mode. |
| 238 |
:param int max_length: the maximal line length of the LDIF file. |
| 239 |
:raises TypeError: if the output_file is not a file-like object \ |
| 240 |
or max_length is not an int. |
| 241 |
""" |
| 242 |
|
| 243 |
def __init__(self, output_file: TextIO, max_length: int = 76) -> None: |
| 244 |
"""Init method.""" |
| 245 |
if not isinstance(max_length, int): |
| 246 |
raise TypeError("The max_length must be int.") |
| 247 |
self.__file: TextIO |
| 248 |
self.output_file = output_file |
| 249 |
self.max_length = max_length |
| 250 |
|
| 251 |
def _get_attr_lines(self, attrname: str, attrvalue: Iterable[Any]) -> Iterator[str]: |
| 252 |
for val in attrvalue: |
| 253 |
if isinstance(val, (bytes, bytearray)): |
| 254 |
|
| 255 |
has_not_safe_char = True |
| 256 |
has_not_safe_init_char = True |
| 257 |
else: |
| 258 |
val = str(val) |
| 259 |
has_not_safe_char = any( |
| 260 |
char |
| 261 |
for char in val |
| 262 |
if ord(char) > 127 or ord(char) in (0x0A, 0x0D, 0x00) |
| 263 |
) or val.endswith(" ") |
| 264 |
has_not_safe_init_char = val[0] in (" ", ":", "<") |
| 265 |
val = val.encode("UTF-8") |
| 266 |
if has_not_safe_char or has_not_safe_init_char: |
| 267 |
val = base64.b64encode(val) |
| 268 |
name = f"{attrname}:" |
| 269 |
else: |
| 270 |
name = attrname |
| 271 |
line = f"{name}: {val.decode('UTF-8')}" |
| 272 |
for i in range(0, len(line), self.max_length): |
| 273 |
|
| 274 |
if i != 0: |
| 275 |
yield f" {line[i : i + self.max_length]}\n" |
| 276 |
else: |
| 277 |
yield f"{line[i : i + self.max_length]}\n" |
| 278 |
|
| 279 |
def write_entry(self, entry: LDAPEntry) -> None: |
| 280 |
""" |
| 281 |
Write an LDAP entry to the file in LDIF format. |
| 282 |
|
| 283 |
:param LDAPEntry entry: the LDAP entry to serialise. |
| 284 |
""" |
| 285 |
for line in self._get_attr_lines("dn", (entry.dn,)): |
| 286 |
self.__file.write(line) |
| 287 |
for attrname, attrvalue in entry.items(exclude_dn=True): |
| 288 |
for line in self._get_attr_lines(attrname, attrvalue): |
| 289 |
self.__file.write(line) |
| 290 |
|
| 291 |
def write_entries( |
| 292 |
self, entries: Iterable[LDAPEntry], write_version: bool = True |
| 293 |
) -> None: |
| 294 |
""" |
| 295 |
Write multiple LDAP entry to file in LDIF format, separated |
| 296 |
with newline and with optional version header. |
| 297 |
|
| 298 |
:param list entries: list of LDAP entries. |
| 299 |
:param bool write_version: if it's True, write version header. |
| 300 |
""" |
| 301 |
if write_version: |
| 302 |
self.__file.write(next(self._get_attr_lines("version", (1,)))) |
| 303 |
for ent in entries: |
| 304 |
self.write_entry(ent) |
| 305 |
self.__file.write("\n") |
| 306 |
|
| 307 |
def write_changes(self, entry: LDAPEntry) -> None: |
| 308 |
""" |
| 309 |
Write an LDAP entry's changes to file in an LDIF-CHANGE format. |
| 310 |
Only attribute modifications are serialised. |
| 311 |
|
| 312 |
:param LDAPEntry entry: the LDAP entry to serialise. |
| 313 |
""" |
| 314 |
self.__file.write(next(self._get_attr_lines("dn", (entry.dn,)))) |
| 315 |
self.__file.write(next(self._get_attr_lines("changetype", ("modify",)))) |
| 316 |
changes = dict(entry._status()) |
| 317 |
deleted_keys = changes.pop("@deleted_keys") |
| 318 |
for attrname, stat in sorted(changes.items(), key=lambda s: s[1]["@status"]): |
| 319 |
if stat["@status"] == 1 and stat["@added"]: |
| 320 |
self.__file.write(next(self._get_attr_lines("add", (attrname,)))) |
| 321 |
for line in self._get_attr_lines(attrname, stat["@added"]): |
| 322 |
self.__file.write(line) |
| 323 |
self.__file.write("-\n") |
| 324 |
elif stat["@status"] == 1 and stat["@deleted"]: |
| 325 |
self.__file.write(next(self._get_attr_lines("delete", (attrname,)))) |
| 326 |
for line in self._get_attr_lines(attrname, stat["@deleted"]): |
| 327 |
self.__file.write(line) |
| 328 |
self.__file.write("-\n") |
| 329 |
elif stat["@status"] == 2: |
| 330 |
self.__file.write(next(self._get_attr_lines("replace", (attrname,)))) |
| 331 |
for line in self._get_attr_lines(attrname, stat["@added"]): |
| 332 |
self.__file.write(line) |
| 333 |
self.__file.write("-\n") |
| 334 |
for key in deleted_keys: |
| 335 |
self.__file.write(next(self._get_attr_lines("delete", (key,)))) |
| 336 |
self.__file.write("-\n") |
| 337 |
self.__file.write("\n") |
| 338 |
|
| 339 |
@property |
| 340 |
def output_file(self) -> TextIO: |
| 341 |
"""The file-like object for an LDIF file.""" |
| 342 |
return self.__file |
| 343 |
|
| 344 |
@output_file.setter |
| 345 |
def output_file(self, value: TextIO) -> None: |
| 346 |
if not isinstance(value, io.TextIOBase): |
| 347 |
raise TypeError("The output_file must be file-like object in text mode.") |
| 348 |
self.__file = value |