# Authors: # Rob Crittenden # Pavel Zuna # # Copyright (C) 2009 Red Hat # see file 'COPYING' for use and warranty information # # 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 . """ Directory Server Access Control Instructions (ACIs) ACIs are used to allow or deny access to information. This module is currently designed to allow, not deny, access. The aci commands are designed to grant permissions that allow updating existing entries or adding or deleting new ones. The goal of the ACIs that ship with IPA is to provide a set of low-level permissions that grant access to special groups called taskgroups. These low-level permissions can be combined into roles that grant broader access. These roles are another type of group, roles. For example, if you have taskgroups that allow adding and modifying users you could create a role, useradmin. You would assign users to the useradmin role to allow them to do the operations defined by the taskgroups. You can create ACIs that delegate permission so users in group A can write attributes on group B. The type option is a map that applies to all entries in the users, groups or host location. It is primarily designed to be used when granting add permissions (to write new entries). An ACI consists of three parts: 1. target 2. permissions 3. bind rules The target is a set of rules that define which LDAP objects are being targeted. This can include a list of attributes, an area of that LDAP tree or an LDAP filter. The targets include: - attrs: list of attributes affected - type: an object type (user, group, host, service, etc) - memberof: members of a group - targetgroup: grant access to modify a specific group. This is primarily designed to enable users to add or remove members of a specific group. - filter: A legal LDAP filter used to narrow the scope of the target. - subtree: Used to apply a rule across an entire set of objects. For example, to allow adding users you need to grant "add" permission to the subtree ldap://uid=*,cn=users,cn=accounts,dc=example,dc=com. The subtree option is a fail-safe for objects that may not be covered by the type option. The permissions define what the ACI is allowed to do, and are one or more of: 1. write - write one or more attributes 2. read - read one or more attributes 3. add - add a new entry to the tree 4. delete - delete an existing entry 5. all - all permissions are granted Note the distinction between attributes and entries. The permissions are independent, so being able to add a user does not mean that the user will be editable. The bind rule defines who this ACI grants permissions to. The LDAP server allows this to be any valid LDAP entry but we encourage the use of taskgroups so that the rights can be easily shared through roles. For a more thorough description of access controls see http://www.redhat.com/docs/manuals/dir-server/ag/8.0/Managing_Access_Control.html EXAMPLES: NOTE: ACIs are now added via the permission plugin. These examples are to demonstrate how the various options work but this is done via the permission command-line now (see last example). Add an ACI so that the group "secretaries" can update the address on any user: ipa group-add --desc="Office secretaries" secretaries ipa aci-add --attrs=streetAddress --memberof=ipausers --group=secretaries --permissions=write --prefix=none "Secretaries write addresses" Show the new ACI: ipa aci-show --prefix=none "Secretaries write addresses" Add an ACI that allows members of the "addusers" permission to add new users: ipa aci-add --type=user --permission=addusers --permissions=add --prefix=none "Add new users" Add an ACI that allows members of the editors manage members of the admins group: ipa aci-add --permissions=write --attrs=member --targetgroup=admins --group=editors --prefix=none "Editors manage admins" Add an ACI that allows members of the admins group to manage the street and zip code of those in the editors group: ipa aci-add --permissions=write --memberof=editors --group=admins --attrs=street,postalcode --prefix=none "admins edit the address of editors" Add an ACI that allows the admins group manage the street and zipcode of those who work for the boss: ipa aci-add --permissions=write --group=admins --attrs=street,postalcode --filter="(manager=uid=boss,cn=users,cn=accounts,dc=example,dc=com)" --prefix=none "Edit the address of those who work for the boss" Add an entirely new kind of record to IPA that isn't covered by any of the --type options, creating a permission: ipa permission-add --permissions=add --subtree="cn=*,cn=orange,cn=accounts,dc=example,dc=com" --desc="Add Orange Entries" add_orange The show command shows the raw 389-ds ACI. IMPORTANT: When modifying the target attributes of an existing ACI you must include all existing attributes as well. When doing an aci-mod the targetattr REPLACES the current attributes, it does not add to them. """ from copy import deepcopy from ipalib import api, crud, errors from ipalib import Object, Command from ipalib import Flag, Int, Str, StrEnum from ipalib.aci import ACI from ipalib.dn import DN from ipalib import output from ipalib import _, ngettext from ipalib.plugins.baseldap import gen_pkey_only_option if api.env.in_server and api.env.context in ['lite', 'server']: from ldap import explode_dn from ipapython.ipa_log_manager import * ACI_NAME_PREFIX_SEP = ":" _type_map = { 'user': 'ldap:///uid=*,%s,%s' % (api.env.container_user, api.env.basedn), 'group': 'ldap:///cn=*,%s,%s' % (api.env.container_group, api.env.basedn), 'host': 'ldap:///fqdn=*,%s,%s' % (api.env.container_host, api.env.basedn), 'hostgroup': 'ldap:///cn=*,%s,%s' % (api.env.container_hostgroup, api.env.basedn), 'service': 'ldap:///krbprincipalname=*,%s,%s' % (api.env.container_service, api.env.basedn), 'netgroup': 'ldap:///ipauniqueid=*,%s,%s' % (api.env.container_netgroup, api.env.basedn), 'dnsrecord': 'ldap:///idnsname=*,%s,%s' % (api.env.container_dns, api.env.basedn), } _valid_permissions_values = [ u'read', u'write', u'add', u'delete', u'all' ] _valid_prefix_values = ( u'permission', u'delegation', u'selfservice', u'none' ) class ListOfACI(output.Output): type = (list, tuple) doc = _('A list of ACI values') def validate(self, cmd, entries): assert isinstance(entries, self.type) for (i, entry) in enumerate(entries): if not isinstance(entry, unicode): raise TypeError(output.emsg % (cmd.name, self.__class__.__name__, self.name, i, unicode, type(entry), entry) ) aci_output = ( output.Output('result', unicode, 'A string representing the ACI'), output.value, output.summary, ) def _make_aci_name(aciprefix, aciname): """ Given a name and a prefix construct an ACI name. """ if aciprefix == u"none": return aciname return aciprefix + ACI_NAME_PREFIX_SEP + aciname def _parse_aci_name(aciname): """ Parse the raw ACI name and return a tuple containing the ACI prefix and the actual ACI name. """ aciparts = aciname.partition(ACI_NAME_PREFIX_SEP) if not aciparts[2]: # no prefix/name separator found return (u"none",aciparts[0]) return (aciparts[0], aciparts[2]) def _group_from_memberof(memberof): """ Pull the group name out of a memberOf filter """ st = memberof.find('memberOf=') if st == -1: # We have a raw group name, use that return api.Object['group'].get_dn(memberof) en = memberof.find(')', st) return memberof[st+9:en] def _make_aci(ldap, current, aciname, kw): """ Given a name and a set of keywords construct an ACI. """ # Do some quick and dirty validation. checked_args=['type','filter','subtree','targetgroup','attrs','memberof'] valid={} for arg in checked_args: if arg in kw: valid[arg]=kw[arg] is not None else: valid[arg]=False if valid['type'] + valid['filter'] + valid['subtree'] + valid['targetgroup'] > 1: raise errors.ValidationError(name='target', error=_('type, filter, subtree and targetgroup are mutually exclusive')) if 'aciprefix' not in kw: raise errors.ValidationError(name='aciprefix', error=_('ACI prefix is required')) if sum(valid.itervalues()) == 0: raise errors.ValidationError(name='target', error=_('at least one of: type, filter, subtree, targetgroup, attrs or memberof are required')) if valid['filter'] + valid['memberof'] > 1: raise errors.ValidationError(name='target', error=_('filter and memberof are mutually exclusive')) group = 'group' in kw permission = 'permission' in kw selfaci = 'selfaci' in kw and kw['selfaci'] == True if group + permission + selfaci > 1: raise errors.ValidationError(name='target', error=_('group, permission and self are mutually exclusive')) elif group + permission + selfaci == 0: raise errors.ValidationError(name='target', error=_('One of group, permission or self is required')) # Grab the dn of the group we're granting access to. This group may be a # permission or a user group. entry_attrs = [] if permission: # This will raise NotFound if the permission doesn't exist try: entry_attrs = api.Command['permission_show'](kw['permission'])['result'] except errors.NotFound, e: if 'test' in kw and not kw.get('test'): raise e else: entry_attrs = {'dn': 'cn=%s,%s' % (kw['permission'], api.env.container_permission)} elif group: # Not so friendly with groups. This will raise try: entry_attrs = api.Command['group_show'](kw['group'])['result'] except errors.NotFound: raise errors.NotFound(reason=_("Group '%s' does not exist") % kw['group']) try: a = ACI(current) a.name = _make_aci_name(kw['aciprefix'], aciname) a.permissions = kw['permissions'] if 'selfaci' in kw and kw['selfaci']: a.set_bindrule('userdn = "ldap:///self"') else: dn = entry_attrs['dn'] a.set_bindrule('groupdn = "ldap:///%s"' % dn) if valid['attrs']: a.set_target_attr(kw['attrs']) if valid['memberof']: try: api.Command['group_show'](kw['memberof']) except errors.NotFound: api.Object['group'].handle_not_found(kw['memberof']) groupdn = _group_from_memberof(kw['memberof']) a.set_target_filter('memberOf=%s' % groupdn) if valid['filter']: # Test the filter by performing a simple search on it. The # filter is considered valid if either it returns some entries # or it returns no entries, otherwise we let whatever exception # happened be raised. if kw['filter'] in ('', None, u''): raise errors.BadSearchFilter(info=_('empty filter')) try: entries = ldap.find_entries(filter=kw['filter']) except errors.NotFound: pass a.set_target_filter(kw['filter']) if valid['type']: target = _type_map[kw['type']] a.set_target(target) if valid['targetgroup']: # Purposely no try here so we'll raise a NotFound entry_attrs = api.Command['group_show'](kw['targetgroup'])['result'] target = 'ldap:///%s' % entry_attrs['dn'] a.set_target(target) if valid['subtree']: # See if the subtree is a full URI target = kw['subtree'] if not target.startswith('ldap:///'): target = 'ldap:///%s' % target a.set_target(target) except SyntaxError, e: raise errors.ValidationError(name='target', error=_('Syntax Error: %(error)s') % dict(error=str(e))) return a def _aci_to_kw(ldap, a, test=False, pkey_only=False): """Convert an ACI into its equivalent keywords. This is used for the modify operation so we can merge the incoming kw and existing ACI and pass the result to _make_aci(). """ kw = {} kw['aciprefix'], kw['aciname'] = _parse_aci_name(a.name) if pkey_only: return kw kw['permissions'] = tuple(a.permissions) if 'targetattr' in a.target: kw['attrs'] = list(a.target['targetattr']['expression']) for i in xrange(len(kw['attrs'])): kw['attrs'][i] = unicode(kw['attrs'][i]) kw['attrs'] = tuple(kw['attrs']) if 'targetfilter' in a.target: target = a.target['targetfilter']['expression'] if target.startswith('(memberOf=') or target.startswith('memberOf='): (junk, memberof) = target.split('memberOf=', 1) memberof = DN(memberof) kw['memberof'] = memberof['cn'] else: kw['filter'] = unicode(target) if 'target' in a.target: target = a.target['target']['expression'] found = False for k in _type_map.keys(): if _type_map[k] == target: kw['type'] = unicode(k) found = True break; if not found: if target.startswith('('): kw['filter'] = unicode(target) else: # See if the target is a group. If so we set the # targetgroup attr, otherwise we consider it a subtree if api.env.container_group in target: targetdn = unicode(target.replace('ldap:///','')) target = DN(targetdn) kw['targetgroup'] = target['cn'] else: kw['subtree'] = unicode(target) groupdn = a.bindrule['expression'] groupdn = groupdn.replace('ldap:///','') if groupdn == 'self': kw['selfaci'] = True elif groupdn == 'anyone': pass else: if groupdn.startswith('cn='): dn = '' entry_attrs = {} try: (dn, entry_attrs) = ldap.get_entry(groupdn, ['cn']) except errors.NotFound, e: # FIXME, use real name here if test: dn = 'cn=%s,%s' % ('test', api.env.container_permission) entry_attrs = {'cn': [u'test']} if api.env.container_permission in dn: kw['permission'] = entry_attrs['cn'][0] else: if 'cn' in entry_attrs: kw['group'] = entry_attrs['cn'][0] return kw def _convert_strings_to_acis(acistrs): acis = [] for a in acistrs: try: acis.append(ACI(a)) except SyntaxError, e: root_logger.warning("Failed to parse: %s" % a) return acis def _find_aci_by_name(acis, aciprefix, aciname): name = _make_aci_name(aciprefix, aciname).lower() for a in acis: if a.name.lower() == name: return a raise errors.NotFound(reason=_('ACI with name "%s" not found') % aciname) def validate_permissions(ugettext, permissions): valid_permissions = [] permissions = permissions.split(',') for p in permissions: p = p.strip().lower() if not p in _valid_permissions_values: return '"%s" is not a valid permission' % p def _normalize_permissions(permissions): valid_permissions = [] permissions = permissions.split(',') for p in permissions: p = p.strip().lower() if p not in valid_permissions: valid_permissions.append(p) return ','.join(valid_permissions) _prefix_option = StrEnum('aciprefix', cli_name='prefix', label=_('ACI prefix'), doc=_('Prefix used to distinguish ACI types ' \ '(permission, delegation, selfservice, none)'), values=_valid_prefix_values, ) class aci(Object): """ ACI object. """ NO_CLI = True label = _('ACIs') takes_params = ( Str('aciname', cli_name='name', label=_('ACI name'), primary_key=True, flags=('virtual_attribute',), ), Str('permission?', cli_name='permission', label=_('Permission'), doc=_('Permission ACI grants access to'), flags=('virtual_attribute',), ), Str('group?', cli_name='group', label=_('User group'), doc=_('User group ACI grants access to'), flags=('virtual_attribute',), ), Str('permissions+', validate_permissions, cli_name='permissions', label=_('Permissions'), doc=_('comma-separated list of permissions to grant' \ '(read, write, add, delete, all)'), csv=True, normalizer=_normalize_permissions, flags=('virtual_attribute',), ), Str('attrs*', cli_name='attrs', label=_('Attributes'), doc=_('Comma-separated list of attributes'), csv=True, flags=('virtual_attribute',), ), StrEnum('type?', cli_name='type', label=_('Type'), doc=_('type of IPA object (user, group, host, hostgroup, service, netgroup)'), values=(u'user', u'group', u'host', u'service', u'hostgroup', u'netgroup', u'dnsrecord'), flags=('virtual_attribute',), ), Str('memberof?', cli_name='memberof', label=_('Member of'), # FIXME: Does this label make sense? doc=_('Member of a group'), flags=('virtual_attribute',), ), Str('filter?', cli_name='filter', label=_('Filter'), doc=_('Legal LDAP filter (e.g. ou=Engineering)'), flags=('virtual_attribute',), ), Str('subtree?', cli_name='subtree', label=_('Subtree'), doc=_('Subtree to apply ACI to'), flags=('virtual_attribute',), ), Str('targetgroup?', cli_name='targetgroup', label=_('Target group'), doc=_('Group to apply ACI to'), flags=('virtual_attribute',), ), Flag('selfaci?', cli_name='self', label=_('Target your own entry (self)'), doc=_('Apply ACI to your own entry (self)'), flags=('virtual_attribute',), ), ) api.register(aci) class aci_add(crud.Create): """ Create new ACI. """ NO_CLI = True msg_summary = _('Created ACI "%(value)s"') takes_options = ( _prefix_option, Flag('test?', doc=_('Test the ACI syntax but don\'t write anything'), default=False, ), ) def execute(self, aciname, **kw): """ Execute the aci-create operation. Returns the entry as it will be created in LDAP. :param aciname: The name of the ACI being added. :param kw: Keyword arguments for the other LDAP attributes. """ assert 'aciname' not in kw ldap = self.api.Backend.ldap2 newaci = _make_aci(ldap, None, aciname, kw) (dn, entry_attrs) = ldap.get_entry(self.api.env.basedn, ['aci']) acis = _convert_strings_to_acis(entry_attrs.get('aci', [])) for a in acis: # FIXME: add check for permission_group = permission_group if a.isequal(newaci) or newaci.name == a.name: raise errors.DuplicateEntry() newaci_str = unicode(newaci) entry_attrs['aci'].append(newaci_str) if not kw.get('test', False): ldap.update_entry(dn, entry_attrs) if kw.get('raw', False): result = dict(aci=unicode(newaci_str)) else: result = _aci_to_kw(ldap, newaci, kw.get('test', False)) return dict( result=result, value=aciname, ) api.register(aci_add) class aci_del(crud.Delete): """ Delete ACI. """ NO_CLI = True has_output = output.standard_boolean msg_summary = _('Deleted ACI "%(value)s"') takes_options = (_prefix_option,) def execute(self, aciname, **kw): """ Execute the aci-delete operation. :param aciname: The name of the ACI being deleted. :param kw: unused """ assert 'aciname' not in kw ldap = self.api.Backend.ldap2 (dn, entry_attrs) = ldap.get_entry(self.api.env.basedn, ['aci']) acistrs = entry_attrs.get('aci', []) acis = _convert_strings_to_acis(acistrs) aci = _find_aci_by_name(acis, kw['aciprefix'], aciname) for a in acistrs: candidate = ACI(a) if aci.isequal(candidate): acistrs.remove(a) break entry_attrs['aci'] = acistrs ldap.update_entry(dn, entry_attrs) return dict( result=True, value=aciname, ) api.register(aci_del) class aci_mod(crud.Update): """ Modify ACI. """ NO_CLI = True has_output_params = ( Str('aci', label=_('ACI'), ), ) takes_options = (_prefix_option,) msg_summary = _('Modified ACI "%(value)s"') def execute(self, aciname, **kw): ldap = self.api.Backend.ldap2 (dn, entry_attrs) = ldap.get_entry(self.api.env.basedn, ['aci']) acis = _convert_strings_to_acis(entry_attrs.get('aci', [])) aci = _find_aci_by_name(acis, kw['aciprefix'], aciname) # The strategy here is to convert the ACI we're updating back into # a series of keywords. Then we replace any keywords that have been # updated and convert that back into an ACI and write it out. oldkw = _aci_to_kw(ldap, aci) newkw = deepcopy(oldkw) if 'selfaci' in newkw and newkw['selfaci'] == True: # selfaci is set in aci_to_kw to True only if the target is self kw['selfaci'] = True for k in kw.keys(): newkw[k] = kw[k] for acikw in (oldkw, newkw): try: del acikw['aciname'] except KeyError: pass # _make_aci is what is run in aci_add and validates the input. # Do this before we delete the existing ACI. newaci = _make_aci(ldap, None, aciname, newkw) if aci.isequal(newaci): raise errors.EmptyModlist() self.api.Command['aci_del'](aciname, **kw) try: result = self.api.Command['aci_add'](aciname, **newkw)['result'] except Exception, e: # ACI could not be added, try to restore the old deleted ACI and # report the ADD error back to user try: self.api.Command['aci_add'](aciname, **oldkw) except: pass raise e if kw.get('raw', False): result = dict(aci=unicode(newaci)) else: result = _aci_to_kw(ldap, newaci) return dict( result=result, value=aciname, ) api.register(aci_mod) class aci_find(crud.Search): """ Search for ACIs. Returns a list of ACIs EXAMPLES: To find all ACIs that apply directly to members of the group ipausers: ipa aci-find --memberof=ipausers To find all ACIs that grant add access: ipa aci-find --permissions=add Note that the find command only looks for the given text in the set of ACIs, it does not evaluate the ACIs to see if something would apply. For example, searching on memberof=ipausers will find all ACIs that have ipausers as a memberof. There may be other ACIs that apply to members of that group indirectly. """ NO_CLI = True msg_summary = ngettext('%(count)d ACI matched', '%(count)d ACIs matched', 0) takes_options = (_prefix_option.clone_rename("aciprefix?", required=False), gen_pkey_only_option("name"),) def execute(self, term, **kw): ldap = self.api.Backend.ldap2 (dn, entry_attrs) = ldap.get_entry(self.api.env.basedn, ['aci']) acis = _convert_strings_to_acis(entry_attrs.get('aci', [])) results = [] if term: term = term.lower() for a in acis: if a.name.lower().find(term) != -1 and a not in results: results.append(a) acis = list(results) else: results = list(acis) if kw.get('aciname'): for a in acis: prefix, name = _parse_aci_name(a.name) if name != kw['aciname']: results.remove(a) acis = list(results) if kw.get('aciprefix'): for a in acis: prefix, name = _parse_aci_name(a.name) if prefix != kw['aciprefix']: results.remove(a) acis = list(results) if kw.get('attrs'): for a in acis: if not 'targetattr' in a.target: results.remove(a) continue alist1 = sorted( [t.lower() for t in a.target['targetattr']['expression']] ) alist2 = sorted([t.lower() for t in kw['attrs']]) if len(set(alist1) & set(alist2)) != len(alist2): results.remove(a) acis = list(results) if kw.get('permission'): try: self.api.Command['permission_show']( kw['permission'] ) except errors.NotFound: pass else: for a in acis: if a.bindrule['expression'] != ('ldap:///%s' % dn): results.remove(a) acis = list(results) if kw.get('permissions'): for a in acis: alist1 = sorted(a.permissions) alist2 = sorted(kw['permissions']) if len(set(alist1) & set(alist2)) != len(alist2): results.remove(a) acis = list(results) if kw.get('memberof'): try: dn = _group_from_memberof(kw['memberof']) except errors.NotFound: pass else: memberof_filter = '(memberOf=%s)' % dn for a in acis: if 'targetfilter' in a.target: targetfilter = a.target['targetfilter']['expression'] if targetfilter != memberof_filter: results.remove(a) else: results.remove(a) if kw.get('type'): for a in acis: if 'target' in a.target: target = a.target['target']['expression'] else: results.remove(a) continue found = False for k in _type_map.keys(): if _type_map[k] == target and kw['type'] == k: found = True break; if not found: try: results.remove(a) except ValueError: pass if kw.get('selfaci', False) is True: for a in acis: if a.bindrule['expression'] != u'ldap:///self': try: results.remove(a) except ValueError: pass if kw.get('group'): for a in acis: groupdn = a.bindrule['expression'] groupdn = groupdn.replace('ldap:///','') cn = None if groupdn.startswith('cn='): cn = explode_dn(groupdn)[0] cn = cn.replace('cn=','') if cn is None or cn != kw['group']: try: results.remove(a) except ValueError: pass if kw.get('targetgroup'): for a in acis: found = False if 'target' in a.target: target = a.target['target']['expression'] if api.env.container_group in target: targetdn = unicode(target.replace('ldap:///','')) cn = explode_dn(targetdn)[0] cn = cn.replace('cn=','') if cn == kw['targetgroup']: found = True if not found: try: results.remove(a) except ValueError: pass if kw.get('filter'): if not kw['filter'].startswith('('): kw['filter'] = unicode('('+kw['filter']+')') for a in acis: if 'targetfilter' not in a.target or\ not a.target['targetfilter']['expression'] or\ a.target['targetfilter']['expression'] != kw['filter']: results.remove(a) # TODO: searching by: subtree acis = [] for result in results: if kw.get('raw', False): aci = dict(aci=unicode(result)) else: aci = _aci_to_kw(ldap, result, pkey_only=kw.get('pkey_only', False)) acis.append(aci) return dict( result=acis, count=len(acis), truncated=False, ) api.register(aci_find) class aci_show(crud.Retrieve): """ Display a single ACI given an ACI name. """ NO_CLI = True has_output_params = ( Str('aci', label=_('ACI'), ), ) takes_options = (_prefix_option,) def execute(self, aciname, **kw): """ Execute the aci-show operation. Returns the entry :param uid: The login name of the user to retrieve. :param kw: unused """ ldap = self.api.Backend.ldap2 (dn, entry_attrs) = ldap.get_entry(self.api.env.basedn, ['aci']) acis = _convert_strings_to_acis(entry_attrs.get('aci', [])) aci = _find_aci_by_name(acis, kw['aciprefix'], aciname) if kw.get('raw', False): result = dict(aci=unicode(aci)) else: result = _aci_to_kw(ldap, aci) return dict( result=result, value=aciname, ) api.register(aci_show) class aci_rename(crud.Update): """ Rename an ACI. """ NO_CLI = True has_output_params = ( Str('aci', label=_('ACI'), ), ) takes_options = ( _prefix_option, Str('newname', doc=_('New ACI name'), ), ) msg_summary = _('Renamed ACI to "%(value)s"') def execute(self, aciname, **kw): ldap = self.api.Backend.ldap2 (dn, entry_attrs) = ldap.get_entry(self.api.env.basedn, ['aci']) acis = _convert_strings_to_acis(entry_attrs.get('aci', [])) aci = _find_aci_by_name(acis, kw['aciprefix'], aciname) for a in acis: prefix, name = _parse_aci_name(a.name) if _make_aci_name(prefix, kw['newname']) == a.name: raise errors.DuplicateEntry() # The strategy here is to convert the ACI we're updating back into # a series of keywords. Then we replace any keywords that have been # updated and convert that back into an ACI and write it out. newkw = _aci_to_kw(ldap, aci) if 'selfaci' in newkw and newkw['selfaci'] == True: # selfaci is set in aci_to_kw to True only if the target is self kw['selfaci'] = True if 'aciname' in newkw: del newkw['aciname'] # _make_aci is what is run in aci_add and validates the input. # Do this before we delete the existing ACI. newaci = _make_aci(ldap, None, kw['newname'], newkw) self.api.Command['aci_del'](aciname, **kw) result = self.api.Command['aci_add'](kw['newname'], **newkw)['result'] if kw.get('raw', False): result = dict(aci=unicode(newaci)) else: result = _aci_to_kw(ldap, newaci) return dict( result=result, value=kw['newname'], ) api.register(aci_rename) /a> 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
/*
	Written 1997-1998 by Donald Becker.

	This software may be used and distributed according to the terms
	of the GNU General Public License, incorporated herein by reference.

	This driver is for the 3Com ISA EtherLink XL "Corkscrew" 3c515 ethercard.

	The author may be reached as becker@scyld.com, or C/O
	Scyld Computing Corporation
	410 Severn Ave., Suite 210
	Annapolis MD 21403


	2000/2/2- Added support for kernel-level ISAPnP
		by Stephen Frost <sfrost@snowman.net> and Alessandro Zummo
	Cleaned up for 2.3.x/softnet by Jeff Garzik and Alan Cox.

	2001/11/17 - Added ethtool support (jgarzik)

	2002/10/28 - Locking updates for 2.5 (alan@lxorguk.ukuu.org.uk)

*/

