Exemplo n.º 1
0
    def get_addr_groups_op(self, request, arg):
        try:

            def cb(res):
                request.write(simplejson.dumps(res))
                request.finish()

            gtype_str = get_principal_type_from_args(arg)
            gtype = groupname_to_type[gtype_str]
            if gtype == Directory.NWADDR_GROUP:
                addr = create_cidr_ipaddr(arg['<address>'].encode('utf-8'))
            elif gtype == Directory.DLADDR_GROUP:
                addr = create_eaddr(arg['<address>'].encode('utf-8'))
            else:
                return webservice.badRequest(
                    request, "Could not retrieve "
                    "address groups: invalid address type.")
            if addr is None:
                return webservice.badRequest(
                    request, "Could not retrieve "
                    "address groups: invalid address format.")
            d = self.dm.get_group_membership(gtype, addr)
            d.addCallback(cb)
            d.addErrback(self.err, request, "get_group_parents",
                         "Could not retrieve address groups.")
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "get_addr_groups",
                            "Could not retrieve address groups.")
Exemplo n.º 2
0
    def shutdown(self, request, arg):
        try:
            content = json_parse_message_body(request)
            if content == None:
                return webservice.badRequest(request,
                                             "Unable to parse message body.")

            if not content in self.shutdown_scripts:
                return webservice.badRequest(request,
                                             "Cannot shutdown '%s'." % content)

            d = defer.Deferred()
            args = self.shutdown_scripts[content]
            env = dict(os.environ)

            process = reactor.spawnProcess(OutputGrabber(d),
                                           self.shutdown_scripts[content][0],
                                           args=args,
                                           env=env)

            def success(output):
                lg.debug("Shutdown completed:\n%s" % output)

            def error(failure):
                lg.error("Shutdown did not complete:\n%s" % str(failure))

            d.addCallback(success).\
                addErrback(error)

            return simplejson.dumps(True)
        except Exception, e:
            return self.err(Failure(), request, "shutdown",
                            "Could not shutdown the system/process.")
Exemplo n.º 3
0
    def render_POST(self,request): 
        try:
          if "req" not in request.args: 
            webservice.badRequest(request, "POST did not include a 'req' argument")
            return webservice.NOT_DONE_YET
            
          req = request.args["req"][0]
          fp = hashlib.sha1(req).hexdigest()

          def err(res): 
            lg.error("error submitting pki sign req: %s" % str(res))
            webservice.internalError(request, "server error: %s" % str(res))
           
          def write_ok(res): 
            request.write(fp)
            request.finish()
         
          def find_slot_ok(slot_id): 
            data = [fp,req]
            d = self.simple_config.set_config(REQUEST_SEC_ID,{slot_id : data})
            d.addCallbacks(write_ok,err)
          
          d = self.find_next_slot()
          d.addCallbacks(find_slot_ok,err)
          return webservice.NOT_DONE_YET

        except Exception,e:
            lg.error("exception: " + str(e)) 
            webservice.badRequest(request, "failed to get CSR")
            return webservice.NOT_DONE_YET
Exemplo n.º 4
0
    def shutdown(self, request, arg):
        try:
            content = json_parse_message_body(request)
            if content == None:
                return webservice.badRequest(request, 
                                             "Unable to parse message body.")

            if not content in self.shutdown_scripts:
                return webservice.badRequest(request, "Cannot shutdown '%s'." % 
                                             content)

            d = defer.Deferred()
            args = self.shutdown_scripts[content]
            env = dict(os.environ)

            process = reactor.spawnProcess(OutputGrabber(d), 
                                           self.shutdown_scripts[content][0],
                                           args=args, env=env)

            def success(output):
                lg.debug("Shutdown completed:\n%s" % output)

            def error(failure):
                lg.error("Shutdown did not complete:\n%s" % str(failure))

            d.addCallback(success).\
                addErrback(error)

            return simplejson.dumps(True)
        except Exception, e:
            return self.err(Failure(), request, "shutdown",
                            "Could not shutdown the system/process.")
Exemplo n.º 5
0
 def put_interface(self, request, arg):
     try:
         intf = cfg_interface()
         content = json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request, "Unable to parse message body.")
         try:
             if not 'name' in content:
                 return webservice.badRequest(request, "Cannot configure interface: Name parameter not present.")
             intf.name = str(content['name'])
             if 'hwaddr' in content:
                 intf.hwaddr = str(content['hwaddr'])
             if 'ip4addr' in content:
                 intf.ip4addr = str(content['ip4addr'])
             if 'ip4mask' in content:
                 intf.ip4mask = str(content['ip4mask'])
             if 'ip4bcast' in content:
                 intf.ip4bcast = str(content['ip4bcast'])
             if 'ip4gw' in content:
                 intf.ip4gw = str(content['ip4gw'])
             if 'ip4dns' in content:
                 intf.ip4dns = str(content['ip4dns'])
             if 'dhcp' in content:
                 intf.dhcp = content['dhcp']
         except Exception, e:
             f = Failure()
             lg.error("put_interface_config: error reading interface information from request:" + str(f))
             return webservice.badRequest(request,"Cannot configure interface: invalid content parameters.")
         self.cfg.set_interface(intf)
         return simplejson.dumps(True)
