예제 #1
0
class BaseMetaObject(Object):
    takes_params = (
        Str(
            'name',
            label=_("Name"),
            normalizer=lambda name: name.replace(u'-', u'_'),
            flags={'no_search'},
        ),
        Str(
            'doc?',
            label=_("Documentation"),
            flags={'no_search'},
        ),
        Str(
            'exclude*',
            label=_("Exclude from"),
            flags={'no_search'},
        ),
        Str(
            'include*',
            label=_("Include in"),
            flags={'no_search'},
        ),
    )

    def _get_obj(self, obj, **kwargs):
        raise NotImplementedError()

    def _retrieve(self, *args, **kwargs):
        raise NotImplementedError()

    def retrieve(self, *args, **kwargs):
        obj = self._retrieve(*args, **kwargs)
        obj = self._get_obj(obj, **kwargs)
        return obj

    def _search(self, *args, **kwargs):
        raise NotImplementedError()

    def _split_search_args(self, criteria=None):
        return [], criteria

    def search(self, *args, **kwargs):
        args, criteria = self._split_search_args(*args)

        result = self._search(*args, **kwargs)
        result = (self._get_obj(r, **kwargs) for r in result)

        if criteria:
            criteria = criteria.lower()
            result = (r for r in result
                      if (criteria in r['name'].lower()
                          or criteria in r.get('doc', u'').lower()))

        if not kwargs.get('all', False) and kwargs.get('pkey_only', False):
            key = self.primary_key.name
            result = ({key: r[key]} for r in result)

        return result
예제 #2
0
        class my_cmd(self.cls):
            takes_options = (
                Str('option0'),
                Str('option1', default_from=lambda option0: option0),
                Str('option2', default_from=lambda option1: option1),
            )

            def run(self, *args, **options):
                return dict(result=options)
예제 #3
0
class dnsrecord_split_parts(Command):
    __doc__ = _('Split DNS record to parts')
    NO_CLI = True

    takes_args = (
        Str('name'),
        Str('value'),
    )

    def execute(self, name, value, *args, **options):
        def split_exactly(count):
            values = value.split()
            if len(values) != count:
                return None
            return tuple(values)

        result = ()

        rrtype = get_record_rrtype(name)
        if rrtype in ('A', 'AAAA', 'CNAME', 'DNAME', 'NS', 'PTR'):
            result = split_exactly(1)
        elif rrtype in ('AFSDB', 'KX', 'MX'):
            result = split_exactly(2)
        elif rrtype in ('CERT', 'DLV', 'DS', 'SRV', 'TLSA'):
            result = split_exactly(4)
        elif rrtype in ('NAPTR'):
            result = split_exactly(6)
        elif rrtype in ('A6', 'TXT'):
            result = (value,)
        elif rrtype == 'LOC':
            regex = re.compile(
                r'(?P<d1>\d{1,2}\s+)'
                r'(?:(?P<m1>\d{1,2}\s+)'
                r'(?P<s1>\d{1,2}(?:\.\d{1,3})?\s+)?)?'
                r'(?P<dir1>[NS])\s+'
                r'(?P<d2>\d{1,3}\s+)'
                r'(?:(?P<m2>\d{1,2}\s+)'
                r'(?P<s2>\d{1,2}(?:\.\d{1,3})?\s+)?)?'
                r'(?P<dir2>[WE])\s+'
                r'(?P<alt>-?\d{1,8}(?:\.\d{1,2})?)m?'
                r'(?:\s+(?P<siz>\d{1,8}(?:\.\d{1,2})?)m?'
                r'(?:\s+(?P<hp>\d{1,8}(?:\.\d{1,2})?)m?'
                r'(?:\s+(?P<vp>\d{1,8}(?:\.\d{1,2})?)m?\s*)?)?)?$')

            m = regex.match(value)
            if m is not None:
                result = tuple(
                    x.strip() if x is not None else x for x in m.groups())
        elif rrtype == 'SSHFP':
            values = value.split(None, 2)
            if len(values) == 3:
                result = tuple(values)

        return dict(result=result)
예제 #4
0
class CertRetrieveOverride(MethodOverride):
    takes_options = (Str(
        'certificate_out?',
        doc=_('Write certificate (chain if --chain used) to file'),
        include='cli',
        cli_metavar='FILE',
    ), )

    def forward(self, *args, **options):
        certificate_out = options.pop('certificate_out', None)
        if certificate_out is not None:
            util.check_writable_file(certificate_out)

        result = super(CertRetrieveOverride, self).forward(*args, **options)

        if certificate_out is not None:
            if options.get('chain', False):
                certs = result['result']['certificate_chain']
            else:
                certs = [result['result']['certificate']]
            certs = (x509.normalize_certificate(cert) for cert in certs)
            certs = (x509.make_pem(base64.b64encode(cert)) for cert in certs)
            with open(certificate_out, 'w') as f:
                f.write('\n'.join(certs))

        return result
예제 #5
0
파일: cli.py 프로젝트: vikas-lamba/freeipa
class show_mappings(frontend.Command):
    """
    Show mapping of LDAP attributes to command-line option.
    """
    takes_args = (
        Str('command_name',
            label=_('Command name'),
        ),
    )
    has_output = tuple()

    topic = None

    def run(self, command_name, **options):
        command_name = from_cli(command_name)
        if command_name not in self.Command:
            raise CommandError(name=command_name)
        params = self.Command[command_name].options
        out = [('Parameter','LDAP attribute'),
               ('=========','==============')]
        mcl = len(out[0][0])
        for param in params():
            if param.exclude and 'webui' in param.exclude:
                continue
            out.append((param.cli_name, param.param_spec))
            mcl = max(mcl,len(param.cli_name))
        for item in out:
            print(to_cli(item[0]).ljust(mcl)+' : '+item[1])