#define DRV_NAME		"3c515"
#define DRV_VERSION		"0.99t-ac"
#define DRV_RELDATE		"28-Oct-2002"

static char *version =
DRV_NAME ".c:v" DRV_VERSION " " DRV_RELDATE " becker@scyld.com and others\n";

#define CORKSCREW 1

/* "Knobs" that adjust features and parameters. */
/* Set the copy breakpoint for the copy-only-tiny-frames scheme.
   Setting to > 1512 effectively disables this feature. */
static int rx_copybreak = 200;

/* Allow setting MTU to a larger size, bypassing the normal ethernet setup. */
static const int mtu = 1500;

/* Maximum events (Rx packets, etc.) to handle at each interrupt. */
static int max_interrupt_work = 20;

/* Enable the automatic media selection code -- usually set. */
#define AUTOMEDIA 1

/* Allow the use of fragment bus master transfers instead of only
   programmed-I/O for Vortex cards.  Full-bus-master transfers are always
   enabled by default on Boomerang cards.  If VORTEX_BUS_MASTER is defined,
   the feature may be turned on using 'options'. */
#define VORTEX_BUS_MASTER

/* A few values that may be tweaked. */
/* Keep the ring sizes a power of two for efficiency. */
#define TX_RING_SIZE	16
#define RX_RING_SIZE	16
#define PKT_BUF_SZ		1536	/* Size of each temporary Rx buffer. */

