#!/usr/bin/python3 """ ldif - generate and parse LDIF data (see RFC 2849) written by Michael Stroeder See http://python-ldap.sourceforge.net for details. $Id: ldif.py,v 1.3 2008/02/11 16:35:43 dwelch Exp $ Python compability note: Tested with Python 2.0+, but should work with Python 1.5.2+. The python-ldap package is distributed under Python-style license. Standard disclaimer: This software is made available by the author(s) to the public for free and "as is". All users of this free software are solely and entirely responsible for their own choice and use of this software for their own purposes. By using this software, each user agrees that the author(s) shall not be liable for damages of any kind in relation to its use or performance. The author(s) do not warrant that this software is fit for any purpose. Note: This file is part of the python-ldap package. For the complete python-ldap package, please visit: http://sourceforge.net/projects/python-ldap/ It has been modified for use in HPLIP. """ __version__ = '0.5.5' __all__ = [ # constants 'ldif_pattern', # functions 'AttrTypeandValueLDIF', 'CreateLDIF', 'ParseLDIF', # classes 'LDIFWriter', 'LDIFParser', 'LDIFRecordList', 'LDIFCopy', ] from .sixext.moves import urllib2_request, urllib2_parse, urllib2_error import base64 import re import types try: from io import StringIO except ImportError: from io import StringIO from .g import * attrtype_pattern = r'[\w;.]+(;[\w_-]+)*' attrvalue_pattern = r'(([^,]|\\,)+|".*?")' rdn_pattern = attrtype_pattern + r'[ ]*=[ ]*' + attrvalue_pattern dn_pattern = rdn_pattern + r'([ ]*,[ ]*' + rdn_pattern + r')*[ ]*' dn_regex = re.compile('^%s$' % dn_pattern) ldif_pattern = '^((dn(:|::) %(dn_pattern)s)|(%(attrtype_pattern)s(:|::) .*)$)+' % vars() MOD_OP_INTEGER = { 'add':0, 'delete':1, 'replace':2 } MOD_OP_STR = { 0:'add', 1:'delete', 2:'replace' } CHANGE_TYPES = ['add', 'delete', 'modify', 'modrdn'] valid_changetype_dict = {} for c in CHANGE_TYPES: valid_changetype_dict[c]=None SAFE_STRING_PATTERN = '(^(\000|\n|\r| |:|<)|[\000\n\r\200-\377]+|[ ]+$)' safe_string_re = re.compile(SAFE_STRING_PATTERN) def is_dn(s): """ returns 1 if s is a LDAP DN """ if s=='': return 1 rm = dn_regex.match(s) return rm!=None and rm.group(0)==s def needs_base64(s): """ returns 1 if s has to be base-64 encoded because of special chars """ return not safe_string_re.search(s) is None def list_dict(l): """ return a dictionary with all items of l being the keys of the dictionary """ return dict([(i, None) for i in l]) class LDIFWriter: """ Write LDIF entry or change records to file object Copy LDIF input to a file output object containing all data retrieved via URLs """ def __init__(self, output_file, base64_attrs=None, cols=76, line_sep='\n'): """ output_file file object for output base64_attrs list of attribute types to be base64-encoded in any case cols Specifies how many columns a line may have before it's folded into many lines. line_sep String used as line separator """ self._output_file = output_file self._base64_attrs = list_dict([a.lower() for a in (bases64_attrs or [])]) self._cols = cols self._line_sep = line_sep self.records_written = 0 def _unfoldLDIFLine(self, line): """ Write string line as one or more folded lines """ # Check maximum line length line_len = len(line) if line_len<=self._cols: self._output_file.write(line) self._output_file.write(self._line_sep) else: # Fold line pos = self._cols self._output_file.write(line[0:min(line_len, self._cols)]) self._output_file.write(self._line_sep) while pos %s" % (repr(attr_type), repr(attr_value))) if not attr_type or not attr_value: attr_type, attr_value = self._parseAttrTypeandValue() continue if attr_type == 'dn': # attr type and value pair was DN of LDIF record if dn is not None: raise ValueError('Two lines starting with dn: in one record.') if not is_dn(attr_value): raise ValueError('No valid string-representation of distinguished name %s.' % (repr(attr_value))) dn = attr_value elif attr_type == 'version' and dn is None: version = 1 elif attr_type == 'changetype': # attr type and value pair was DN of LDIF record if dn is None: raise ValueError('Read changetype: before getting valid dn: line.') if changetype is not None: raise ValueError('Two lines starting with changetype: in one record.') if not attr_value.lower() in valid_changetype_dict: raise ValueError('changetype value %s is invalid.' % (repr(attr_value))) changetype = attr_value elif attr_value is not None and \ attr_type.lower() not in self._ignored_attr_types: # Add the attribute to the entry if not ignored attribute if attr_type in entry: entry[attr_type].append(attr_value) else: entry[attr_type]=[attr_value] # Read the next line within an entry attr_type, attr_value = self._parseAttrTypeandValue() if entry: # append entry to result list self.handle(dn, entry) self.records_read += 1 return # parse() class LDIFRecordList(LDIFParser): """ Collect all records of LDIF input into a single list. of 2-tuples (dn, entry). It can be a memory hog! """ def __init__(self, input_file, ignored_attr_types=None, max_entries=0, process_url_schemes=None): """ See LDIFParser.__init__() Additional Parameters: all_records List instance for storing parsed records """ LDIFParser.__init__(self, input_file, ignored_attr_types, max_entries, process_url_schemes) self.all_records = [] def handle(self, dn, entry): """ Append single record to dictionary of all records. """ self.all_records.append((dn, entry)) class LDIFCopy(LDIFParser): """ Copy LDIF input to LDIF output containing all data retrieved via URLs """ def __init__(self, input_file, output_file, ignored_attr_types=None, max_entries=0, process_url_schemes=None, base64_attrs=None, cols=76, line_sep='\n'): """ See LDIFParser.__init__() and LDIFWriter.__init__() """ LDIFParser.__init__(self, input_file, ignored_attr_types, max_entries, process_url_schemes) self._output_ldif = LDIFWriter(output_file, base64_attrs, cols, line_sep) def handle(self, dn, entry): """ Write single LDIF record to output file. """ self._output_ldif.unparse(dn, entry) def ParseLDIF(f, ignore_attrs=None, maxentries=0): """ Parse LDIF records read from file. This is a compability function. Use is deprecated! """ ldif_parser = LDIFRecordList(f, ignored_attr_types=ignore_attrs, max_entries=maxentries, process_url_schemes=0) ldif_parser.parse() return ldif_parser.all_records