예제 #6
0
class BaseParam(BaseMetaObject):
    takes_params = BaseMetaObject.takes_params + (
        Str(
            'type?',
            label=_("Type"),
            flags={'no_search'},
        ),
        Bool(
            'required?',
            label=_("Required"),
            flags={'no_search'},
        ),
        Bool(
            'multivalue?',
            label=_("Multi-value"),
            flags={'no_search'},
        ),
    )

    def get_params(self):
        for param in super(BaseParam, self).get_params():
            if param.name == 'name':
                param = param.clone(primary_key=True)
            yield param

    @property
    def parent(self):
        raise AttributeError('parent')

    def _split_search_args(self, parent_name, criteria=None):
        return [parent_name], criteria
예제 #7
0
class subid_generate(LDAPQuery):
    __doc__ = _(
        "Generate and auto-assign subuid and subgid range to user entry")

    has_output = output.standard_entry

    takes_options = LDAPQuery.takes_options + (Str(
        "ipaowner?",
        cli_name="owner",
        label=_("Owner"),
        doc=_("Owning user of subordinate id entry"),
    ), )

    def get_args(self):
        return []

    def execute(self, *keys, **options):
        owner_uid = options.get("ipaowner")
        # default to current user
        if owner_uid is None:
            owner_dn = DN(self.api.Backend.ldap2.conn.whoami_s()[4:])
            # validate it's a user and not a service or host
            owner_dn = self.obj.get_owner_dn(owner_dn)
            owner_uid = owner_dn[0].value

        return self.api.Command.subid_add(
            description="auto-assigned subid",
            ipaowner=owner_uid,
            version=options["version"],
        )
예제 #8
0
class CertRetrieveOverride(MethodOverride):
    takes_options = (Str(
        'certificate_out?',
        doc=_('Write certificate (chain if --chain used) to file'),
        include='cli',
        cli_metavar='FILE',
    ), )

    def forward(self, *args, **options):
        if 'certificate_out' in options:
            certificate_out = options.pop('certificate_out')
            try:
                util.check_writable_file(certificate_out)
            except errors.FileError as e:
                raise errors.ValidationError(name='certificate-out',
                                             error=str(e))
        else:
            certificate_out = None

        result = super(CertRetrieveOverride, self).forward(*args, **options)

        if certificate_out is not None:
            if options.get('chain', False):
                certs = result['result']['certificate_chain']
            else:
                certs = [base64.b64decode(result['result']['certificate'])]
            certs = (x509.load_der_x509_certificate(cert) for cert in certs)
            x509.write_certificate_list(certs, certificate_out)

        return result
예제 #9
0
    def get_params(self):
        for param in super(MetaObject, self).get_params():
            yield param

            if param.name == 'name':
                yield Str(
                    'version',
                    label=_("Version"),
                    flags={'no_search'},
                )
                yield Str(
                    'full_name',
                    label=_("Full name"),
                    primary_key=True,
                    normalizer=lambda name: name.replace(u'-', u'_'),
                    flags={'no_search'},
                )
예제 #10
0
class server_role(Object):
    """
    association between certain role (e.g. DNS server) and its status with
    an IPA master
    """
    backend_name = 'serverroles'
    object_name = _('server role')
    object_name_plural = _('server roles')
    default_attributes = [
        'role', 'status'
    ]
    label = _('IPA Server Roles')
    label_singular = _('IPA Server Role')

    takes_params = (
        Str(
            'server_server',
            cli_name='server',
            label=_('Server name'),
            doc=_('IPA server hostname'),
        ),
        Str(
            'role_servrole',
            cli_name='role',
            label=_("Role name"),
            doc=_("IPA server role name"),
            flags={u'virtual_attribute'}
        ),
        StrEnum(
            'status?',
            cli_name='status',
            label=_('Role status'),
            doc=_('Status of the role'),
            values=(u'enabled', u'configured', u'absent'),
            default=u'enabled',
            flags={'virtual_attribute', 'no_create', 'no_update'}
        )
    )

    def ensure_master_exists(self, fqdn):
        server_obj = self.api.Object.server
        try:
            server_obj.get_dn_if_exists(fqdn)
        except NotFound:
            server_obj.handle_not_found(fqdn)
예제 #11
0
class cert_remove_hold(MethodOverride):
    has_output_params = (
        Flag('unrevoked',
            label=_('Unrevoked'),
        ),
        Str('error_string',
            label=_('Error'),
        ),
    )
예제 #12
0
 class example(self.cls):
     has_output_params = (
         'one',
         'two',
         'three',
     )
     takes_args = ('foo', )
     takes_options = (
         Str('bar', flags='no_output'),
         'baz',
     )
예제 #13
0
class servrole(Object):
    """
    Server role object
    """
    object_name = _('role')
    object_name_plural = _('roles')
    takes_params = (Str('name',
                        primary_key=True,
                        label=_("Role name"),
                        doc=_("IPA role name"),
                        flags=(u'virtual_attribute', )))
예제 #14
0
 def test_get_options(self):
     """
     Test the `ipalib.crud.Create.get_options` method.
     """
     api = self.get_api()
     assert list(api.Method.user_verb.options) == \
         ['givenname', 'sn', 'initials', 'all', 'raw', 'version']
     for param in api.Method.user_verb.options():
         if param.name != 'version':
             assert param.required is True
     api = self.get_api(options=(Str('extra?'), ))
     assert list(api.Method.user_verb.options) == \
         ['givenname', 'sn', 'initials', 'extra', 'all', 'raw', 'version']
     assert api.Method.user_verb.options.extra.required is False