Exemplo n.º 6
0
    def member_op_start(self, request, arg, otype_str):
        try:
            groupname = arg["<group name>"]
            groupdir = arg["<group dir>"]
            mangled_group = mangle_name(groupdir, groupname)
            membername = arg["<member name>"]
            memberdir = arg.get("<member dir>")
            ptype_str = get_principal_type_from_args(arg)
            ctype_str = find_value_in_args(arg, ["principal", "address", "subgroup"])

            if memberdir == self.dm.discovered_dir.name:
                return webservice.badRequest(
                    request,
                    "Discovered principals "
                    "may not be added to groups; try moving principal to "
                    "a persistent directory first.",
                )
            ptype = groupname_to_type[ptype_str]
            is_address = ctype_str == "address"
            if is_address and ptype == Directory_Factory.DLADDR_GROUP:
                mangled_member = create_eaddr(membername.encode("utf-8"))
            elif is_address and ptype == Directory_Factory.NWADDR_GROUP:
                mangled_member = create_cidr_ipaddr(membername.encode("utf-8"))
            else:
                mangled_member = mangle_name(memberdir, membername)
            if mangled_member is None:
                return webservice.badRequest(request, "Invalid group member parameter: '%s'" % membername)

            d = self.dm.get_group(ptype, mangled_group)
            f = lambda x: self.member_op(request, x, mangled_member, ptype_str, otype_str, ctype_str)
            d.addCallback(f)
            d.addErrback(self.err, request, "member_op_start", "Could not retrieve group.")
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "member_op_start", "Could not retrieve group.")
Exemplo n.º 7
0
Arquivo: pki.py Projeto: pombreda/snac
    def render_POST(self, request):
        try:
            if "req" not in request.args:
                webservice.badRequest(request,
                                      "POST did not include a 'req' argument")
                return webservice.NOT_DONE_YET

            req = request.args["req"][0]
            fp = hashlib.sha1(req).hexdigest()

            def err(res):
                lg.error("error submitting pki sign req: %s" % str(res))
                webservice.internalError(request,
                                         "server error: %s" % str(res))

            def write_ok(res):
                request.write(fp)
                request.finish()

            def find_slot_ok(slot_id):
                data = [fp, req]
                d = self.simple_config.set_config(REQUEST_SEC_ID,
                                                  {slot_id: data})
                d.addCallbacks(write_ok, err)

            d = self.find_next_slot()
            d.addCallbacks(find_slot_ok, err)
            return webservice.NOT_DONE_YET

        except Exception, e:
            lg.error("exception: " + str(e))
            webservice.badRequest(request, "failed to get CSR")
            return webservice.NOT_DONE_YET
Exemplo n.º 8
0
    def post_config_base64(self,request, arg): 
        try:
            section_id = arg['<section>']
            content = {}
      
            boundary = None
            content_type = request.getHeader("Content-Type")
            for field in content_type.split("; "):
                arr = field.split("=")
                if arr[0] == "boundary": 
                    boundary = arr[1] 
                    break

            if not boundary: 
                lg.error("Could not find boundary in multipart request") 
                return webservice.badRequest(request, \
                                                 "Could not find boundary to parse multipart/form-data")
        
            if str(type(request.content)) == "<type 'cStringIO.StringO'>": 
                multipart_str = str(request.content.getvalue()).lower()
            elif isinstance(request.content,file): 
                multipart_str = request.content.read()
            else:
                lg.error("request.content has unknown type '%s'" % \
                             str(type(request.content)))
                return webservice.internalError(request,"Cannot handle request.content type.")

            multipart_arr = multipart_str.split(boundary)

            for key,value in request.args.iteritems():
                if key == "section_id":
                    continue  # TODO: figure out how to stop this in javascript
                content[key] = [ base64.b64encode(value[0])] 
                found = False
                for chunk in multipart_arr:
                    if chunk.find("name=\""+key+"\"") >= 0: 
                        start_index = chunk.find("content-type:")
                        end_index = chunk.find("\n",start_index)
                        content [key + "_content_type"] = \
                            chunk[start_index:end_index].split(" ")[1].strip()
                        start_index = chunk.find("filename=")
                        q1_index = chunk.find("\"", start_index)
                        q2_index = chunk.find("\"", q1_index + 1) 
                        content [key + "_filename"] =  chunk[(q1_index + 1):q2_index]
                        found = True
                        break
                if not found:
                    msg = "Could not find Content-Type in multipart/form-data for item %s" % key
                    lg.error("post_config_base64: %s" % msg)
                    return webservice.badRequest(request, msg)

            request.setHeader("Content-Type", "text/plain") 
            return self.set_config_common(request,section_id,content)
        
        except Exception, e:
            return self.err(Failure(), request, "post_config_base64", "Could not set key.")
Exemplo n.º 9
0
    def __post_rules__(self, tmp, request, data, content):
        if not content.has_key('policy_id'):
            return webservice.badRequest(request, 'Request must include policy id to update.')
        elif content['policy_id'] != self.policy.policy_id:
            return webservice.conflictError(request, 'Cannot apply changes to old policy id %u.' % content['policy_id'])

        if not content.has_key('rules'):
            return webservice.badRequest(request, 'Request must include array of new policy rules.')

        d = self.__categorize_rules__(content['rules'])
        d.addCallbacks(self.__post_rules2__, self.badReq, (request,), None, (request, "post_rules"))
        return d
Exemplo n.º 10
0
 def put_record_rule_senders(self, request, data):
     try:
         content = webservice.json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request, "Unable to parse message body.")
         elif not self.policy.set_record_rule_senders(data['<rule id>'],
                                                      content['record_senders']):
             return webservice.badRequest(request, "Could not set record senders for rule ID %u." % data['<rule id>'])
         return "Success"
     except Exception, e:
         return self.err(Failure(), request, "put_record_rule_senders",
                         "Could not set record rule senders field.")
Exemplo n.º 11
0
    def member_op(self, request, group_info, member, ptype_str, otype_str,
                  ctype_str):
        try:

            def ok(res):
                def unicode_(s, encoding):
                    if isinstance(s, unicode): return s
                    return unicode(s, encoding)

                members = []
                for member in res[0]:
                    if not isinstance(member, basestring):
                        member = str(member)
                    members.append(unicode_(member, 'utf-8'))
                subgroups = [
                    unicode_(subgroup, 'utf-8') for subgroup in res[1]
                ]
                res_str = [members, subgroups]
                request.write(simplejson.dumps(res_str))
                request.finish()

            if group_info is None:
                return webservice.badRequest(request, "Group does not exist.")

            exists = is_member(group_info, member, ctype_str)
            if otype_str == "add" and exists:
                return webservice.badRequest(request, "%s is already a %s in the group." \
                                                   % (member,ctype_str))
            if otype_str != "add" and not exists:
                return webservice.notFound(request, "%s %s not found in group." \
                                                 % (ctype_str.capitalize(),member))

            if otype_str == "":
                # special case, this is just a membership test
                # if the request got this far, return success
                request.finish()
                return

            ptype = groupname_to_type[ptype_str]
            method_name = otype_str + "_group_members"
            f = getattr(self.dm, method_name)

            if ctype_str in ["principal", "address"]:
                d = f(ptype, group_info.name, (member, ), ())
            else:  # 'subgroup' case
                d = f(ptype, group_info.name, (), (member, ))
            d.addCallback(ok)
            d.addErrback(self.err, request, "%s member_op" % method_name,
                         "Could not %s." % method_name)
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "member_op",
                            "Could not perform group operation.")