#include <linux/module.h>
#include <linux/isapnp.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/in.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/etherdevice.h>
#include <linux/interrupt.h>
#include <linux/timer.h>
#include <linux/ethtool.h>
#include <linux/bitops.h>

#include <asm/uaccess.h>
#include <asm/io.h>
#include <asm/dma.h>

#define NEW_MULTICAST
#include <linux/delay.h>

#define MAX_UNITS 8

MODULE_AUTHOR("Donald Becker <becker@scyld.com>");
MODULE_DESCRIPTION("3Com 3c515 Corkscrew driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);

/* "Knobs" for adjusting internal parameters. */
/* Put out somewhat more debugging messages. (0 - no msg, 1 minimal msgs). */
#define DRIVER_DEBUG 1
/* Some values here only for performance evaluation and path-coverage
   debugging. */
static int rx_nocopy, rx_copy, queued_packet;

/* Number of times to check to see if the Tx FIFO has space, used in some
   limited cases. */
#define WAIT_TX_AVAIL 200

/* Operational parameter that usually are not changed. */
#define TX_TIMEOUT  40		/* Time in jiffies before concluding Tx hung */

/* The size here is somewhat misleading: the Corkscrew also uses the ISA
   aliased registers at <base>+0x400.
   */
#define CORKSCREW_TOTAL_SIZE 0x20

#ifdef DRIVER_DEBUG
static int corkscrew_debug = DRIVER_DEBUG;
#else
static int corkscrew_debug = 1;
#endif

#define CORKSCREW_ID 10

/*
				Theory of Operation

I. Board Compatibility

This device driver is designed for the 3Com 3c515 ISA Fast EtherLink XL,
3Com's ISA bus adapter for Fast Ethernet.  Due to the unique I/O port layout,
it's not practical to integrate this driver with the other EtherLink drivers.

II. Board-specific settings

The Corkscrew has an EEPROM for configuration, but no special settings are
needed for Linux.

III. Driver operation

The 3c515 series use an interface that's very similar to the 3c900 "Boomerang"
PCI cards, with the bus master interface extensively modified to work with
the ISA bus.

The card is capable of full-bus-master transfers with separate
lists of transmit and receive descriptors, similar to the AMD LANCE/PCnet,
DEC Tulip and Intel Speedo3.

This driver uses a "RX_COPYBREAK" scheme rather than a fixed intermediate
receive buffer.  This scheme allocates full-sized skbuffs as receive
buffers.  The value RX_COPYBREAK is used as the copying breakpoint: it is
chosen to trade-off the memory wasted by passing the full-sized skbuff to
the queue layer for all frames vs. the copying cost of copying a frame to a
correctly-sized skbuff.


IIIC. Synchronization
The driver runs as two independent, single-threaded flows of control.  One
is the send-packet routine, which enforces single-threaded use by the netif
layer.  The other thread is the interrupt handler, which is single
threaded by the hardware and other software.

IV. Notes

Thanks to Terry Murphy of 3Com for providing documentation and a development
board.

The names "Vortex", "Boomerang" and "Corkscrew" are the internal 3Com
project names.  I use these names to eliminate confusion -- 3Com product
numbers and names are very similar and often confused.

The new chips support both ethernet (1.5K) and FDDI (4.5K) frame sizes!
This driver only supports ethernet frames because of the recent MTU limit
of 1.5K, but the changes to support 4.5K are minimal.
*/

/* Operational definitions.
   These are not used by other compilation units and thus are not
   exported in a ".h" file.

   First the windows.  There are eight register windows, with the command
   and status registers available in each.
   */
#define EL3WINDOW(win_num) outw(SelectWindow + (win_num), ioaddr + EL3_CMD)
#define EL3_CMD 0x0e
#define EL3_STATUS 0x0e

/* The top five bits written to EL3_CMD are a command, the lower
   11 bits are the parameter, if applicable.
   Note that 11 parameters bits was fine for ethernet, but the new chips
   can handle FDDI length frames (~4500 octets) and now parameters count
   32-bit 'Dwords' rather than octets. */

enum corkscrew_cmd {
	TotalReset = 0 << 11, SelectWindow = 1 << 11, StartCoax = 2 << 11,
	RxDisable = 3 << 11, RxEnable = 4 << 11, RxReset = 5 << 11,
	UpStall = 6 << 11, UpUnstall = (6 << 11) + 1, DownStall = (6 << 11) + 2,
	DownUnstall = (6 << 11) + 3, RxDiscard = 8 << 11, TxEnable = 9 << 11,
	TxDisable = 10 << 11, TxReset = 11 << 11, FakeIntr = 12 << 11,
	AckIntr = 13 << 11, SetIntrEnb = 14 << 11, SetStatusEnb = 15 << 11,
	SetRxFilter = 16 << 11, SetRxThreshold = 17 << 11,
	SetTxThreshold = 18 << 11, SetTxStart = 19 << 11, StartDMAUp = 20 << 11,
	StartDMADown = (20 << 11) + 1, StatsEnable = 21 << 11,
	StatsDisable = 22 << 11, StopCoax = 23 << 11,
};

/* The SetRxFilter command accepts the following classes: */
enum RxFilter {
	RxStation = 1, RxMulticast = 2, RxBroadcast = 4, RxProm = 8
};

/* Bits in the general status register. */
enum corkscrew_status {
	IntLatch = 0x0001, AdapterFailure = 0x0002, TxComplete = 0x0004,
	TxAvailable = 0x0008, RxComplete = 0x0010, RxEarly = 0x0020,
	IntReq = 0x0040, StatsFull = 0x0080,
	DMADone = 1 << 8, DownComplete = 1 << 9, UpComplete = 1 << 10,
	DMAInProgress = 1 << 11,	/* DMA controller is still busy. */
	CmdInProgress = 1 << 12,	/* EL3_CMD is still busy. */
};

/* Register window 1 offsets, the window used in normal operation.
   On the Corkscrew this window is always mapped at offsets 0x10-0x1f. */
enum Window1 {
	TX_FIFO = 0x10, RX_FIFO = 0x10, RxErrors = 0x14,
	RxStatus = 0x18, Timer = 0x1A, TxStatus = 0x1B,
	TxFree = 0x1C,		/* Remaining free bytes in Tx buffer. */
};
enum Window0 {
	Wn0IRQ = 0x08,
#if defined(CORKSCREW)
	Wn0EepromCmd = 0x200A,	/* Corkscrew EEPROM command register. */
	Wn0EepromData = 0x200C,	/* Corkscrew EEPROM results register. */
#else
	Wn0EepromCmd = 10,	/* Window 0: EEPROM command register. */
	Wn0EepromData = 12,	/* Window 0: EEPROM results register. */
#endif
};
enum Win0_EEPROM_bits {
	EEPROM_Read = 0x80, EEPROM_WRITE = 0x40, EEPROM_ERASE = 0xC0,
	EEPROM_EWENB = 0x30,	/* Enable erasing/writing for 10 msec. */
	EEPROM_EWDIS = 0x00,	/* Disable EWENB before 10 msec timeout. */
};

/* EEPROM locations. */
enum eeprom_offset {