예제 #15
0
class certmap(Object):
    """
    virtual object for certmatch_map API
    """
    takes_params = (
        DNSNameParam(
            'domain',
            label=_('Domain'),
            flags={'no_search'},
        ),
        Str(
            'uid*',
            label=_('User logins'),
            flags={'no_search'},
        ),
    )
예제 #16
0
class command_defaults(PKQuery):
    NO_CLI = True

    takes_options = (
        Str('params*'),
        Dict('kw?'),
    )

    def execute(self, name, **options):
        command = self.api.Command[name]

        params = options.get('params') or []
        kw = options.get('kw') or {}

        result = command.get_default(params, **kw)

        return dict(result=result)
예제 #17
0
파일: pkinit.py 프로젝트: wanglu119/freeipa
class pkinit(Object):
    """
    PKINIT Options
    """
    object_name = _('pkinit')

    label = _('PKINIT')

    takes_params = (Str(
        'server_server?',
        cli_name='server',
        label=_('Server name'),
        doc=_('IPA server hostname'),
    ),
                    StrEnum(
                        'status?',
                        cli_name='status',
                        label=_('PKINIT status'),
                        doc=_('Whether PKINIT is enabled or disabled'),
                        values=(u'enabled', u'disabled'),
                        flags={'virtual_attribute', 'no_create', 'no_update'}))
예제 #18
0
class metaobject(MetaObject):
    takes_params = MetaObject.takes_params + (Str(
        'params_param*',
        label=_("Parameters"),
        flags={'no_search'},
    ), )

    def _iter_params(self, metaobj):
        raise NotImplementedError()

    def _get_obj(self, metaobj, all=False, **kwargs):
        obj = dict()
        obj['name'] = unicode(metaobj.name)
        obj['version'] = unicode(metaobj.version)
        obj['full_name'] = unicode(metaobj.full_name)

        if all:
            params = [unicode(p.name) for p in self._iter_params(metaobj)]
            if params:
                obj['params_param'] = params

        return obj
예제 #19
0
class command_defaults(PKQuery):
    __doc__ = _('Return command defaults')
    NO_CLI = True

    takes_options = (
        Str('params*'),
        Dict('kw?'),
    )

    def execute(self, name, **options):
        if name not in self.api.Command:
            raise errors.NotFound(
                reason=_("{oname}: {command_name} not found").format(
                    oname=self.name, command_name=name))

        command = self.api.Command[name]

        params = options.get('params') or []
        kw = options.get('kw') or {}

        result = command.get_default(params, **kw)

        return dict(result=result)
예제 #20
0
class MetaObject(BaseMetaObject):
    takes_params = BaseMetaObject.takes_params + (Str(
        'topic_topic?',
        label=_("Help topic"),
        flags={'no_search'},
    ), )

    def get_params(self):
        for param in super(MetaObject, self).get_params():
            yield param

            if param.name == 'name':
                yield Str(
                    'version',
                    label=_("Version"),
                    flags={'no_search'},
                )
                yield Str(
                    'full_name',
                    label=_("Full name"),
                    primary_key=True,
                    normalizer=lambda name: name.replace(u'-', u'_'),
                    flags={'no_search'},
                )
예제 #21
0
    def get_options(self):
        """
        Iterate through parameters for ``Command.options`` namespace.

        This method gets called by `HasParam._create_param_namespace()`.

        For commands that return entries two special options are generated:
        --all   makes the command retrieve/display all attributes
        --raw   makes the command display attributes as they are stored

        Subclasses can override this to customize how the arguments are
        determined.  For an example of why this can be useful, see the
        `ipalib.crud.Create` subclass.
        """
        for option in self._get_param_iterable('options'):
            yield option
        for o in self.has_output:
            if isinstance(o, (Entry, ListOfEntries)):
                yield Flag('all',
                    cli_name='all',
                    doc=_('Retrieve and print all attributes from the server. Affects command output.'),
                    exclude='webui',
                    flags=['no_output'],
                )
                yield Flag('raw',
                    cli_name='raw',
                    doc=_('Print entries as stored on the server. Only affects output format.'),
                    exclude='webui',
                    flags=['no_output'],
                )
                break
        yield Str('version?',
            doc=_('Client version. Used to determine if server will accept request.'),
            exclude='webui',
            flags=['no_option', 'no_output'],
        )