Exemplo n.º 12
0
 def put_record_rule_senders(self, request, data):
     try:
         content = webservice.json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request,
                                          "Unable to parse message body.")
         elif not self.policy.set_record_rule_senders(
                 data['<rule id>'], content['record_senders']):
             return webservice.badRequest(
                 request, "Could not set record senders for rule ID %u." %
                 data['<rule id>'])
         return "Success"
     except Exception, e:
         return self.err(Failure(), request, "put_record_rule_senders",
                         "Could not set record rule senders field.")
Exemplo n.º 13
0
    def __put_analysis__(self, tmp, request, data, content):
        if not content.has_key('rules'):
            return webservice.badRequest(request, 'Request must include array of policy rules to analyze.')

        d = self.__categorize_rules__(request, content['rules'])
        d.addCallbacks(self.__put_analysis2__, self.badReq, (request,), None, (request, "put_analysis"))
        return d
Exemplo n.º 14
0
    def set_port_name_config_bool(self, request, arg, switch_info, maskbit): 
        try:
            dpid = switch_info.dpid.as_host()
            if dpid not in self.switchstats.dp_stats:
                return webservice.notFound(request, "Switch not active to set config.")
            portname = arg['<port name>']
            port = None
            for p in self.switchstats.dp_stats[dpid]['ports']:
                if p['name'] == portname:
                    port = p
                    break
            if port is None:
                return webservice.notFound(request, "Port not active to set config.")

            content = json_parse_message_body(request)
            if content != True and content != False:
                return webservice.badRequest(request, "Excepts a boolean value as message body.")
            port_no = port['port_no']    
            hw_addr = port['hw_addr'].replace('-',':')
            mask = 0 | maskbit 
            if content:
                config = 0
            else:    
                config = 0xffffffff 
            ret = self.switchstats.send_port_mod(dpid, port_no, hw_addr, mask, config)
            request.write(simplejson.dumps(ret))
            request.finish()
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "set_port_name_config",
                            "Could not set port name config.")
Exemplo n.º 15
0
    def _change_search_order(self, request, arg):
        def err_specific(res):
            if isinstance(res.value, DirectoryException) \
                    and res.value.code == DirectoryException.NONEXISTING_NAME:
                lg.error(
                    "Bad request: _change_search_order received nonexisting_name: %s"
                    % str(res))
                return webservice.badRequest(request, res.value.message)
            return self.err(res, request, "_change_search_order",
                            "Could not change search order.")

        try:
            content = json_parse_message_body(request)
            if content == None:
                return webservice.badRequest(request,
                                             "Unable to parse message body.")

            def ok(res):
                request.write(simplejson.dumps(res))
                request.finish()

            d = self._dm.set_search_order(content)
            d.addCallback(ok)
            d.addErrback(err_specific)
            return NOT_DONE_YET
        except Exception, e:
            err_specific(Failure())
Exemplo n.º 16
0
 def err_specific(res):
     if isinstance(res.value, DirectoryException) \
             and res.value.code == DirectoryException.NONEXISTING_NAME:
         lg.error("Bad request: _change_search_order received nonexisting_name: %s" % str(res))
         return webservice.badRequest(request, res.value.message)
     return self.err(res, request, "_change_search_order",
                     "Could not change search order.")
Exemplo n.º 17
0
    def member_op(self, request, group_info, member, ptype_str, otype_str, ctype_str):
        try:

            def ok(res):
                def unicode_(s, encoding):
                    if isinstance(s, unicode):
                        return s
                    return unicode(s, encoding)

                members = []
                for member in res[0]:
                    if not isinstance(member, basestring):
                        member = str(member)
                    members.append(unicode_(member, "utf-8"))
                subgroups = [unicode_(subgroup, "utf-8") for subgroup in res[1]]
                res_str = [members, subgroups]
                request.write(simplejson.dumps(res_str))
                request.finish()

            if group_info is None:
                return webservice.badRequest(request, "Group does not exist.")

            exists = is_member(group_info, member, ctype_str)
            if otype_str == "add" and exists:
                return webservice.badRequest(request, "%s is already a %s in the group." % (member, ctype_str))
            if otype_str != "add" and not exists:
                return webservice.notFound(request, "%s %s not found in group." % (ctype_str.capitalize(), member))

            if otype_str == "":
                # special case, this is just a membership test
                # if the request got this far, return success
                request.finish()
                return

            ptype = groupname_to_type[ptype_str]
            method_name = otype_str + "_group_members"
            f = getattr(self.dm, method_name)

            if ctype_str in ["principal", "address"]:
                d = f(ptype, group_info.name, (member,), ())
            else:  # 'subgroup' case
                d = f(ptype, group_info.name, (), (member,))
            d.addCallback(ok)
            d.addErrback(self.err, request, "%s member_op" % method_name, "Could not %s." % method_name)
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "member_op", "Could not perform group operation.")
Exemplo n.º 18
0
    def group_op(self, request, group_info, mangled_group, ptype_str, otype_str):
        try:

            def ok(res):
                if isinstance(res, GroupInfo):
                    request.write(simplejson.dumps(res.to_str_dict()))
                else:
                    request.write(simplejson.dumps(res))
                request.finish()

            is_get_op = otype_str == "get" or otype_str == "principal" or otype_str == "subgroup"
            if group_info is None and (is_get_op or otype_str == "del"):
                return webservice.notFound(request, "Group %s does not exist." % mangled_group)

            # read operations finish here.  this includes 'get','principal'
            # and 'subgroup' otype_str
            if is_get_op:
                str_dict = group_info.to_str_dict()
                if otype_str == "get":
                    request.write(simplejson.dumps(str_dict))
                elif otype_str == "principal":
                    request.write(simplejson.dumps(str_dict["member_names"]))
                elif otype_str == "subgroup":
                    request.write(simplejson.dumps(str_dict["subgroup_names"]))
                request.finish()
                return

            # only otype_str == 'add' or 'del' continues to this point

            ptype = groupname_to_type[ptype_str]
            if otype_str == "add":
                content = json_parse_message_body(request)
                if content == None:
                    return webservice.badRequest(request, "Unable to parse message body.")
                if group_info is None:
                    content["name"] = mangled_group
                    d = getattr(self.dm, "add_group")(ptype, GroupInfo.from_str_dict(content))
                elif len(content) == 1 and content.has_key("name"):
                    d = getattr(self.dm, "rename_group")(ptype, mangled_group, content["name"], "", "")
                else:
                    content["name"] = mangled_group
                    d = getattr(self.dm, "modify_group")(ptype, GroupInfo.from_str_dict(content))
            else:  # delete
                d = getattr(self.dm, "del_group")(ptype, mangled_group)
            d.addCallback(ok)
            d.addErrback(
                self.err,
                request,
                "%s %s group_op" % (otype_str, ptype_str),
                "Could not perform %s group operation." % ptype_str,
            )
            return NOT_DONE_YET
        except Exception, e:
            return self.err(
                Failure(),
                request,
                "%s %s group_op" % (otype_str, ptype_str),
                "Could not perform %s group operation." % ptype_str,
            )