예제 #22
0
파일: frontend.py 프로젝트: zpytela/freeipa
class ClientMethod(ClientCommand, Method):
    _failed_member_output_params = (
        # baseldap
        Str(
            'member',
            label=_("Failed members"),
        ),
        Str(
            'sourcehost',
            label=_("Failed source hosts/hostgroups"),
        ),
        Str(
            'memberhost',
            label=_("Failed hosts/hostgroups"),
        ),
        Str(
            'memberuser',
            label=_("Failed users/groups"),
        ),
        Str(
            'memberservice',
            label=_("Failed service/service groups"),
        ),
        Str(
            'failed',
            label=_("Failed to remove"),
            flags=['suppress_empty'],
        ),
        Str(
            'ipasudorunas',
            label=_("Failed RunAs"),
        ),
        Str(
            'ipasudorunasgroup',
            label=_("Failed RunAsGroup"),
        ),
        # caacl
        Str(
            'ipamembercertprofile',
            label=_("Failed profiles"),
        ),
        Str(
            'ipamemberca',
            label=_("Failed CAs"),
        ),
        # group, hostgroup
        Str(
            'membermanager',
            label=_("Failed member manager"),
        ),
        # host
        Str(
            'managedby',
            label=_("Failed managedby"),
        ),
        # service
        Str(
            'ipaallowedtoperform_read_keys',
            label=_("Failed allowed to retrieve keytab"),
        ),
        Str(
            'ipaallowedtoperform_write_keys',
            label=_("Failed allowed to create keytab"),
        ),
        # servicedelegation
        Str(
            'failed_memberprincipal',
            label=_("Failed members"),
        ),
        Str(
            'ipaallowedtarget',
            label=_("Failed targets"),
        ),
        # vault
        Str(
            'owner?',
            label=_("Failed owners"),
        ),
    )

    def get_output_params(self):
        seen = set()
        for param in self.params():
            if param.name not in self.obj.params:
                seen.add(param.name)
                yield param
        for output_param in super(ClientMethod, self).get_output_params():
            seen.add(output_param.name)
            yield output_param
        for output_param in self._failed_member_output_params:
            if output_param.name not in seen:
                yield output_param
예제 #23
0
 class user(frontend.Object):
     takes_params = ('givenname', Str('sn', flags='no_update'),
                     Str('uid', primary_key=True), 'initials',
                     Str('uidnumber', flags=['no_create', 'no_search']))
예제 #24
0
파일: cli.py 프로젝트: vikas-lamba/freeipa
class help(frontend.Local):
    """
    Display help for a command or topic.
    """
    class Writer(object):
        """
        Writer abstraction
        """
        def __init__(self, outfile):
            self.outfile = outfile
            self.buffer = []

        @property
        def buffer_length(self):
            length = 0
            for line in self.buffer:
                length += len(line.split("\n"))
            return length

        def append(self, string=u""):
            self.buffer.append(unicode(string))

        def write(self):
            if self.buffer_length > get_terminal_height():
                data = "\n".join(self.buffer).encode("utf-8")
                open_in_pager(data)
            else:
                try:
                    for line in self.buffer:
                        print(line, file=self.outfile)
                except IOError:
                    pass

    takes_args = (
        Str('command?', cli_name='topic', label=_('Topic or Command'),
            doc=_('The topic or command name.')),
    )
    takes_options = (
        Any('outfile?', flags=['no_option']),
    )

    has_output = tuple()

    topic = None

    def _get_topic(self, topic):
        doc = u''
        parent_topic = None

        for package in self.api.packages:
            module_name = '{0}.{1}'.format(package.__name__, topic)
            try:
                module = sys.modules[module_name]
            except KeyError:
                try:
                    module = importlib.import_module(module_name)
                except ImportError:
                    continue

            if module.__doc__ is not None:
                doc = unicode(module.__doc__ or '').strip()
            try:
                parent_topic = module.topic
            except AttributeError:
                pass

        return doc, parent_topic

    def _count_topic_mcl(self, topic_name, mod_name):
        mcl = max((self._topics[topic_name][1], len(mod_name)))
        self._topics[topic_name][1] = mcl

    def _on_finalize(self):
        # {topic: ["description", mcl, {
        #     "subtopic": ["description", mcl, [commands]]}]}
        # {topic: ["description", mcl, [commands]]}
        self._topics = {}
        # [builtin_commands]
        self._builtins = []

        # build help topics
        for c in self.api.Command:
            if c is not self.api.Command.get_plugin(c.name):
                continue
            if c.NO_CLI:
                continue

            if c.topic is not None:
                doc, topic_name = self._get_topic(c.topic)
                doc = doc.split('\n', 1)[0]
                if topic_name is None:  # a module without grouping
                    topic_name = c.topic
                    if topic_name in self._topics:
                        self._topics[topic_name][2].append(c)
                    else:
                        self._topics[topic_name] = [doc, 0, [c]]
                    mcl = max((self._topics[topic_name][1], len(c.name)))
                    self._topics[topic_name][1] = mcl
                else:  # a module grouped in a topic
                    topic = self._get_topic(topic_name)
                    mod_name = c.topic
                    if topic_name in self._topics:
                        if mod_name in self._topics[topic_name][2]:
                            self._topics[topic_name][2][mod_name][2].append(c)
                        else:
                            self._topics[topic_name][2][mod_name] = [
                                doc, 0, [c]]
                            self._count_topic_mcl(topic_name, mod_name)
                        # count mcl for for the subtopic
                        mcl = max((
                            self._topics[topic_name][2][mod_name][1],
                            len(c.name)))
                        self._topics[topic_name][2][mod_name][1] = mcl
                    else:
                        self._topics[topic_name] = [
                            topic[0].split('\n', 1)[0],
                            0,
                            {mod_name: [doc, 0, [c]]}]
                        self._count_topic_mcl(topic_name, mod_name)
            else:
                self._builtins.append(c)

        # compute maximum topic length
        topics = list(self._topics) + [c.name for c in self._builtins]
        self._mtl = max(len(s) for s in topics)

        super(help, self)._on_finalize()

    def run(self, key=None, outfile=None, **options):
        if outfile is None:
            outfile = sys.stdout

        writer = self.Writer(outfile)
        name = from_cli(key)

        if key is None:
            self.api.parser.print_help(outfile)
            return
        if name == "topics":
            self.print_topics(outfile)
            return
        if name in self._topics:
            self.print_commands(name, outfile)
        elif name in self.Command:
            cmd = self.Command[name]
            if cmd.NO_CLI:
                raise HelpError(topic=name)
            self.Backend.cli.build_parser(cmd).print_help(outfile)
        elif any(name in t[2] for t in self._topics.values()
                 if type(t[2]) is dict):
            self.print_commands(name, outfile)
        elif name == "commands":
            mcl = 0
            for cmd_plugin in self.Command:
                if cmd_plugin is not self.Command.get_plugin(cmd_plugin.name):
                    continue
                if cmd_plugin.NO_CLI:
                    continue
                mcl = max(mcl, len(cmd_plugin.name))
                writer.append('{0}  {1}'.format(
                    to_cli(cmd_plugin.name).ljust(mcl), cmd_plugin.summary))
        else:
            raise HelpError(topic=name)
        writer.write()

    def print_topics(self, outfile):
        writer = self.Writer(outfile)

        for t, topic in sorted(self._topics.items()):
            writer.append('{0}  {1}'.format(
                to_cli(t).ljust(self._mtl), topic[0]))
        writer.write()

    def print_commands(self, topic, outfile):
        writer = self.Writer(outfile)

        if topic in self._topics and type(self._topics[topic][2]) is dict:
            # we want to display topic which has subtopics
            for subtopic in self._topics[topic][2]:
                doc = self._topics[topic][2][subtopic][0]
                mcl = self._topics[topic][1]
                writer.append('  {0}  {1}'.format(
                    to_cli(subtopic).ljust(mcl), doc))
        else:
            # we want to display subtopic or a topic which has no subtopics
            if topic in self._topics:
                mcl = self._topics[topic][1]
                commands = self._topics[topic][2]
            else:
                commands = []
                for t in self._topics:
                    if type(self._topics[t][2]) is not dict:
                        continue
                    if topic not in self._topics[t][2]:
                        continue
                    mcl = self._topics[t][2][topic][1]
                    commands = self._topics[t][2][topic][2]
                    break

            doc, _topic = self._get_topic(topic)

            if topic not in self.Command and len(commands) == 0:
                raise HelpError(topic=topic)

            writer.append(doc)
            if commands:
                writer.append()
                writer.append(_('Topic commands:'))
                for c in commands:
                    writer.append(
                        '  {0}  {1}'.format(
                            to_cli(c.name).ljust(mcl), c.summary))
                writer.append()
                writer.append(_('To get command help, use:'))
                writer.append(_('  ipa <command> --help'))
            writer.append()
        writer.write()
예제 #25
0
class batch(Command):
    NO_CLI = True

    takes_args = (
        Any('methods*',
            doc=_('Nested Methods to execute'),
        ),
    )

    take_options = (
        Str('version',
            cli_name='version',
            doc=_('Client version. Used to determine if server will accept request.'),
            exclude='webui',
            flags=['no_option', 'no_output'],
            default=API_VERSION,
            autofill=True,
        ),
    )

    has_output = (
        Output('count', int, doc=''),
        Output('results', (list, tuple), doc='')
    )

    def execute(self, *args, **options):
        results = []
        for arg in args[0]:
            params = dict()
            name = None
            try:
                if 'method' not in arg:
                    raise errors.RequirementError(name='method')
                if 'params' not in arg:
                    raise errors.RequirementError(name='params')
                name = arg['method']
                if name not in self.Command:
                    raise errors.CommandError(name=name)
                a, kw = arg['params']
                newkw = dict((str(k), v) for k, v in kw.items())
                params = api.Command[name].args_options_2_params(*a, **newkw)
                newkw.setdefault('version', options['version'])

                result = api.Command[name](*a, **newkw)
                self.info(
                    '%s: batch: %s(%s): SUCCESS', context.principal, name, ', '.join(api.Command[name]._repr_iter(**params))
                )
                result['error']=None
            except Exception as e:
                if isinstance(e, errors.RequirementError) or \
                    isinstance(e, errors.CommandError):
                    self.info(
                        '%s: batch: %s',
                        context.principal,  # pylint: disable=no-member
                        e.__class__.__name__
                    )
                else:
                    self.info(
                        '%s: batch: %s(%s): %s',
                        context.principal, name,  # pylint: disable=no-member
                        ', '.join(api.Command[name]._repr_iter(**params)),
                        e.__class__.__name__
                    )
                if isinstance(e, errors.PublicError):
                    reported_error = e
                else:
                    reported_error = errors.InternalError()
                result = dict(
                    error=reported_error.strerror,
                    error_code=reported_error.errno,
                    error_name=unicode(type(reported_error).__name__),
                )
            results.append(result)
        return dict(count=len(results) , results=results)