Exemplo n.º 19
0
    def __post_rules__(self, tmp, request, data, content):
        if not content.has_key('policy_id'):
            return webservice.badRequest(
                request, 'Request must include policy id to update.')
        elif content['policy_id'] != self.policy.policy_id:
            return webservice.conflictError(
                request, 'Cannot apply changes to old policy id %u.' %
                content['policy_id'])

        if not content.has_key('rules'):
            return webservice.badRequest(
                request, 'Request must include array of new policy rules.')

        d = self.__categorize_rules__(content['rules'])
        d.addCallbacks(self.__post_rules2__, self.badReq, (request, ), None,
                       (request, "post_rules"))
        return d
Exemplo n.º 20
0
    def do_set_creds(self, request, arg):
        try:
            def _ok(res):
                ret = {Directory.AUTH_SIMPLE : []}
                if len(res):
                    ret[Directory.AUTH_SIMPLE].append(res[0].to_str_dict())
                request.write(simplejson.dumps(ret))
                request.finish()

            user_name = arg["<principal name>"]
            dir_name  = arg["<dir name>"]
           
            content = json_parse_message_body(request)
            if content == None: 
                return webservice.badRequest(request, "Unable to parse message body.")

            pwcreds = []
            enabled_auth_types = self.dm.get_directory_instance(dir_name)._instance.get_enabled_auth_types()
            for credtype, credlist in content.items():
                if not isinstance(credlist, list):
                    return webservice.badRequest(request,
                                                 "Credentials must be a list")
                if credtype not in enabled_auth_types or credtype != Directory.AUTH_SIMPLE:
                    return webservice.badRequest(request,
                                                 "Unsupported credential type '%s'" %credtype)

                if len(credlist) > 1:
                    return webservice.badRequest(request,
                                                 "Only one "+Directory.AUTH_SIMPLE
                                                 + " credential may be supplied")
                for pwdict in credlist:
                    pwcred = PasswordCredential.from_str_dict(pwdict)
                    if pwcred.password is None:
                        return webservice.badRequest(request,
                                                     "Invalid "+Directory.AUTH_SIMPLE
                                                     + " credential supplied")
                    pwcreds.append(pwcred)
            d = self.dm.put_credentials(Directory.USER_PRINCIPAL, user_name,
                                        pwcreds, dir_name=dir_name)
            d.addCallback(_ok)
            d.addErrback(self.err, request, "do_set_creds",
                         "Could not set credential information.")
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "do_set_creds",
                            "Could not set credential information.")
Exemplo n.º 21
0
    def __delete_rule__(self, tmp, request, data):
        id = data['<rule id>']
        if not self.policy.remove_rule(id):
            return webservice.badRequest(request, "Could not remove rule %u." % id)

        d = self.policy.apply(request.getSession().user.username)
        d.addCallback(self.write_policy_id, request)
        return d
Exemplo n.º 22
0
 def get_policy_names(self, request, data):
     try:
         content = web_arg_utils.flatten_args(request.args)
         keys = ['inport', 'dpsrc', 'dlsrc', 'dldst', 'nwsrc', 'nwdst']
         for key in keys:
             if not content.has_key(key):
                 return webservice.badRequest(request, "Must include '%s' argument." % key)
         try:
             dp = create_datapathid_from_host(long(content['dpsrc']))
             if dp == None:
                 return webservice.badRequest(request, "Invalid datapath ID.")
         except ValueError, e:
             return webservice.badRequest(request, "Invalid datapath.")
         try:
             port = int(content['inport'])
         except ValueError, e:
             return webservice.badRequest(request, "Invalid inport.")
Exemplo n.º 23
0
    def _modify_dir(self, request, arg):
        try:

            def _config_set(res):
                ep = convert_map_name_to_type(content["enabled_principals"])
                d = di.set_enabled_principals(ep)
                d.addCallback(_enabled_principals_set)
                return d

            def _enabled_principals_set(res):
                d = di.set_enabled_auth_types(content["enabled_auth_types"])
                d.addCallback(_enabled_auth_set)
                return d

            def _enabled_auth_set(res):
                if content["name"] != dname:
                    lg.error("TODO: implement renaming directories")
                item = self._convert_instance_to_dict(instance)
                ret = simplejson.dumps(item)
                request.write(ret)
                request.finish()

            dname = arg['<dir name>']
            content = json_parse_message_body(request)
            if content is None:
                return webservice.badRequest(request,
                                             "Unable to parse message body.")
            if request.args.get('add', ['false'])[0].lower() == 'true':
                return self._add_dir(request, dname, content)
            instance = self._dm.get_directory_instance(dname)
            if instance is None:
                return webservice.badRequest(
                    request, "Could not modify "
                    "directory: directory named '%s' does not exist" % dname)

            # otherwise, proceed with normal modify
            di = instance._instance
            d = di.set_config_params(content["config_params"])
            d.addCallback(_config_set)
            d.addErrback(self.err, request, "_modify_dir",
                         "Could not modify directory.")
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "_modify_dir",
                            "Could not add/modify directory.")
Exemplo n.º 24
0
 def err_specific(res):
     if isinstance(res.value, DirectoryException) \
             and res.value.code == DirectoryException.NONEXISTING_NAME:
         lg.error(
             "Bad request: _change_search_order received nonexisting_name: %s"
             % str(res))
         return webservice.badRequest(request, res.value.message)
     return self.err(res, request, "_change_search_order",
                     "Could not change search order.")
Exemplo n.º 25
0
    def __delete_rule__(self, tmp, request, data):
        id = data['<rule id>']
        if not self.policy.remove_rule(id):
            return webservice.badRequest(request,
                                         "Could not remove rule %u." % id)

        d = self.policy.apply(request.getSession().user.username)
        d.addCallback(self.write_policy_id, request)
        return d
Exemplo n.º 26
0
    def _modify_dir(self,request,arg): 
        try:
            def _config_set(res):
                ep = convert_map_name_to_type(content["enabled_principals"]) 
                d = di.set_enabled_principals(ep)
                d.addCallback(_enabled_principals_set)
                return d

            def _enabled_principals_set(res):
                d = di.set_enabled_auth_types(content["enabled_auth_types"])
                d.addCallback(_enabled_auth_set)
                return d

            def _enabled_auth_set(res):
                if content["name"] != dname: 
                    lg.error("TODO: implement renaming directories")
                item = self._convert_instance_to_dict(instance) 
                ret = simplejson.dumps(item) 
                request.write(ret)
                request.finish()

            dname = arg['<dir name>']
            content = json_parse_message_body(request)
            if content is None:
                return webservice.badRequest(request,
                        "Unable to parse message body.")
            if request.args.get('add', ['false'])[0].lower() == 'true':
                return self._add_dir(request, dname, content)
            instance = self._dm.get_directory_instance(dname)
            if instance is None:
                return webservice.badRequest(request,"Could not modify "
                        "directory: directory named '%s' does not exist" 
                        %dname)
            
            # otherwise, proceed with normal modify
            di = instance._instance
            d = di.set_config_params(content["config_params"])
            d.addCallback(_config_set)
            d.addErrback(self.err, request, "_modify_dir",
                         "Could not modify directory.")
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "_modify_dir",
                            "Could not add/modify directory.")
Exemplo n.º 27
0
 def get_policy_names(self, request, data):
     try:
         content = web_arg_utils.flatten_args(request.args)
         keys = ['inport', 'dpsrc', 'dlsrc', 'dldst', 'nwsrc', 'nwdst']
         for key in keys:
             if not content.has_key(key):
                 return webservice.badRequest(
                     request, "Must include '%s' argument." % key)
         try:
             dp = create_datapathid_from_host(long(content['dpsrc']))
             if dp == None:
                 return webservice.badRequest(request,
                                              "Invalid datapath ID.")
         except ValueError, e:
             return webservice.badRequest(request, "Invalid datapath.")
         try:
             port = int(content['inport'])
         except ValueError, e:
             return webservice.badRequest(request, "Invalid inport.")
Exemplo n.º 28
0
 def put_config_from_request(self,request, arg): 
     try:
         section_id = arg['<section>']
         content = webservice.json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request, "Unable to parse message body.")
         return self.set_config_common(request,section_id,content)
     except Exception, e:
         return self.err(Failure(), request, "put_config_from_request",
                         "Could not set config.")
Exemplo n.º 29
0
    def __put_analysis__(self, tmp, request, data, content):
        if not content.has_key('rules'):
            return webservice.badRequest(
                request,
                'Request must include array of policy rules to analyze.')

        d = self.__categorize_rules__(request, content['rules'])
        d.addCallbacks(self.__put_analysis2__, self.badReq, (request, ), None,
                       (request, "put_analysis"))
        return d
Exemplo n.º 30
0
 def send_switch_command(self, request, arg, switch_info):
     try:
         dpid = switch_info.dpid.as_host()
         content = json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request,"Unable to parse message body.")
         if type(content) != type({}):
             return webservice.badRequest(request,"Bad message body, expecting dict.")
         if 'command' not in content:    
             return webservice.badRequest(request,"No 'command' key in put")
         args = []
         if 'args' in content:    
             args = content['args']
         res = self.dm.send_switch_command(dpid, content['command'], args)
         request.write(simplejson.dumps(res))
         request.finish()
         return NOT_DONE_YET
     except Exception, e:
         return self.err(Failure(), request, "send_switch_command",
                         "Sending command failed.")
Exemplo n.º 31
0
    def get_rule_stats(self, request, data):
        try:
            stats = self.policy.get_rule_stats(data['<rule id>'])
            if stats == None:
                return webservice.badRequest(request, "Could not retrieve rule stats for ID %u." % data['<rule id>'])

            stats['sender_macs'] = [ str(eth) for eth in stats['sender_macs'] ]
            return simplejson.dumps(stats)
        except Exception, e:
            return self.err(Failure(), request, "get_rule_stats",
                            "Could not retrieve policy rule stats.")
Exemplo n.º 32
0
    def render_GET(self, request):
          if "req" not in request.args: 
            webservice.badRequest(request, "POST did not include a 'req' argument")
            return webservice.NOT_DONE_YET

          fp = request.args["fp"][0]
          print "trying to retreive cert with fingerprint = '%s'"
         
          def err(res): 
            lg.error("Error looking for signed cert: %s" % str(res))
            webservice.internalError(request, "server error: %s" % str(res))

          def find_cert(cert_dict): 
            if fp in cert_dict: 
              request.write(cert_dict[fp])
              request.finish()
            else: 
              webservice.notFound(request, "No approved cert with fingerprint = '%s'" % fp)

          d = self.simple_config.get_config(CERT_SEC_ID)
          d.addCallbacks(get_slot,err)
          return webservice.NOT_DONE_YET
Exemplo n.º 33
0
 def _add_table_row(self, request, arg):
     schema = arg[self.dbschema.dbname]
     table_name = arg["<db table name>"]
     row = webservice.json_parse_message_body(request)
     if row == None:
         return webservice.NOT_DONE_YET
     e = base_storagews._errors_in_row(schema, table_name, row, noGUID=True)
     if len(e) != 0:
         errmsg =  "Errors in message body:" + "\n    - ".join(e)
         return webservice.badRequest(request, errmsg)
     p = self.op_cls(self.db, schema, request)
     p.doPut(table_name, row)
     return webservice.NOT_DONE_YET
Exemplo n.º 34
0
 def _add_table_row(self, request, arg):
     schema = arg[self.dbschema.dbname]
     table_name = arg["<db table name>"]
     row = webservice.json_parse_message_body(request)
     if row == None:
         return webservice.NOT_DONE_YET
     e = base_storagews._errors_in_row(schema, table_name, row, noGUID=True)
     if len(e) != 0:
         errmsg = "Errors in message body:" + "\n    - ".join(e)
         return webservice.badRequest(request, errmsg)
     p = self.op_cls(self.db, schema, request)
     p.doPut(table_name, row)
     return webservice.NOT_DONE_YET