예제 #26
0
class cert_request(CertRetrieveOverride):
    takes_options = CertRetrieveOverride.takes_options + (
        Str(
            'database?',
            label=_('Path to NSS database'),
            doc=_('Path to NSS database to use for private key'),
        ),
        Str(
            'private_key?',
            label=_('Path to private key file'),
            doc=_('Path to PEM file containing a private key'),
        ),
        Str(
            'password_file?',
            label=_(
                'File containing a password for the private key or database'),
        ),
        Str(
            'csr_profile_id?',
            label=_('Name of CSR generation profile (if not the same as'
                    ' profile_id)'),
        ),
    )

    def get_args(self):
        for arg in super(cert_request, self).get_args():
            if arg.name == 'csr':
                arg = arg.clone_retype(arg.name, File, required=False)
            yield arg

    def forward(self, csr=None, **options):
        database = options.pop('database', None)
        private_key = options.pop('private_key', None)
        csr_profile_id = options.pop('csr_profile_id', None)
        password_file = options.pop('password_file', None)

        if csr is None:
            if database:
                adaptor = csrgen.NSSAdaptor(database, password_file)
            elif private_key:
                adaptor = csrgen.OpenSSLAdaptor(private_key, password_file)
            else:
                raise errors.InvocationError(
                    message=u"One of 'database' or 'private_key' is required")

            pubkey_info = adaptor.get_subject_public_key_info()
            pubkey_info_b64 = base64.b64encode(pubkey_info)

            # If csr_profile_id is passed, that takes precedence.
            # Otherwise, use profile_id. If neither are passed, the default
            # in cert_get_requestdata will be used.
            profile_id = csr_profile_id
            if profile_id is None:
                profile_id = options.get('profile_id')

            response = self.api.Command.cert_get_requestdata(
                profile_id=profile_id,
                principal=options.get('principal'),
                public_key_info=unicode(pubkey_info_b64))

            req_info_b64 = response['result']['request_info']
            req_info = base64.b64decode(req_info_b64)

            csr = adaptor.sign_csr(req_info)

            if not csr:
                raise errors.CertificateOperationError(
                    error=(_('Generated CSR was empty')))

            # cert_request requires the CSR to be base64-encoded (but PEM
            # header and footer are not required)
            csr = unicode(base64.b64encode(csr))
        else:
            if database is not None or private_key is not None:
                raise errors.MutuallyExclusiveError(reason=_(
                    "Options 'database' and 'private_key' are not compatible"
                    " with 'csr'"))

        return super(cert_request, self).forward(csr, **options)
예제 #27
0
class schema(Command):
    __doc__ = _('Store and provide schema for commands and topics')
    NO_CLI = True

    takes_options = (Str('known_fingerprints*',
                         label=_("Fingerprint of schema cached by client")), )

    @staticmethod
    def _calculate_fingerprint(data):
        """
        Returns fingerprint for schema

        Behavior of this function can be changed at any time
        given that it always generates identical fingerprint for
        identical data (change in order of items in dict is
        irelevant) and the risk of generating identical fingerprint
        for different inputs is low.
        """
        to_process = [data]
        fingerprint = hashlib.sha1()

        for entry in to_process:
            if isinstance(entry, (list, tuple)):
                for item in entry:
                    to_process.append(item)
            elif isinstance(entry, dict):
                for key in sorted(entry.keys()):
                    to_process.append(key)
                    to_process.append(entry[key])
            else:
                fingerprint.update(unicode(entry).encode('utf-8'))

        return unicode(fingerprint.hexdigest()[:8])

    def _generate_schema(self, **kwargs):
        commands = list(self.api.Object.command.search(**kwargs))
        for command in commands:
            name = command['name']
            command['params'] = list(
                self.api.Object.param.search(name, **kwargs))
            command['output'] = list(
                self.api.Object.output.search(name, **kwargs))

        classes = list(self.api.Object['class'].search(**kwargs))
        for cls in classes:
            cls['params'] = list(
                self.api.Object.param.search(cls['name'], **kwargs))

        topics = list(self.api.Object.topic.search(**kwargs))

        schema = dict()
        schema['version'] = API_VERSION
        schema['commands'] = commands
        schema['classes'] = classes
        schema['topics'] = topics
        schema['fingerprint'] = self._calculate_fingerprint(schema)

        return schema

    def execute(self, *args, **kwargs):
        langs = "".join(getattr(context, "languages", []))

        if getattr(self.api, "_schema", None) is None:
            setattr(self.api, "_schema", {})

        schema = self.api._schema.get(langs)
        if schema is None:
            schema = self._generate_schema(**kwargs)
            self.api._schema[langs] = schema

        schema['ttl'] = SCHEMA_TTL

        if schema['fingerprint'] in kwargs.get('known_fingerprints', []):
            raise errors.SchemaUpToDate(
                fingerprint=schema['fingerprint'],
                ttl=schema['ttl'],
            )

        return dict(result=schema)