Exemplo n.º 35
0
    def get_rule_stats(self, request, data):
        try:
            stats = self.policy.get_rule_stats(data['<rule id>'])
            if stats == None:
                return webservice.badRequest(
                    request, "Could not retrieve rule stats for ID %u." %
                    data['<rule id>'])

            stats['sender_macs'] = [str(eth) for eth in stats['sender_macs']]
            return simplejson.dumps(stats)
        except Exception, e:
            return self.err(Failure(), request, "get_rule_stats",
                            "Could not retrieve policy rule stats.")
Exemplo n.º 36
0
    def member_op_start(self, request, arg, otype_str):
        try:
            groupname = arg['<group name>']
            groupdir = arg['<group dir>']
            mangled_group = mangle_name(groupdir, groupname)
            membername = arg['<member name>']
            memberdir = arg.get('<member dir>')
            ptype_str = get_principal_type_from_args(arg)
            ctype_str = find_value_in_args(
                arg, ["principal", "address", "subgroup"])

            if memberdir == self.dm.discovered_dir.name:
                return webservice.badRequest(
                    request, "Discovered principals "
                    "may not be added to groups; try moving principal to "
                    "a persistent directory first.")
            ptype = groupname_to_type[ptype_str]
            is_address = ctype_str == "address"
            if is_address and ptype == Directory_Factory.DLADDR_GROUP:
                mangled_member = create_eaddr(membername.encode('utf-8'))
            elif is_address and ptype == Directory_Factory.NWADDR_GROUP:
                mangled_member = create_cidr_ipaddr(membername.encode('utf-8'))
            else:
                mangled_member = mangle_name(memberdir, membername)
            if mangled_member is None:
                return webservice.badRequest(
                    request,
                    "Invalid group member parameter: '%s'" % membername)

            d = self.dm.get_group(ptype, mangled_group)
            f = lambda x: self.member_op(request, x, mangled_member, ptype_str,
                                         otype_str, ctype_str)
            d.addCallback(f)
            d.addErrback(self.err, request, "member_op_start",
                         "Could not retrieve group.")
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "member_op_start",
                            "Could not retrieve group.")
Exemplo n.º 37
0
 def put_rule(self, request, data):
     try:
         content = webservice.json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request, "Unable to parse message body.")
         d = self.policy.lock_policy()
         d.addCallback(self.__put_rule__, request, data, content)
         d.addBoth(self.unlock_policy)
         d.addErrback(self.err, request, "put_rule",
                      "Could not modify rule.")
     except Exception, e:
         return self.err(Failure(), request, "put_rule",
                         "Could not modify rule.")
Exemplo n.º 38
0
 def put_interface(self, request, arg):
     try:
         intf = cfg_interface()
         content = json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request,
                                          "Unable to parse message body.")
         try:
             if not 'name' in content:
                 return webservice.badRequest(
                     request,
                     "Cannot configure interface: Name parameter not present."
                 )
             intf.name = str(content['name'])
             if 'hwaddr' in content:
                 intf.hwaddr = str(content['hwaddr'])
             if 'ip4addr' in content:
                 intf.ip4addr = str(content['ip4addr'])
             if 'ip4mask' in content:
                 intf.ip4mask = str(content['ip4mask'])
             if 'ip4bcast' in content:
                 intf.ip4bcast = str(content['ip4bcast'])
             if 'ip4gw' in content:
                 intf.ip4gw = str(content['ip4gw'])
             if 'ip4dns' in content:
                 intf.ip4dns = str(content['ip4dns'])
             if 'dhcp' in content:
                 intf.dhcp = content['dhcp']
         except Exception, e:
             f = Failure()
             lg.error(
                 "put_interface_config: error reading interface information from request:"
                 + str(f))
             return webservice.badRequest(
                 request,
                 "Cannot configure interface: invalid content parameters.")
         self.cfg.set_interface(intf)
         return simplejson.dumps(True)
Exemplo n.º 39
0
 def put_analysis(self, request, data):
     try:
         content = webservice.json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request, "Unable to parse message body.")
         d = self.policy.lock_policy()
         d.addCallback(self.__put_analysis__, request, data, content)
         d.addBoth(self.unlock_policy)
         d.addErrback(self.err, request, "put_analysis",
                      "Could not analyze rules.")
         return webservice.NOT_DONE_YET
     except Exception, e:
         return self.err(Failure(), request, "put_analysis",
                         "Could not analyze rules.")
Exemplo n.º 40
0
    def get_addr_groups_op(self, request, arg):
        try:

            def cb(res):
                request.write(simplejson.dumps(res))
                request.finish()

            gtype_str = get_principal_type_from_args(arg)
            gtype = groupname_to_type[gtype_str]
            if gtype == Directory.NWADDR_GROUP:
                addr = create_cidr_ipaddr(arg["<address>"].encode("utf-8"))
            elif gtype == Directory.DLADDR_GROUP:
                addr = create_eaddr(arg["<address>"].encode("utf-8"))
            else:
                return webservice.badRequest(request, "Could not retrieve " "address groups: invalid address type.")
            if addr is None:
                return webservice.badRequest(request, "Could not retrieve " "address groups: invalid address format.")
            d = self.dm.get_group_membership(gtype, addr)
            d.addCallback(cb)
            d.addErrback(self.err, request, "get_group_parents", "Could not retrieve address groups.")
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "get_addr_groups", "Could not retrieve address groups.")
Exemplo n.º 41
0
def modify_protocol(request, data):
    try:
        content = webservice.json_parse_message_body(request)
        if content == None:
            return webservice.badRequest(request, "Unable to parse message body.")

        d = to_protocol_tup(request, content)
        d.addCallback(__modify_protocol2__, request, data)
        d.addErrback(err, request, "modify_protocol",
                     "Could not modify protocol.")
        return webservice.NOT_DONE_YET
    except Exception, e:
        return err(Failure(), request, "modify_protocol",
                   "Could not modify protocol.")
Exemplo n.º 42
0
 def put_rule(self, request, data):
     try:
         content = webservice.json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request,
                                          "Unable to parse message body.")
         d = self.policy.lock_policy()
         d.addCallback(self.__put_rule__, request, data, content)
         d.addBoth(self.unlock_policy)
         d.addErrback(self.err, request, "put_rule",
                      "Could not modify rule.")
     except Exception, e:
         return self.err(Failure(), request, "put_rule",
                         "Could not modify rule.")
Exemplo n.º 43
0
Arquivo: pki.py Projeto: pombreda/snac
    def render_GET(self, request):
        if "req" not in request.args:
            webservice.badRequest(request,
                                  "POST did not include a 'req' argument")
            return webservice.NOT_DONE_YET

        fp = request.args["fp"][0]
        print "trying to retreive cert with fingerprint = '%s'"

        def err(res):
            lg.error("Error looking for signed cert: %s" % str(res))
            webservice.internalError(request, "server error: %s" % str(res))

        def find_cert(cert_dict):
            if fp in cert_dict:
                request.write(cert_dict[fp])
                request.finish()
            else:
                webservice.notFound(
                    request, "No approved cert with fingerprint = '%s'" % fp)

        d = self.simple_config.get_config(CERT_SEC_ID)
        d.addCallbacks(get_slot, err)
        return webservice.NOT_DONE_YET
Exemplo n.º 44
0
 def put_analysis(self, request, data):
     try:
         content = webservice.json_parse_message_body(request)
         if content == None:
             return webservice.badRequest(request,
                                          "Unable to parse message body.")
         d = self.policy.lock_policy()
         d.addCallback(self.__put_analysis__, request, data, content)
         d.addBoth(self.unlock_policy)
         d.addErrback(self.err, request, "put_analysis",
                      "Could not analyze rules.")
         return webservice.NOT_DONE_YET
     except Exception, e:
         return self.err(Failure(), request, "put_analysis",
                         "Could not analyze rules.")
Exemplo n.º 45
0
def modify_protocol(request, data):
    try:
        content = webservice.json_parse_message_body(request)
        if content == None:
            return webservice.badRequest(request,
                                         "Unable to parse message body.")

        d = to_protocol_tup(request, content)
        d.addCallback(__modify_protocol2__, request, data)
        d.addErrback(err, request, "modify_protocol",
                     "Could not modify protocol.")
        return webservice.NOT_DONE_YET
    except Exception, e:
        return err(Failure(), request, "modify_protocol",
                   "Could not modify protocol.")
Exemplo n.º 46
0
    def _do_auth_event(self, request, arg):
        content = json_parse_message_body(request)
       
        try : 
          type = Auth_event.AUTHENTICATE
          if "type" in content and content["type"] == "deauthenticate": 
            type = Auth_event.DEAUTHENTICATE
          ni = NetInfo.from_str_dict(content)
          hostname =str(content.get("hostname",Authenticator.get_unknown_name()))  
          username =str(content.get("username", Authenticator.get_unknown_name())) 

          ae = Auth_event(type, ni.dpid, ni.port, ni.dladdr,ni.nwaddr,False, 
                          hostname, username, 0, 0)
          self.post(ae) 
          return "[]" 
        except Exception , e : 
          traceback.print_exc()
          return webservice.badRequest(request, str(e)) 
Exemplo n.º 47
0
    def _do_auth_event(self, request, arg):
        content = json_parse_message_body(request)

        try:
            type = Auth_event.AUTHENTICATE
            if "type" in content and content["type"] == "deauthenticate":
                type = Auth_event.DEAUTHENTICATE
            ni = NetInfo.from_str_dict(content)
            hostname = str(
                content.get("hostname", Authenticator.get_unknown_name()))
            username = str(
                content.get("username", Authenticator.get_unknown_name()))

            ae = Auth_event(type, ni.dpid, ni.port, ni.dladdr, ni.nwaddr,
                            False, hostname, username, 0, 0)
            self.post(ae)
            return "[]"
        except Exception, e:
            traceback.print_exc()
            return webservice.badRequest(request, str(e))
Exemplo n.º 48
0
 def _update_table_row(self, request, arg):
     schema = arg[self.dbschema.dbname]
     table_name = arg["<db table name>"]
     guid = arg["<db row guid>"]
     row = webservice.json_parse_message_body(request)
     if row == None:
         return webservice.NOT_DONE_YET
     e = base_storagews._errors_in_row(schema, table_name, row, 
             noGUID=False)
     if guid != row["GUID"]:
         e.append("GUID in message body must match GUID in URI.")
     if len(e) != 0:
         errmsg =  "The following error(s) were found:\n\n    - "
         errmsg += "\n    - ".join(e)
         return webservice.badRequest(request, errmsg)
     # TBD: remove this hack when storage API supports python
     # TBD: unicode strings.
     base_storagews._strip_unicode_in_dict(row)
     p = self.op_cls(self.db, schema, request)
     p.doModifyRow(table_name, row)
     return webservice.NOT_DONE_YET
Exemplo n.º 49
0
    def _do_user_deauth(self, request, arg):
        

        try:
          dirname = arg['<dir name>'] 
          name = arg['<principal name>']
          mangled_name = mangle_name(dirname,name)
        
          def cb(entity_list):
              if len(entity_list) == 0: 
                msg = "User '%s' is not currently authenticated. No entries removed." % \
                    (mangled_name)
                request.write(simplejson.dumps(msg))
                request.finish()
                return 

              for e in entity_list:
                dpid = datapathid.from_host(e[0])
                port = e[1]
                dladdr = ethernetaddr(e[2])
                nwaddr = e[3] 
                hostname = Authenticator.get_unknown_name()
                username = mangled_name 
                ae = Auth_event(Auth_event.DEAUTHENTICATE, dpid,
                        port, dladdr,nwaddr, False, hostname,
                        username, 0, 0)
                self.post(ae) 
                
              msg = "successfully removed %s user entries for '%s'" % \
                    (len(entity_list), mangled_name)
              request.write(simplejson.dumps(msg))
              request.finish()

          self.bs.get_entities_by_name(mangled_name,Name.USER,cb)
          return NOT_DONE_YET

        except Exception, e: 
          traceback.print_exc() 
          return webservice.badRequest(request,"Invalid URL parameters: %s" % e)