예제 #28
0
class param(BaseParam):
    takes_params = BaseParam.takes_params + (
        Bool(
            'alwaysask?',
            label=_("Always ask"),
            flags={'no_search'},
        ),
        Str(
            'cli_metavar?',
            label=_("CLI metavar"),
            flags={'no_search'},
        ),
        Str(
            'cli_name?',
            label=_("CLI name"),
            flags={'no_search'},
        ),
        Bool(
            'confirm',
            label=_("Confirm (password)"),
            flags={'no_search'},
        ),
        Str(
            'default*',
            label=_("Default"),
            flags={'no_search'},
        ),
        Str(
            'default_from_param*',
            label=_("Default from"),
            flags={'no_search'},
        ),
        Str(
            'label?',
            label=_("Label"),
            flags={'no_search'},
        ),
        Bool(
            'no_convert?',
            label=_("Convert on server"),
            flags={'no_search'},
        ),
        Str(
            'option_group?',
            label=_("Option group"),
            flags={'no_search'},
        ),
        Bool(
            'sensitive?',
            label=_("Sensitive"),
            flags={'no_search'},
        ),
        Bool(
            'positional?',
            label=_("Positional argument"),
            flags={'no_search'},
        ),
    )

    @property
    def parent(self):
        return self.api.Object.metaobject

    def _get_obj(self, metaobj_param, **kwargs):
        metaobj, param = metaobj_param

        obj = dict()
        obj['name'] = unicode(param.name)

        if param.type is unicode:
            obj['type'] = u'str'
        elif param.type is bytes:
            obj['type'] = u'bytes'
        elif param.type is not None:
            obj['type'] = unicode(param.type.__name__)

        if not param.required:
            obj['required'] = False
        if param.multivalue:
            obj['multivalue'] = True
        if param.password:
            obj['sensitive'] = True
        if isinstance(metaobj, Command):
            if param.required and param.name not in metaobj.args:
                obj['positional'] = False
            elif not param.required and param.name in metaobj.args:
                obj['positional'] = True

        for key, value in param._Param__clonekw.items():
            if key in ('doc', 'label'):
                obj[key] = unicode(value)
            elif key in ('exclude', 'include'):
                obj[key] = list(unicode(v) for v in value)
            if isinstance(metaobj, Command):
                if key == 'alwaysask':
                    obj.setdefault(key, value)
                elif key == 'confirm':
                    obj[key] = value
                elif key in ('cli_metavar', 'cli_name', 'option_group'):
                    obj[key] = unicode(value)
                elif key == 'default':
                    if param.multivalue:
                        obj[key] = [unicode(v) for v in value]
                    else:
                        obj[key] = [unicode(value)]
                    if not param.autofill:
                        obj['alwaysask'] = True
                elif key == 'default_from':
                    obj['default_from_param'] = list(
                        unicode(k) for k in value.keys)
                    if not param.autofill:
                        obj['alwaysask'] = True
                elif key in ('exponential', 'normalizer', 'only_absolute',
                             'precision'):
                    obj['no_convert'] = True

        if ((isinstance(metaobj, Command) and 'no_option' in param.flags) or
            (isinstance(metaobj, Object) and 'no_output' in param.flags)):
            value = obj.setdefault('exclude', [])
            if u'cli' not in value:
                value.append(u'cli')
            if u'webui' not in value:
                value.append(u'webui')

        return obj

    def _retrieve(self, metaobjectfull_name, name, **kwargs):
        found = False

        try:
            metaobj = self.api.Command[metaobjectfull_name]
        except KeyError:
            raise errors.NotFound(
                reason=_("%(metaobject)s: %(oname)s not found") % {
                    'metaobject': metaobjectfull_name,
                    'oname': self.name,
                })

        if 'command' in self.api.Object:
            plugin = self.api.Object['command']
            found = True
        elif 'class' in self.api.Object:
            plugin = self.api.Object['class']
            found = True

        if found:
            for param in plugin._iter_params(metaobj):
                if param.name == name:
                    return metaobj, param

        raise errors.NotFound(reason=_("%(pkey)s: %(oname)s not found") % {
            'pkey': name,
            'oname': self.name,
        })

    def _search(self, metaobjectfull_name, **kwargs):
        try:
            metaobj = self.api.Command[metaobjectfull_name]
            plugin = self.api.Object['command']
        except KeyError:
            try:
                metaobj = self.api.Object[metaobjectfull_name]
                plugin = self.api.Object['class']
            except KeyError:
                return tuple()

        return ((metaobj, param) for param in plugin._iter_params(metaobj))