Exemplo n.º 50
0
    def _do_user_deauth(self, request, arg):

        try:
            dirname = arg['<dir name>']
            name = arg['<principal name>']
            mangled_name = mangle_name(dirname, name)

            def cb(entity_list):
                if len(entity_list) == 0:
                    msg = "User '%s' is not currently authenticated. No entries removed." % \
                        (mangled_name)
                    request.write(simplejson.dumps(msg))
                    request.finish()
                    return

                for e in entity_list:
                    dpid = datapathid.from_host(e[0])
                    port = e[1]
                    dladdr = ethernetaddr(e[2])
                    nwaddr = e[3]
                    hostname = Authenticator.get_unknown_name()
                    username = mangled_name
                    ae = Auth_event(Auth_event.DEAUTHENTICATE, dpid, port,
                                    dladdr, nwaddr, False, hostname, username,
                                    0, 0)
                    self.post(ae)

                msg = "successfully removed %s user entries for '%s'" % \
                      (len(entity_list), mangled_name)
                request.write(simplejson.dumps(msg))
                request.finish()

            self.bs.get_entities_by_name(mangled_name, Name.USER, cb)
            return NOT_DONE_YET

        except Exception, e:
            traceback.print_exc()
            return webservice.badRequest(request,
                                         "Invalid URL parameters: %s" % e)
Exemplo n.º 51
0
 def _update_table_row(self, request, arg):
     schema = arg[self.dbschema.dbname]
     table_name = arg["<db table name>"]
     guid = arg["<db row guid>"]
     row = webservice.json_parse_message_body(request)
     if row == None:
         return webservice.NOT_DONE_YET
     e = base_storagews._errors_in_row(schema,
                                       table_name,
                                       row,
                                       noGUID=False)
     if guid != row["GUID"]:
         e.append("GUID in message body must match GUID in URI.")
     if len(e) != 0:
         errmsg = "The following error(s) were found:\n\n    - "
         errmsg += "\n    - ".join(e)
         return webservice.badRequest(request, errmsg)
     # TBD: remove this hack when storage API supports python
     # TBD: unicode strings.
     base_storagews._strip_unicode_in_dict(row)
     p = self.op_cls(self.db, schema, request)
     p.doModifyRow(table_name, row)
     return webservice.NOT_DONE_YET
Exemplo n.º 52
0
    def _change_search_order(self, request, arg): 
        def err_specific(res):
            if isinstance(res.value, DirectoryException) \
                    and res.value.code == DirectoryException.NONEXISTING_NAME:
                lg.error("Bad request: _change_search_order received nonexisting_name: %s" % str(res))
                return webservice.badRequest(request, res.value.message)
            return self.err(res, request, "_change_search_order",
                            "Could not change search order.")
    
        try:
            content = json_parse_message_body(request)
            if content == None:
                return webservice.badRequest(request,"Unable to parse message body.")

            def ok(res):
                request.write(simplejson.dumps(res)) 
                request.finish()

            d = self._dm.set_search_order(content)
            d.addCallback(ok)
            d.addErrback(err_specific) 
            return NOT_DONE_YET
        except Exception, e:
            err_specific(Failure())
Exemplo n.º 53
0
    def set_port_name_config(self, request, arg, switch_info):
        try:
            dpid = switch_info.dpid.as_host()
            if dpid not in self.switchstats.dp_stats:
                return webservice.notFound(request, "Switch not active to set config.")
            portname = arg['<port name>']
            port = None
            for p in self.switchstats.dp_stats[dpid]['ports']:
                if p['name'] == portname:
                    port = p
                    break
            if port is None:
                return webservice.notFound(request, "Port not active to set config.")

            content = json_parse_message_body(request)
            if content == None:
                return webservice.badRequest(request,"Unable to parse message body.")
            port_no = port['port_no']    
            hw_addr = port['hw_addr'].replace('-',':')
            config = 0
            mask  = 0
            if 'flood' in content:
                mask |= openflow.OFPPC_NO_FLOOD
                if content['flood'] == False:
                    config |= openflow.OFPPC_NO_FLOOD
            if 'enabled' in content:
                mask |= openflow.OFPPC_PORT_DOWN
                if content['enabled'] == False:
                    config |= openflow.OFPPC_PORT_DOWN
            ret = self.switchstats.send_port_mod(dpid, port_no, hw_addr, mask, config)
            request.write(simplejson.dumps(ret))
            request.finish()
            return NOT_DONE_YET
        except Exception, e:
            return self.err(Failure(), request, "set_port_name_config",
                            "Could not set port name config.")
Exemplo n.º 54
0
    def group_op(self, request, group_info, mangled_group, ptype_str,
                 otype_str):
        try:

            def ok(res):
                if isinstance(res, GroupInfo):
                    request.write(simplejson.dumps(res.to_str_dict()))
                else:
                    request.write(simplejson.dumps(res))
                request.finish()

            is_get_op = otype_str == "get" or otype_str == "principal" \
                or otype_str == "subgroup"
            if group_info is None and (is_get_op or otype_str == "del"):
                return webservice.notFound(
                    request, "Group %s does not exist." % mangled_group)

            # read operations finish here.  this includes 'get','principal'
            # and 'subgroup' otype_str
            if is_get_op:
                str_dict = group_info.to_str_dict()
                if otype_str == "get":
                    request.write(simplejson.dumps(str_dict))
                elif otype_str == "principal":
                    request.write(simplejson.dumps(str_dict["member_names"]))
                elif otype_str == "subgroup":
                    request.write(simplejson.dumps(str_dict["subgroup_names"]))
                request.finish()
                return

            # only otype_str == 'add' or 'del' continues to this point

            ptype = groupname_to_type[ptype_str]
            if otype_str == "add":
                content = json_parse_message_body(request)
                if content == None:
                    return webservice.badRequest(
                        request, "Unable to parse message body.")
                if group_info is None:
                    content["name"] = mangled_group
                    d = getattr(self.dm,
                                "add_group")(ptype,
                                             GroupInfo.from_str_dict(content))
                elif len(content) == 1 and content.has_key('name'):
                    d = getattr(self.dm,
                                "rename_group")(ptype, mangled_group,
                                                content['name'], '', '')
                else:
                    content["name"] = mangled_group
                    d = getattr(self.dm, "modify_group")(
                        ptype, GroupInfo.from_str_dict(content))
            else:  # delete
                d = getattr(self.dm, "del_group")(ptype, mangled_group)
            d.addCallback(ok)
            d.addErrback(self.err, request,
                         "%s %s group_op" % (otype_str, ptype_str),
                         "Could not perform %s group operation." % ptype_str)
            return NOT_DONE_YET
        except Exception, e:
            return self.err(
                Failure(), request, "%s %s group_op" % (otype_str, ptype_str),
                "Could not perform %s group operation." % ptype_str)