예제 #29
0
파일: asterisk.py 프로젝트: sorbouc/sorbo
class astsite(LDAPObject):
    """
    Asterisk site, container for users, extensions, mailboxes and configs.
    """
    container_dn = 'cn=asterisk'
    object_name = _('Asterisk Site')
    object_name_plural = _('Asterisk Sites')
    object_class = ['top', 'nsContainer', 'AsteriskSiteDefaults']
    default_attributes = ['cn', 'description']
    label = _('Asterisk Sites')
    label_singular = _('Asterisk Site')

    takes_params = (
        Str(
            'cn',
            cli_name='name',
            label=_('Site name'),
            doc=_('Site Name'),
            normalizer=lambda value: value.lower(),
            primary_key=True,
        ),
        Str(
            'description',
            cli_name='description',
            label=_('Site Description'),
            doc=_('Site Description'),
        ),
        Str(
            'astaccountregistrationserver?',
            cli_name='default_registrationserver',
            label=_('Default registration server'),
            doc=
            _('Default registration server for this site. You may specify an IP or domain name'
              ),
        ),
        Str(
            'astaccountfromdomain?',
            cli_name='default_fromdomain',
            label=_('Default FromDomain'),
            doc=
            _('Sets default From: domain in SIP messages when acting as a SIP ua (client)'
              ),
        ),
        StrEnum(
            'astaccountallowoverlap?',
            cli_name='default_allowoverlap',
            label=_('AllowOverlap Default'),
            doc=
            _('Overlap dial provides for a longer time-out period between digits, also called the inter-digit timer. With overlap dial set to off, the gateway expects to receive the digits one right after the other coming in to this line with very little delay between digits'
              ),
            values=(
                u'yes',
                u'no',
            ),
        ),
        Str(
            'astaccountallowedcodec?',
            cli_name='default_allowedcodec',
            label=_('Default Allowed Codecs'),
            doc=_('Default Allowed Codecs'),
        ),
        Str(
            'astaccountdisallowedcodec?',
            cli_name='default_disallowedcodec',
            label=_('Default Disallowed Codecs'),
            doc=_('Default Disallowed Codecs'),
        ),
        StrEnum(
            'astaccountamaflags?',
            cli_name='default_amaflags',
            label=_('AMAflags Default'),
            doc=_('Default Automated Message Accounting flags'),
            values=(
                u'default',
                u'omit',
                u'billing',
                u'documentation',
            ),
        ),
        Int(
            'astaccountcalllimit?',
            cli_name='default_calllimit',
            label=_('CallLimit Default'),
            doc=_(
                'Number of simultaneous calls through this user/peer by default'
            ),
            minvalue=0,
        ),
        StrEnum(
            'astaccountcanreinvite?',
            cli_name='default_canreinvite',
            label=_('CanReinvite Default'),
            doc=_('Permit direct media traffic between endpoints by default'),
            values=(
                u'yes',
                u'no',
            ),
        ),
        StrEnum(
            'astaccountnat?',
            cli_name='default_nat',
            label=_('Nat Default'),
            doc=
            _('Setting it to yes forces RFC 3581 behavior and enables symmetric RTP support. Setting it to no only enables RFC 3581 behavior if the remote side requests it and disables symmetric RTP support. Setting it to force_rport forces RFC 3581 behavior and disables symmetric RTP support. Setting it to comedia enables RFC 3581 behavior if the remote side requests it and enables symmetric RTP support.'
              ),
            values=(
                u'yes',
                u'no',
                u'force_rport',
                u'comedia',
            ),
        ),
        StrEnum(
            'astaccountqualify?',
            cli_name='default_qualify',
            label=_('Qualify Default'),
            doc=_('Check if peer is online'),
            values=(
                u'yes',
                u'no',
            ),
        ),
        StrEnum(
            'astaccountdtmfmode?',
            cli_name='default_dtmfmode',
            label=_('Default Dtmfmode'),
            doc=_('Configure DTMF transmission'),
            values=(
                u'inband',
                u'rfc2833',
                u'info',
                u'auto',
            ),
        ),
        Str(
            'astaccountpermit?',
            _validate_ipmask,
            cli_name='default_permit',
            label=_('Default permitted subnet'),
            doc=_('Default permitted subnet in ip/mask format'),
        ),
        Str(
            'astaccountdeny?',
            _validate_ipmask,
            cli_name='default_deny',
            label=_('Default denied subnet'),
            doc=_('Default permitted subnet in ip/mask format'),
        ),
        Str(
            'astaccountlanguage?',
            cli_name='default_language',
            label=_('Default Language'),
            doc=_('Default language for voice prompts'),
        ),
        Str(
            'astaccountmusiconhold?',
            cli_name='default_musiconhold',
            label=_('Default MOH'),
            doc=_('Default music on hold category'),
        ),
        Int(
            'astaccountrtpholdtimeout?',
            cli_name='default_rtpholdtimeout',
            label=_('Default RTPHoldTimeout'),
            doc=_('Default value for RTP HOLD timeout parameter'),
            minvalue=0,
        ),
        Int(
            'astaccountrtptimeout?',
            cli_name='default_rtptimeout',
            label=_('Default RTPtimeout'),
            doc=_('Default value for RTP timeout parameter'),
            minvalue=0,
        ),
        Str(
            'astaccountregistrationcontext?',
            cli_name='default_registrationcontext',
            label=_('Default registration context'),
            doc=
            _('If specified, Asterisk will dynamically create and destroy a NoOp priority 1 extension in this context for a given peer who registers '
              ),
        ),
        Str(
            'astaccountsubscribecontext?',
            cli_name='default_subscribecontext',
            label=_('Default subscribe context'),
            doc=_('Set a specific context for SIP SUBSCRIBE requests'),
        ),
        Str(
            'astaccounttransport?',
            cli_name='default_transport',
            label=_('Default transport'),
            doc=
            _('Default transports in preferred order, comma separated. E.g. tls,tcp,udp'
              ),
        ),
        StrEnum(
            'astaccounttype?',
            cli_name='default_type',
            label=_('type Default'),
            doc=_(' '),
            values=(u'user', u'peer', u'friend'),
        ),
        StrEnum(
            'astaccountvideosupport?',
            cli_name='default_videosupport',
            label=_('videosupport Default'),
            doc=_(' '),
            values=(
                u'yes',
                u'no',
            ),
        ),
        #astvoicemailoptions
        #astvoicemailtimestamp
        #astvoicemailcontext
        StrEnum(
            'astaccountencryption?',
            cli_name='default_encryption',
            label=_('encryption Default'),
            doc=_(' '),
            values=(
                u'yes',
                u'no',
            ),
        ),
        #ipaautoastextension
        #ipaautoasttemplate
    )
예제 #30
0
class command(metaobject):
    takes_params = metaobject.takes_params + (
        Str(
            'obj_class?',
            label=_("Method of"),
            flags={'no_search'},
        ),
        Str(
            'attr_name?',
            label=_("Method name"),
            flags={'no_search'},
        ),
    )

    def _iter_params(self, cmd):
        for arg in cmd.args():
            yield arg
        for option in cmd.options():
            if option.name == 'version':
                continue
            yield option

    def _get_obj(self, cmd, **kwargs):
        obj = super(command, self)._get_obj(cmd, **kwargs)

        if cmd.doc:
            obj['doc'] = unicode(cmd.doc)

        if cmd.topic:
            try:
                topic = self.api.Object.topic.retrieve(unicode(cmd.topic))
            except errors.NotFound:
                pass
            else:
                obj['topic_topic'] = topic['full_name']

        if isinstance(cmd, Method):
            obj['obj_class'] = unicode(cmd.obj_full_name)
            obj['attr_name'] = unicode(cmd.attr_name)

        if cmd.NO_CLI:
            obj['exclude'] = [u'cli']

        return obj

    def _retrieve(self, name, **kwargs):
        try:
            cmd = self.api.Command[name]
            if not isinstance(cmd, Local):
                return cmd
        except KeyError:
            pass

        raise errors.NotFound(reason=_("%(pkey)s: %(oname)s not found") % {
            'pkey': name,
            'oname': self.name,
        })

    def _search(self, **kwargs):
        for cmd in self.api.Command():
            if not isinstance(cmd, Local):
                yield cmd