These patches aims to bring Python3 support to sepolgen module. They're made from the patch I've sent earlier which was a little bit big for a single review so I cut it into smaller patches.
PATCH 1/11 sepolgen: Replace deprecated *Equals functions in tests
Also remove usage of cmp in tests as cmp is removed in Python3
--- sepolgen/tests/test_access.py | 44 ++++++++------- sepolgen/tests/test_audit.py | 108 ++++++++++++++++++------------------- sepolgen/tests/test_interfaces.py | 28 +++++----- sepolgen/tests/test_matching.py | 12 ++--- sepolgen/tests/test_objectmodel.py | 18 +++---- sepolgen/tests/test_refparser.py | 6 +-- sepolgen/tests/test_refpolicy.py | 50 ++++++++--------- 7 files changed, 135 insertions(+), 131 deletions(-)
sepolgen/tests/test_access.py +24 -20
@@ -32,7 +32,7 @@ class TestAccessVector(unittest.TestCase): self.assertEqual(a.obj_class, None) self.assertTrue(isinstance(a.perms, refpolicy.IdSet)) self.assertTrue(isinstance(a.audit_msgs, type([]))) - self.assertEquals(len(a.audit_msgs), 0) + self.assertEqual(len(a.audit_msgs), 0) # Construction from a list a = access.AccessVector()
@@ -82,8 +82,8 @@ class TestAccessVector(unittest.TestCase): a.obj_class = "file" a.perms.update(["read", "write"]) - self.assertEquals(str(a), "allow foo bar:file { read write };") - self.assertEquals(a.to_string(), "allow foo bar:file { read write };") + self.assertEqual(str(a), "allow foo bar:file { read write };") + self.assertEqual(a.to_string(), "allow foo bar:file { read write };") def test_cmp(self): a = access.AccessVector()
@@ -98,36 +98,40 @@ class TestAccessVector(unittest.TestCase): b.obj_class = "file" b.perms.update(["read", "write"]) - self.assertEquals(a, b) + self.assertEqual(a, b) # Source Type b.src_type = "baz" - self.assertEquals(cmp(a, b), 1) + self.assertNotEqual(a, b) + self.assertTrue(a > b) b.src_type = "gaz" - self.assertEquals(cmp(a, b), -1) + self.assertNotEqual(a, b) + self.assertTrue(a < b) # Target Type b.src_type = "foo" b.tgt_type = "aar" - self.assertEquals(cmp(a, b), 1) + self.assertNotEqual(a, b) + self.assertTrue(a > b) b.tgt_type = "gaz" - self.assertEquals(cmp(a, b), -1) + self.assertNotEqual(a, b) + self.assertTrue(a < b) # Perms b.tgt_type = "bar" b.perms = refpolicy.IdSet(["read"]) - ret = cmp(a, b) - self.assertEquals(ret, 1) + self.assertNotEqual(a, b) + self.assertTrue(a > b) b.perms = refpolicy.IdSet(["read", "write", "append"]) - ret = cmp(a, b) - self.assertEquals(ret, -1) + self.assertNotEqual(a, b) + self.assertTrue(a < b) b.perms = refpolicy.IdSet(["read", "append"]) - ret = cmp(a, b) - self.assertEquals(ret, 1) + self.assertNotEqual(a, b) + self.assertTrue(a > b) class TestUtilFunctions(unittest.TestCase): def test_is_idparam(self):
@@ -149,7 +153,7 @@ class TestUtilFunctions(unittest.TestCase): rule.perms.add("write") avs = access.avrule_to_access_vectors(rule) - self.assertEquals(len(avs), 8) + self.assertEqual(len(avs), 8) comps = [("foo", "what", "dir"), ("foo", "what", "file"), ("foo", "bar", "dir"),
@@ -160,7 +164,7 @@ class TestUtilFunctions(unittest.TestCase): ("baz", "bar", "file")] status = [False] * 8 for av in access.avrule_to_access_vectors(rule): - self.assertEquals(av.perms, refpolicy.IdSet(["read", "write"])) + self.assertEqual(av.perms, refpolicy.IdSet(["read", "write"])) for i in xrange(len(comps)): if comps[i][0] == av.src_type and \ comps[i][1] == av.tgt_type and \
@@ -168,7 +172,7 @@ class TestUtilFunctions(unittest.TestCase): status[i] = True for s in status: - self.assertEquals(s, True) + self.assertEqual(s, True) class TestAccessVectorSet(unittest.TestCase):
@@ -203,7 +207,7 @@ class TestAccessVectorSet(unittest.TestCase): ("baz", "bar", "file")] status = [False] * 8 for av in self.s: - self.assertEquals(av.perms, refpolicy.IdSet(["read", "write"])) + self.assertEqual(av.perms, refpolicy.IdSet(["read", "write"])) for i in xrange(len(comps)): if comps[i][0] == av.src_type and \ comps[i][1] == av.tgt_type and \
@@ -211,10 +215,10 @@ class TestAccessVectorSet(unittest.TestCase): status[i] = True for s in status: - self.assertEquals(s, True) + self.assertEqual(s, True) def test_len(self): - self.assertEquals(len(self.s), 8) + self.assertEqual(len(self.s), 8) def test_list(self): a = access.AccessVectorSet()
sepolgen/tests/test_audit.py +54 -54
164 lines not on this page · raw message
sepolgen/tests/test_interfaces.py +14 -14
@@ -202,11 +202,11 @@ class TestInterfaceSet(unittest.TestCase): i = interfaces.InterfaceSet() i.add_headers(h) - self.assertEquals(len(i.interfaces), 1) + self.assertEqual(len(i.interfaces), 1) for key, interface in i.interfaces.items(): - self.assertEquals(key, interface.name) - self.assertEquals(key, "foo") - self.assertEquals(len(interface.access), 2) + self.assertEqual(key, interface.name) + self.assertEqual(key, "foo") + self.assertEqual(len(interface.access), 2) # Check the access vectors comp_avs = [["$1", "usr_t", "dir", "create", "add_name"],
@@ -215,21 +215,21 @@ class TestInterfaceSet(unittest.TestCase): self.assertTrue(ret) # Check the params - self.assertEquals(len(interface.params), 1) + self.assertEqual(len(interface.params), 1) for param in interface.params.values(): - self.assertEquals(param.type, refpolicy.SRC_TYPE) - self.assertEquals(param.name, "$1") - self.assertEquals(param.num, 1) - self.assertEquals(param.required, True) + self.assertEqual(param.type, refpolicy.SRC_TYPE) + self.assertEqual(param.name, "$1") + self.assertEqual(param.num, 1) + self.assertEqual(param.required, True) def test_expansion(self): h = refparser.parse(test_expansion) i = interfaces.InterfaceSet() i.add_headers(h) - self.assertEquals(len(i.interfaces), 3) + self.assertEqual(len(i.interfaces), 3) for key, interface in i.interfaces.items(): - self.assertEquals(key, interface.name) + self.assertEqual(key, interface.name) if key == "foo": comp_avs = [["$1", "usr_t", "dir", "create", "add_name"], ["$1", "usr_t", "file", "read", "write"]]
@@ -277,6 +277,6 @@ class TestInterfaceSet(unittest.TestCase): if ifv.name == "files_exec_usr_files": if_status[2] = True - self.assertEquals(if_status[0], True) - self.assertEquals(if_status[1], True) - self.assertEquals(if_status[2], True) + self.assertEqual(if_status[0], True) + self.assertEqual(if_status[1], True) + self.assertEqual(if_status[2], True)
sepolgen/tests/test_matching.py +6 -6
@@ -33,15 +33,15 @@ class TestMatch(unittest.TestCase): b.dist = 100 b.info_dir_change = True - self.assertEquals(a, b) + self.assertEqual(a, b) b.info_dir_change = False - self.assertEquals(cmp(a, b), 1) - self.assertEquals(cmp(b, a), -1) + self.assertTrue((a > b)) + self.assertTrue((b < a)) b.dist = 200 - self.assertEquals(cmp(a, b), -1) - self.assertEquals(cmp(b, a), 1) + self.assertTrue((a < b)) + self.assertTrue((b > a)) class TestMatchList(unittest.TestCase): def test_append(self):
@@ -90,7 +90,7 @@ class TestMatchList(unittest.TestCase): for x, y in zip(l, ml): self.assertEqual(x, y) - self.assertEquals(ml.best(), c) + self.assertEqual(ml.best(), c) test_expansion = """
sepolgen/tests/test_objectmodel.py +9 -9
@@ -27,18 +27,18 @@ class TestInfoFlow(unittest.TestCase): info.from_file(fd) pm = info.get("filesystem", "mount") - self.assertEquals(pm.perm, "mount") - self.assertEquals(pm.dir, sepolgen.objectmodel.FLOW_WRITE) - self.assertEquals(pm.weight, 1) + self.assertEqual(pm.perm, "mount") + self.assertEqual(pm.dir, sepolgen.objectmodel.FLOW_WRITE) + self.assertEqual(pm.weight, 1) self.assertRaises(KeyError, info.get, "filesystem", "foo") pm = info.getdefault("filesystem", "foo") - self.assertEquals(pm.perm, "foo") - self.assertEquals(pm.dir, sepolgen.objectmodel.FLOW_BOTH) - self.assertEquals(pm.weight, 5) + self.assertEqual(pm.perm, "foo") + self.assertEqual(pm.dir, sepolgen.objectmodel.FLOW_BOTH) + self.assertEqual(pm.weight, 5) pm = info.getdefault("foo", "bar") - self.assertEquals(pm.perm, "bar") - self.assertEquals(pm.dir, sepolgen.objectmodel.FLOW_BOTH) - self.assertEquals(pm.weight, 5) + self.assertEqual(pm.perm, "bar") + self.assertEqual(pm.dir, sepolgen.objectmodel.FLOW_BOTH) + self.assertEqual(pm.weight, 5)
sepolgen/tests/test_refparser.py +3 -3
@@ -107,12 +107,12 @@ class TestParser(unittest.TestCase): h = refparser.parse(interface_example) #print "" #refpolicy.print_tree(h) - #self.assertEquals(len(h.interfaces), 3) + #self.assertEqual(len(h.interfaces), 3) name = "files_search_usr" #i = h.interfaces[name] - #self.assertEquals(i.name, name) - #self.assertEquals(len(i.rules), 1) + #self.assertEqual(i.name, name) + #self.assertEqual(len(i.rules), 1) #rule = i.rules[0] #self.assertTrue(isinstance(rule, refpolicy.AVRule))
sepolgen/tests/test_refpolicy.py +25 -25
111 lines not on this page · raw message
Signature · 1 line
2.4.3
PATCH 2/11 sepolgen: Use relative imports for modules within sepolgen.
In reply to Robert KuskaPython 3 changes the syntax for imports from within a package, requiring you to use the relative import syntax,
saying from . import mymodule instead of the just import mymodule.
--- sepolgen/src/sepolgen/access.py | 3 ++- sepolgen/src/sepolgen/audit.py | 4 ++-- sepolgen/src/sepolgen/classperms.py | 4 ++-- sepolgen/src/sepolgen/interfaces.py | 12 ++++++------ sepolgen/src/sepolgen/matching.py | 6 ++++-- sepolgen/src/sepolgen/module.py | 9 +++++---- sepolgen/src/sepolgen/output.py | 4 ++-- sepolgen/src/sepolgen/policygen.py | 10 +++++----- sepolgen/src/sepolgen/refparser.py | 13 ++++++------- sepolgen/src/sepolgen/yacc.py | 2 +- 10 files changed, 35 insertions(+), 32 deletions(-)
sepolgen/src/sepolgen/access.py +2 -1
@@ -31,7 +31,8 @@ and sets of that access (AccessVectorSet). These objects are used in Madison in a variety of ways, but they are the fundamental representation of access. """ -import refpolicy +from . import refpolicy + from selinux import audit2why def is_idparam(id):
sepolgen/src/sepolgen/audit.py +2 -2
@@ -17,11 +17,11 @@ # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # -import refpolicy -import access import re import sys +from . import refpolicy +from . import access # Convenience functions def get_audit_boot_msgs():
sepolgen/src/sepolgen/classperms.py +2 -2
@@ -52,7 +52,7 @@ def t_error(t): print "Illegal character '%s'" % t.value[0] t.skip(1) -import lex +from . import lex lex.lex() def p_statements(p):
@@ -92,7 +92,7 @@ def p_names(p): def p_error(p): print "Syntax error on line %d %s [type=%s]" % (p.lineno, p.value, p.type) -import yacc +from . import yacc yacc.yacc()
sepolgen/src/sepolgen/interfaces.py +6 -6
@@ -21,15 +21,15 @@ Classes for representing and manipulating interfaces. """ -import access -import refpolicy +import copy import itertools -import objectmodel -import matching -from sepolgeni18n import _ +from . import access +from . import refpolicy +from . import objectmodel +from . import matching +from .sepolgeni18n import _ -import copy class Param: """
sepolgen/src/sepolgen/matching.py +4 -2
@@ -21,10 +21,12 @@ Classes and algorithms for matching requested access to access vectors. """ -import access -import objectmodel import itertools +from . import access +from . import objectmodel + + class Match: def __init__(self, interface=None, dist=0): self.interface = interface
sepolgen/src/sepolgen/module.py +5 -4
@@ -22,10 +22,6 @@ Utilities for dealing with the compilation of modules and creation of module tress. """ -import defaults - -import selinux - import re import tempfile import commands
@@ -34,6 +30,11 @@ import os.path import subprocess import shutil +import selinux + +from . import defaults + + def is_valid_name(modname): """Check that a module name is valid. """
sepolgen/src/sepolgen/output.py +2 -2
@@ -27,8 +27,8 @@ generating policy. This keeps the semantic / syntactic issues cleanly separated from the formatting issues. """ -import refpolicy -import util +from . import refpolicy +from . import util class ModuleWriter: def __init__(self):
sepolgen/src/sepolgen/policygen.py +5 -5
@@ -24,17 +24,17 @@ classes and algorithms for the generation of SELinux policy. import itertools import textwrap -import refpolicy -import objectmodel -import access -import interfaces -import matching import selinux.audit2why as audit2why try: from setools import * except: pass +from . import refpolicy +from . import objectmodel +from . import access +from . import interfaces +from . import matching # Constants for the level of explanation from the generation # routines NO_EXPLANATION = 0
sepolgen/src/sepolgen/refparser.py +6 -7
@@ -34,12 +34,11 @@ import os import re import traceback -import refpolicy -import access -import defaults - -import lex -import yacc +from . import access +from . import defaults +from . import lex +from . import refpolicy +from . import yacc # ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: #
@@ -1041,7 +1040,7 @@ def list_headers(root): def parse_headers(root, output=None, expand=True, debug=False): - import util + from . import util headers = refpolicy.Headers()
sepolgen/src/sepolgen/yacc.py +1 -1
@@ -190,7 +190,7 @@ class Parser: # If no lexer was given, we will try to use the lex module if not lexer: - import lex + from . import lex lexer = lex.lexer pslice.lexer = lexer
Signature · 1 line
2.4.3
PATCH 3/11 sepolgen: Replace func_code calls with __code__.
In reply to Robert KuskaIn Python 3, special function attributes have been renamed for consistency with other attributes. __code__ attribute is also present in py2.7 and py2.6
--- sepolgen/src/sepolgen/lex.py | 10 +++++----- sepolgen/src/sepolgen/yacc.py | 22 +++++++++++----------- 2 files changed, 16 insertions(+), 16 deletions(-)
sepolgen/src/sepolgen/lex.py +5 -5
@@ -301,7 +301,7 @@ class Lexer: if not self.lexoptimize: if not self.lextokens.has_key(newtok.type): raise LexError, ("%s:%d: Rule '%s' returned an unknown token type '%s'" % ( - func.func_code.co_filename, func.func_code.co_firstlineno, + func.__code__.co_filename, func.__code__.co_firstlineno, func.__name__, newtok.type),lexdata[lexpos:]) return newtok
@@ -635,7 +635,7 @@ def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,now # Sort the functions by line number for f in funcsym.values(): - f.sort(lambda x,y: cmp(x[1].func_code.co_firstlineno,y[1].func_code.co_firstlineno)) + f.sort(lambda x,y: cmp(x[1].__code__.co_firstlineno,y[1].__code__.co_firstlineno)) # Sort the strings by regular expression length for s in strsym.values():
@@ -649,15 +649,15 @@ def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,now # Add rules defined by functions first for fname, f in funcsym[state]: - line = f.func_code.co_firstlineno - file = f.func_code.co_filename + line = f.__code__.co_firstlineno + file = f.__code__.co_filename files[file] = None tokname = toknames[fname] ismethod = isinstance(f, types.MethodType) if not optimize: - nargs = f.func_code.co_argcount + nargs = f.__code__.co_argcount if ismethod: reqargs = 2 else:
sepolgen/src/sepolgen/yacc.py +11 -11
@@ -457,11 +457,11 @@ def validate_dict(d): if n[0:2] == 'p_': sys.stderr.write("yacc: Warning. '%s' not defined as a function\n" % n) - if 1 and isinstance(v,types.FunctionType) and v.func_code.co_argcount == 1: + if 1 and isinstance(v,types.FunctionType) and v.__code__.co_argcount == 1: try: doc = v.__doc__.split(" ") if doc[1] == ':': - sys.stderr.write("%s:%d: Warning. Possible grammar rule '%s' defined without p_ prefix.\n" % (v.func_code.co_filename, v.func_code.co_firstlineno,n)) + sys.stderr.write("%s:%d: Warning. Possible grammar rule '%s' defined without p_ prefix.\n" % (v.__code__.co_filename, v.__code__.co_firstlineno,n)) except StandardError: pass
@@ -722,8 +722,8 @@ def add_production(f,file,line,prodname,syms): # and adds rules to the grammar def add_function(f): - line = f.func_code.co_firstlineno - file = f.func_code.co_filename + line = f.__code__.co_firstlineno + file = f.__code__.co_filename error = 0 if isinstance(f,types.MethodType):
@@ -731,11 +731,11 @@ def add_function(f): else: reqdargs = 1 - if f.func_code.co_argcount > reqdargs: + if f.__code__.co_argcount > reqdargs: sys.stderr.write("%s:%d: Rule '%s' has too many arguments.\n" % (file,line,f.__name__)) return -1 - if f.func_code.co_argcount < reqdargs: + if f.__code__.co_argcount < reqdargs: sys.stderr.write("%s:%d: Rule '%s' requires an argument.\n" % (file,line,f.__name__)) return -1
@@ -2079,11 +2079,11 @@ def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, ismethod = 1 else: raise YaccError,"'p_error' defined, but is not a function or method." - eline = ef.func_code.co_firstlineno - efile = ef.func_code.co_filename + eline = ef.__code__.co_firstlineno + efile = ef.__code__.co_filename files[efile] = None - if (ef.func_code.co_argcount != 1+ismethod): + if (ef.__code__.co_argcount != 1+ismethod): raise YaccError,"%s:%d: p_error() requires 1 argument." % (efile,eline) global Errorfunc Errorfunc = ef
@@ -2100,14 +2100,14 @@ def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, raise YaccError,"no rules of the form p_rulename are defined." # Sort the symbols by line number - symbols.sort(lambda x,y: cmp(x.func_code.co_firstlineno,y.func_code.co_firstlineno)) + symbols.sort(lambda x,y: cmp(x.__code__.co_firstlineno,y.__code__.co_firstlineno)) # Add all of the symbols to the grammar for f in symbols: if (add_function(f)) < 0: error += 1 else: - files[f.func_code.co_filename] = None + files[f.__code__.co_filename] = None # Make a signature of the docstrings for f in symbols:
Signature · 1 line
2.4.3
PATCH 4/11 sepolgen: Use sort function with key parameter.
In reply to Robert KuskaSince Python 2.4 .sort() as well as the new sorted() function take a key parameter which should be a function that returns a sorting key.
--- sepolgen/src/sepolgen/lex.py | 4 ++-- sepolgen/src/sepolgen/yacc.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-)
sepolgen/src/sepolgen/lex.py +2 -2
@@ -635,11 +635,11 @@ def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,now # Sort the functions by line number for f in funcsym.values(): - f.sort(lambda x,y: cmp(x[1].__code__.co_firstlineno,y[1].__code__.co_firstlineno)) + f.sort(key=lambda x: x[1].__code__.co_firstlineno) # Sort the strings by regular expression length for s in strsym.values(): - s.sort(lambda x,y: (len(x[1]) < len(y[1])) - (len(x[1]) > len(y[1]))) + s.sort(key=lambda x: len(x[1])) regexs = { }
sepolgen/src/sepolgen/yacc.py +1 -1
@@ -2100,7 +2100,7 @@ def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, raise YaccError,"no rules of the form p_rulename are defined." # Sort the symbols by line number - symbols.sort(lambda x,y: cmp(x.__code__.co_firstlineno,y.__code__.co_firstlineno)) + symbols.sort(key=lambda x: x.__code__.co_firstlineno) # Add all of the symbols to the grammar for f in symbols:
Signature · 1 line
2.4.3
PATCH 5/11 sepolgen: Unicode-objects must be encoded before hashing.
In reply to Robert Kuskasha256 hash operates with bytes and in Python3 all strings are unicode by default, we must encode the data before hashing to ensure they are bytes in Python3
--- sepolgen/src/sepolgen/util.py | 14 ++++++++++++++ sepolgen/src/sepolgen/yacc.py | 10 ++++++---- 2 files changed, 20 insertions(+), 4 deletions(-)
sepolgen/src/sepolgen/util.py +14 -0
@@ -76,6 +76,20 @@ def first(s, sorted=False): for x in s: return x +def encode_input(text): + import locale + """Encode given text via preferred system encoding""" + # locale will often find out the correct encoding + encoding = locale.getpreferredencoding() + try: + encoded_text = text.encode(encoding) + except UnicodeError: + # if it fails to find correct encoding then ascii is used + # which may lead to UnicodeError if `text` contains non ascii signs + # utf-8 is our guess to fix the situation + encoded_text = text.encode('utf-8') + return encoded_text + if __name__ == "__main__": import sys import time
sepolgen/src/sepolgen/yacc.py +6 -4
@@ -69,6 +69,8 @@ error_count = 3 # Number of symbols that must be shifted to leave import re, types, sys, cStringIO, hashlib, os.path +from . import util + # Exception raised for yacc-related errors class YaccError(Exception): pass
@@ -1962,7 +1964,7 @@ def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, # Add parsing method to signature - Signature.update(method) + Signature.update(util.encode_input(method)) # If a "module" parameter was supplied, extract its dictionary. # Note: a module may in fact be an instance as well.
@@ -1995,7 +1997,7 @@ def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, if not start: start = ldict.get("start",None) if start: - Signature.update(start) + Signature.update(util.encode_input(start)) # If running in optimized mode. We're going to
@@ -2064,7 +2066,7 @@ def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, if not (isinstance(prec,types.ListType) or isinstance(prec,types.TupleType)): raise YaccError,"precedence must be a list or tuple." add_precedence(prec) - Signature.update(repr(prec)) + Signature.update(util.encode_input(repr(prec))) for n in tokens: if not Precedence.has_key(n):
@@ -2112,7 +2114,7 @@ def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, # Make a signature of the docstrings for f in symbols: if f.__doc__: - Signature.update(f.__doc__) + Signature.update(util.encode_input(f.__doc__)) lr_init_vars()
Signature · 1 line
2.4.3
PATCH 6/11 sepolgen: Replace usage of __cmp__ with rich comparison.
In reply to Robert KuskaIn Python3 the __cmp__ function is removed, and rich comparison should be used instead.
Also the cmp function is gone in Python3 therefore it is reimplemented in util.py and used if running on Python3.
--- sepolgen/src/sepolgen/access.py | 36 ++++++++++++++++++------------------ sepolgen/src/sepolgen/matching.py | 33 ++++++++++++++------------------- sepolgen/src/sepolgen/output.py | 4 ++++ sepolgen/src/sepolgen/policygen.py | 3 +++ sepolgen/src/sepolgen/util.py | 35 +++++++++++++++++++++++++++++++++++ 5 files changed, 74 insertions(+), 37 deletions(-)
sepolgen/src/sepolgen/access.py +18 -18
@@ -32,6 +32,7 @@ in a variety of ways, but they are the fundamental representation of access. """ from . import refpolicy +from . import util from selinux import audit2why
@@ -52,7 +53,7 @@ def is_idparam(id): else: return False -class AccessVector: +class AccessVector(util.Comparison): """ An access vector is the basic unit of access in SELinux.
@@ -89,6 +90,9 @@ class AccessVector: self.audit_msgs = [] self.type = audit2why.TERULE self.data = [] + # when implementing __eq__ also __hash__ is needed on py2 + # if object is muttable __hash__ should be None + self.__hash__ = None # The direction of the information flow represented by this # access vector - used for matching
@@ -134,23 +138,19 @@ class AccessVector: return "allow %s %s:%s %s;" % (self.src_type, self.tgt_type, self.obj_class, self.perms.to_space_str()) - def __cmp__(self, other): - if self.src_type != other.src_type: - return cmp(self.src_type, other.src_type) - if self.tgt_type != other.tgt_type: - return cmp(self.tgt_type, other.tgt_type) - if self.obj_class != self.obj_class: - return cmp(self.obj_class, other.obj_class) - if len(self.perms) != len(other.perms): - return cmp(len(self.perms), len(other.perms)) - x = list(self.perms) - x.sort() - y = list(other.perms) - y.sort() - for pa, pb in zip(x, y): - if pa != pb: - return cmp(pa, pb) - return 0 + def _compare(self, other, method): + try: + x = list(self.perms) + a = (self.src_type, self.tgt_type, self.obj_class, x) + y = list(other.perms) + x.sort() + y.sort() + b = (other.src_type, other.tgt_type, other.obj_class, y) + return method(a, b) + except (AttributeError, TypeError): + # trying to compare to foreign type + return NotImplemented + def avrule_to_access_vectors(avrule): """Convert an avrule into a list of access vectors.
sepolgen/src/sepolgen/matching.py +14 -19
@@ -25,31 +25,26 @@ import itertools from . import access from . import objectmodel +from . import util -class Match: +class Match(util.Comparison): def __init__(self, interface=None, dist=0): self.interface = interface self.dist = dist self.info_dir_change = False - - def __cmp__(self, other): - if self.dist == other.dist: - if self.info_dir_change: - if other.info_dir_change: - return 0 - else: - return 1 - else: - if other.info_dir_change: - return -1 - else: - return 0 - else: - if self.dist < other.dist: - return -1 - else: - return 1 + # when implementing __eq__ also __hash__ is needed on py2 + # if object is muttable __hash__ should be None + self.__hash__ = None + + def _compare(self, other, method): + try: + a = (self.dist, self.info_dir_change) + b = (other.dist, other.info_dir_change) + return method(a, b) + except (AttributeError, TypeError): + # trying to compare to foreign type + return NotImplemented class MatchList: DEFAULT_THRESHOLD = 150
sepolgen/src/sepolgen/output.py +4 -0
@@ -30,6 +30,10 @@ cleanly separated from the formatting issues. from . import refpolicy from . import util +if util.PY3: + from .util import cmp + + class ModuleWriter: def __init__(self): self.fd = None
sepolgen/src/sepolgen/policygen.py +3 -0
@@ -35,6 +35,9 @@ from . import objectmodel from . import access from . import interfaces from . import matching +from . import util +if util.PY3: + from .util import cmp # Constants for the level of explanation from the generation # routines NO_EXPLANATION = 0
sepolgen/src/sepolgen/util.py +35 -0
@@ -16,6 +16,10 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # +import sys + + +PY3 = sys.version_info[0] == 3 class ConsoleProgressBar: def __init__(self, out, steps=100, indicator='#'):
@@ -90,6 +94,37 @@ def encode_input(text): encoded_text = text.encode('utf-8') return encoded_text +class Comparison(): + """Class used when implementing rich comparison. + + Inherit from this class if you want to have a rich + comparison withing the class, afterwards implement + _compare function within your class.""" + + def _compare(self, other, method): + raise NotImplemented + + def __eq__(self, other): + return self._compare(other, lambda a, b: a == b) + + def __lt__(self, other): + return self._compare(other, lambda a, b: a < b) + + def __le__(self, other): + return self._compare(other, lambda a, b: a <= b) + + def __ge__(self, other): + return self._compare(other, lambda a, b: a >= b) + + def __gt__(self, other): + return self._compare(other, lambda a, b: a > b) + + def __ne__(self, other): + return self._compare(other, lambda a, b: a != b) + +def cmp(first, second): + return (first > second) - (second > first) + if __name__ == "__main__": import sys import time
Signature · 1 line
2.4.3
Re: [PATCH 06/11] sepolgen: Replace usage of __cmp__ with rich comparison.
Quoted 60 lines · Robert Kuska
In Python3 the
__cmp__function is removed, and rich comparison should be used instead.
Also the cmp function is gone in Python3 therefore it is reimplemented inutil.pyand used if running on Python3.Signed-off-by Robert Kuska <[email protected]>--- sepolgen/src/sepolgen/access.py | 36 ++++++++++++++++++------------------ sepolgen/src/sepolgen/matching.py | 33 ++++++++++++++------------------- sepolgen/src/sepolgen/output.py | 4 ++++ sepolgen/src/sepolgen/policygen.py | 3 +++ sepolgen/src/sepolgen/util.py | 35 +++++++++++++++++++++++++++++++++++ 5 files changed, 74 insertions(+), 37 deletions(-)sepolgen/src/sepolgen/access.py +5
-12@@ -32,6 +32,7 @@ in a variety of ways, but they are the fundamental representation of access. """ from . import refpolicy +from . import util from selinux import audit2why@@ -52,7 +53,7 @@ def is_idparam(id): else: return False -class AccessVector: +class AccessVector(util.Comparison): """ An access vector is the basic unit of access in SELinux.@@ -89,6 +90,9 @@ class AccessVector: self.audit_msgs = [] self.type = audit2why.TERULE self.data = [] + # when implementing __eq__ also __hash__ is needed on py2 + # if object is muttable __hash__ should be None + self.__hash__ = None # The direction of the information flow represented by this # access vector - used for matching@@ -134,23 +138,19 @@ class AccessVector: return "allow %s %s:%s %s;" % (self.src_type, self.tgt_type, self.obj_class, self.perms.to_space_str()) - def __cmp__(self, other): - if self.src_type != other.src_type: - return cmp(self.src_type, other.src_type) - if self.tgt_type != other.tgt_type: - return cmp(self.tgt_type, other.tgt_type) - if self.obj_class != self.obj_class: - return cmp(self.obj_class, other.obj_class) - if len(self.perms) != len(other.perms): - return cmp(len(self.perms), len(other.perms)) - x = list(self.perms) - x.sort()
sepolgen/src/sepolgen/access.py class AccessVector: · line 144
Quoted 10 lines
sepolgen/src/sepolgen/access.py +4
-6- y = list(other.perms) - y.sort() - for pa, pb in zip(x, y): - if pa != pb: - return cmp(pa, pb) - return 0 + def _compare(self, other, method): + try: + x = list(self.perms) + a = (self.src_type, self.tgt_type, self.obj_class, x)
Shouldn't this be after the x.sort() below?
Quoted 152 lines
sepolgen/src/sepolgen/access.py +9
-0+ y = list(other.perms) + x.sort() + y.sort() + b = (other.src_type, other.tgt_type, other.obj_class, y) + return method(a, b) + except (AttributeError, TypeError): + # trying to compare to foreign type + return NotImplemented + def avrule_to_access_vectors(avrule): """Convert an avrule into a list of access vectors.sepolgen/src/sepolgen/matching.py +14
-19@@ -25,31 +25,26 @@ import itertools from . import access from . import objectmodel +from . import util -class Match: +class Match(util.Comparison): def __init__(self, interface=None, dist=0): self.interface = interface self.dist = dist self.info_dir_change = False - - def __cmp__(self, other): - if self.dist == other.dist: - if self.info_dir_change: - if other.info_dir_change: - return 0 - else: - return 1 - else: - if other.info_dir_change: - return -1 - else: - return 0 - else: - if self.dist < other.dist: - return -1 - else: - return 1 + # when implementing __eq__ also __hash__ is needed on py2 + # if object is muttable __hash__ should be None + self.__hash__ = None + + def _compare(self, other, method): + try: + a = (self.dist, self.info_dir_change) + b = (other.dist, other.info_dir_change) + return method(a, b) + except (AttributeError, TypeError): + # trying to compare to foreign type + return NotImplemented class MatchList: DEFAULT_THRESHOLD = 150sepolgen/src/sepolgen/output.py +4
-0@@ -30,6 +30,10 @@ cleanly separated from the formatting issues. from . import refpolicy from . import util +if util.PY3: + from .util import cmp + + class ModuleWriter: def __init__(self): self.fd = Nonesepolgen/src/sepolgen/policygen.py +3
-0@@ -35,6 +35,9 @@ from . import objectmodel from . import access from . import interfaces from . import matching +from . import util +if util.PY3: + from .util import cmp # Constants for the level of explanation from the generation # routines NO_EXPLANATION = 0sepolgen/src/sepolgen/util.py +35
-0@@ -16,6 +16,10 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # +import sys + + +PY3 = sys.version_info[0] == 3 class ConsoleProgressBar: def __init__(self, out, steps=100, indicator='#'):@@ -90,6 +94,37 @@ def encode_input(text): encoded_text = text.encode('utf-8') return encoded_text +class Comparison(): + """Class used when implementing rich comparison. + + Inherit from this class if you want to have a rich + comparison withing the class, afterwards implement + _compare function within your class.""" + + def _compare(self, other, method): + raise NotImplemented + + def __eq__(self, other): + return self._compare(other, lambda a, b: a == b) + + def __lt__(self, other): + return self._compare(other, lambda a, b: a < b) + + def __le__(self, other): + return self._compare(other, lambda a, b: a <= b) + + def __ge__(self, other): + return self._compare(other, lambda a, b: a >= b) + + def __gt__(self, other): + return self._compare(other, lambda a, b: a > b) + + def __ne__(self, other): + return self._compare(other, lambda a, b: a != b) + +def cmp(first, second): + return (first > second) - (second > first) + if __name__ == "__main__": import sys import timeSignature · 7 lines
2.4.3 _______________________________________________ Selinux mailing list [email protected] To unsubscribe, send email to [email protected]. To get help, send an email containing "help" to [email protected].
Re: [PATCH 06/11] sepolgen: Replace usage of __cmp__ with rich comparison.
--
Robert Kuska
{rkuska}
----- Original Message -----
Quoted 76 lines
From: "Jason Zaman" <[email protected]>
To: "Robert Kuska" <[email protected]>
Cc: [email protected]
Sent: Thursday, July 16, 2015 11:16:47 PM
Subject: Re: [PATCH 06/11] sepolgen: Replace usage of__cmp__with rich comparison.Quoted 69 lines · Robert Kuska
In Python3 the
__cmp__function is removed, and rich comparison should be used instead.
Also the cmp function is gone in Python3 therefore it is reimplemented inutil.pyand used if running on Python3.Signed-off-by Robert Kuska <[email protected]>--- sepolgen/src/sepolgen/access.py | 36 ++++++++++++++++++------------------ sepolgen/src/sepolgen/matching.py | 33 ++++++++++++++------------------- sepolgen/src/sepolgen/output.py | 4 ++++ sepolgen/src/sepolgen/policygen.py | 3 +++ sepolgen/src/sepolgen/util.py | 35 +++++++++++++++++++++++++++++++++++ 5 files changed, 74 insertions(+), 37 deletions(-)sepolgen/src/sepolgen/access.py +0
-0@@ -32,6 +32,7 @@ in a variety of ways, but they are the fundamentalrepresentation of access.
"""from . import refpolicy
sepolgen/src/sepolgen/access.py +5
-16+from . import util from selinux import audit2why@@ -52,7 +53,7 @@ def is_idparam(id): else: return False -class AccessVector: +class AccessVector(util.Comparison): """ An access vector is the basic unit of access in SELinux.@@ -89,6 +90,9 @@ class AccessVector: self.audit_msgs = [] self.type = audit2why.TERULE self.data = [] + # when implementing __eq__ also __hash__ is needed on py2 + # if object is muttable __hash__ should be None + self.__hash__ = None # The direction of the information flow represented by this # access vector - used for matching@@ -134,23 +138,19 @@ class AccessVector: return "allow %s %s:%s %s;" % (self.src_type, self.tgt_type, self.obj_class, self.perms.to_space_str()) - def __cmp__(self, other): - if self.src_type != other.src_type: - return cmp(self.src_type, other.src_type) - if self.tgt_type != other.tgt_type: - return cmp(self.tgt_type, other.tgt_type) - if self.obj_class != self.obj_class: - return cmp(self.obj_class, other.obj_class) - if len(self.perms) != len(other.perms): - return cmp(len(self.perms), len(other.perms)) - x = list(self.perms) - x.sort() - y = list(other.perms) - y.sort() - for pa, pb in zip(x, y): - if pa != pb:
Quoted 8 lines
sepolgen/src/sepolgen/access.py class AccessVector: · line 144
Quoted 6 lines
sepolgen/src/sepolgen/access.py +4
-2- return cmp(pa, pb) - return 0 + def _compare(self, other, method): + try: + x = list(self.perms) + a = (self.src_type, self.tgt_type, self.obj_class, x)Shouldn't this be after the
x.sort()below?
It doesn't really matter as list are muttable. But it could be move for better readability.
See:
Quoted 4 lines
Quoted 4 lines
Quoted 4 lines
a = [1, 2, 9, 7]
b = 1
c = (a, b)
c
([1, 2, 9, 7], 1)
Quoted 2 lines
Quoted 2 lines
Quoted 2 lines
a.sort()
c
([1, 2, 7, 9], 1)
Quoted 158 lines
Quoted 157 lines
sepolgen/src/sepolgen/access.py +9
-0+ y = list(other.perms) + x.sort() + y.sort() + b = (other.src_type, other.tgt_type, other.obj_class, y) + return method(a, b) + except (AttributeError, TypeError): + # trying to compare to foreign type + return NotImplemented + def avrule_to_access_vectors(avrule): """Convert an avrule into a list of access vectors.sepolgen/src/sepolgen/matching.py +14
-19@@ -25,31 +25,26 @@ import itertools from . import access from . import objectmodel +from . import util -class Match: +class Match(util.Comparison): def __init__(self, interface=None, dist=0): self.interface = interface self.dist = dist self.info_dir_change = False - - def __cmp__(self, other): - if self.dist == other.dist: - if self.info_dir_change: - if other.info_dir_change: - return 0 - else: - return 1 - else: - if other.info_dir_change: - return -1 - else: - return 0 - else: - if self.dist < other.dist: - return -1 - else: - return 1 + # when implementing __eq__ also __hash__ is needed on py2 + # if object is muttable __hash__ should be None + self.__hash__ = None + + def _compare(self, other, method): + try: + a = (self.dist, self.info_dir_change) + b = (other.dist, other.info_dir_change) + return method(a, b) + except (AttributeError, TypeError): + # trying to compare to foreign type + return NotImplemented class MatchList: DEFAULT_THRESHOLD = 150sepolgen/src/sepolgen/output.py +4
-0@@ -30,6 +30,10 @@ cleanly separated from the formatting issues. from . import refpolicy from . import util +if util.PY3: + from .util import cmp + + class ModuleWriter: def __init__(self): self.fd = Nonesepolgen/src/sepolgen/policygen.py +3
-0@@ -35,6 +35,9 @@ from . import objectmodel from . import access from . import interfaces from . import matching +from . import util +if util.PY3: + from .util import cmp # Constants for the level of explanation from the generation # routines NO_EXPLANATION = 0sepolgen/src/sepolgen/util.py +35
-1@@ -16,6 +16,10 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # +import sys + + +PY3 = sys.version_info[0] == 3 class ConsoleProgressBar: def __init__(self, out, steps=100, indicator='#'):@@ -90,6 +94,37 @@ def encode_input(text): encoded_text = text.encode('utf-8') return encoded_text +class Comparison(): + """Class used when implementing rich comparison. + + Inherit from this class if you want to have a rich + comparison withing the class, afterwards implement + _compare function within your class.""" + + def _compare(self, other, method): + raise NotImplemented + + def __eq__(self, other): + return self._compare(other, lambda a, b: a == b) + + def __lt__(self, other): + return self._compare(other, lambda a, b: a < b) + + def __le__(self, other): + return self._compare(other, lambda a, b: a <= b) + + def __ge__(self, other): + return self._compare(other, lambda a, b: a >= b) + + def __gt__(self, other): + return self._compare(other, lambda a, b: a > b) + + def __ne__(self, other): + return self._compare(other, lambda a, b: a != b) + +def cmp(first, second): + return (first > second) - (second > first) + if __name__ == "__main__": import sys import time --2.4.3
_______________________________________________
Selinux mailing list
[email protected]
To unsubscribe, send email to [email protected]. To get help, send an email containing "help" to [email protected].
PATCH 7/11 sepolgen: Replace usage of attributes of types module
In reply to Robert KuskaIn Python3 all strings are by default Unicode and both Unicode and String types are removed from types module. We introduce separate variables bytes_type and string_type to reflect Python3 understanding of strings, on Python2 bytes_type refers to <str> and string_type to <unicode>, on Python3 bytes_type are <bytes> and string_type <str>. As all strings are Unicodes by default on Python3 we encode them to bytes when needed as late as possible.
Also other attributes were replaced with their equivalents from builtins which are available for both Python3 and Python2.
--- sepolgen/src/sepolgen/lex.py | 31 ++++++++++++++++++------------- sepolgen/src/sepolgen/util.py | 9 +++++++++ sepolgen/src/sepolgen/yacc.py | 16 ++++++++-------- 3 files changed, 35 insertions(+), 21 deletions(-)
sepolgen/src/sepolgen/lex.py +18 -13
@@ -26,18 +26,20 @@ __version__ = "2.2" import re, sys, types +from . import util + + # Regular expression used to match valid token names _is_identifier = re.compile(r'^[a-zA-Z0-9_]+$') -# Available instance types. This is used when lexers are defined by a class. -# It's a little funky because I want to preserve backwards compatibility -# with Python 2.0 where types.ObjectType is undefined. +# Available instance types. This is used when parsers are defined by a class. +# In Python3 the InstanceType and ObjectType are no more, they've passed, ceased +# to be, they are ex-classes along with old-style classes try: _INSTANCETYPE = (types.InstanceType, types.ObjectType) except AttributeError: - _INSTANCETYPE = types.InstanceType - class object: pass # Note: needed if no new-style classes present + _INSTANCETYPE = object # Exception thrown when invalid token encountered and no default error # handler is defined.
@@ -197,7 +199,7 @@ class Lexer: # input() - Push a new string into the lexer # ------------------------------------------------------------ def input(self,s): - if not (isinstance(s,types.StringType) or isinstance(s,types.UnicodeType)): + if not (isinstance(s,util.bytes_type) or isinstance(s, util.string_type)): raise ValueError, "Expected a string" self.lexdata = s self.lexpos = 0
@@ -543,7 +545,7 @@ def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,now if not tokens: raise SyntaxError,"lex: module does not define 'tokens'" - if not (isinstance(tokens,types.ListType) or isinstance(tokens,types.TupleType)): + if not (isinstance(tokens,list) or isinstance(tokens,tuple)): raise SyntaxError,"lex: tokens must be a list or tuple." # Build a dictionary of valid token names
@@ -564,7 +566,7 @@ def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,now try: for c in literals: - if not (isinstance(c,types.StringType) or isinstance(c,types.UnicodeType)) or len(c) > 1: + if not (isinstance(c,util.bytes_type) or isinstance(c, util.string_type)) or len(c) > 1: print "lex: Invalid literal %s. Must be a single character" % repr(c) error = 1 continue
@@ -577,18 +579,21 @@ def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,now # Build statemap if states: - if not (isinstance(states,types.TupleType) or isinstance(states,types.ListType)): + if not (isinstance(states,tuple) or isinstance(states,list)): print "lex: states must be defined as a tuple or list." error = 1 else: for s in states: - if not isinstance(s,types.TupleType) or len(s) != 2: + if not isinstance(s,tuple) or len(s) != 2: print "lex: invalid state specifier %s. Must be a tuple (statename,'exclusive|inclusive')" % repr(s) error = 1 continue name, statetype = s - if not isinstance(name,types.StringType): - print "lex: state name %s must be a string" % repr(name) + if isinstance(name, util.string_type): + original_name = name + name = util.encode_input(name) + if not isinstance(name,util.bytes_type) or len(original_name) != len(name): + print "lex: state name %s must be a byte string" % repr(original_name) error = 1 continue if not (statetype == 'inclusive' or statetype == 'exclusive'):
@@ -627,7 +632,7 @@ def lex(module=None,object=None,debug=0,optimize=0,lextab="lextab",reflags=0,now if callable(t): for s in states: funcsym[s].append((f,t)) - elif (isinstance(t, types.StringType) or isinstance(t,types.UnicodeType)): + elif (isinstance(t, util.bytes_type) or isinstance(t,util.string_type)): for s in states: strsym[s].append((f,t)) else: print "lex: %s not defined as a function or string" % f
sepolgen/src/sepolgen/util.py +9 -0
@@ -16,11 +16,20 @@ # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # +import locale import sys PY3 = sys.version_info[0] == 3 +if PY3: + bytes_type=bytes + string_type=str +else: + bytes_type=str + string_type=unicode + + class ConsoleProgressBar: def __init__(self, out, steps=100, indicator='#'): self.blocks = 0
sepolgen/src/sepolgen/yacc.py +8 -8
@@ -111,7 +111,7 @@ class YaccProduction: self.stack = stack def __getitem__(self,n): - if type(n) == types.IntType: + if type(n) == int: if n >= 0: return self.slice[n].value else: return self.stack[n].value else:
@@ -1940,13 +1940,13 @@ def lr_read_tables(module=tab_module,optimize=0): # Available instance types. This is used when parsers are defined by a class. -# it's a little funky because I want to preserve backwards compatibility -# with Python 2.0 where types.ObjectType is undefined. +# In Python3 the InstanceType and ObjectType are no more, they've passed, ceased +# to be, they are ex-classes along with old-style classes try: _INSTANCETYPE = (types.InstanceType, types.ObjectType) except AttributeError: - _INSTANCETYPE = types.InstanceType + _INSTANCETYPE = object # ----------------------------------------------------------------------------- # yacc(module)
@@ -2026,18 +2026,18 @@ def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, if not tokens: raise YaccError,"module does not define a list 'tokens'" - if not (isinstance(tokens,types.ListType) or isinstance(tokens,types.TupleType)): + if not (isinstance(tokens,list) or isinstance(tokens,tuple)): raise YaccError,"tokens must be a list or tuple." # Check to see if a requires dictionary is defined. requires = ldict.get("require",None) if requires: - if not (isinstance(requires,types.DictType)): + if not (isinstance(requires,dict)): raise YaccError,"require must be a dictionary." for r,v in requires.items(): try: - if not (isinstance(v,types.ListType)): + if not (isinstance(v,list)): raise TypeError v1 = [x.split(".") for x in v] Requires[r] = v1
@@ -2063,7 +2063,7 @@ def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, # Get the precedence map (if any) prec = ldict.get("precedence",None) if prec: - if not (isinstance(prec,types.ListType) or isinstance(prec,types.TupleType)): + if not (isinstance(prec,list) or isinstance(prec,tuple)): raise YaccError,"precedence must be a list or tuple." add_precedence(prec) Signature.update(util.encode_input(repr(prec)))
Signature · 1 line
2.4.3
PATCH 8/11 sepolgen: Replace usage of xrange inside of tests.
In reply to Robert Kuskaxrange function is gone in Python3 and instead range is xrange by default. Also it doesnt seem to be important to have xrange used in tests on Python2.
--- sepolgen/tests/test_access.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
sepolgen/tests/test_access.py +2 -2
@@ -165,7 +165,7 @@ class TestUtilFunctions(unittest.TestCase): status = [False] * 8 for av in access.avrule_to_access_vectors(rule): self.assertEqual(av.perms, refpolicy.IdSet(["read", "write"])) - for i in xrange(len(comps)): + for i in range(len(comps)): if comps[i][0] == av.src_type and \ comps[i][1] == av.tgt_type and \ comps[i][2] == av.obj_class:
@@ -208,7 +208,7 @@ class TestAccessVectorSet(unittest.TestCase): status = [False] * 8 for av in self.s: self.assertEqual(av.perms, refpolicy.IdSet(["read", "write"])) - for i in xrange(len(comps)): + for i in range(len(comps)): if comps[i][0] == av.src_type and \ comps[i][1] == av.tgt_type and \ comps[i][2] == av.obj_class:
Signature · 1 line
2.4.3
PATCH 9/11 sepolgen: Apply fixes discovered by 2to3 where needed.
In reply to Robert KuskaReplace usage of print statement with print function.
Use in instead of has_key when checking for key in dict. When using raise add text (if any) as parameter of exception function. Add Python3 imports of moved modules.
Replace map with list comprehension.
Use reserved word as in try-except when catching exception. Replace ifilter function with filter.
--- sepolgen/src/sepolgen/access.py | 6 +- sepolgen/src/sepolgen/audit.py | 2 +- sepolgen/src/sepolgen/classperms.py | 6 +- sepolgen/src/sepolgen/defaults.py | 4 +- sepolgen/src/sepolgen/interfaces.py | 2 +- sepolgen/src/sepolgen/lex.py | 123 +++++++++++++++-------------- sepolgen/src/sepolgen/module.py | 8 +- sepolgen/src/sepolgen/objectmodel.py | 2 +- sepolgen/src/sepolgen/policygen.py | 6 +- sepolgen/src/sepolgen/refparser.py | 12 +-- sepolgen/src/sepolgen/refpolicy.py | 39 +++++---- sepolgen/src/sepolgen/yacc.py | 149 ++++++++++++++++++----------------- 12 files changed, 182 insertions(+), 177 deletions(-)
sepolgen/src/sepolgen/access.py +3 -3
@@ -263,7 +263,7 @@ class AccessVectorSet: tgt = self.src.setdefault(src_type, { }) cls = tgt.setdefault(tgt_type, { }) - if cls.has_key((obj_class, avc_type)): + if (obj_class, avc_type) in cls: access = cls[obj_class, avc_type] else: access = AccessVector()
@@ -294,7 +294,7 @@ def avs_extract_types(avs): def avs_extract_obj_perms(avs): perms = { } for av in avs: - if perms.has_key(av.obj_class): + if av.obj_class in perms: s = perms[av.obj_class] else: s = refpolicy.IdSet()
@@ -322,7 +322,7 @@ class RoleTypeSet: return len(self.role_types.keys()) def add(self, role, type): - if self.role_types.has_key(role): + if role in self.role_types: role_type = self.role_types[role] else: role_type = refpolicy.RoleType()
sepolgen/src/sepolgen/audit.py +1 -1
@@ -430,7 +430,7 @@ class AuditParser: # Group by audit header if msg.header != "": - if self.by_header.has_key(msg.header): + if msg.header in self.by_header: self.by_header[msg.header].append(msg) else: self.by_header[msg.header] = [msg]
sepolgen/src/sepolgen/classperms.py +3 -3
@@ -49,7 +49,7 @@ def t_NAME(t): return t def t_error(t): - print "Illegal character '%s'" % t.value[0] + print("Illegal character '%s'" % t.value[0]) t.skip(1) from . import lex
@@ -90,7 +90,7 @@ def p_names(p): p[0] = [p[1]] + p[2] def p_error(p): - print "Syntax error on line %d %s [type=%s]" % (p.lineno, p.value, p.type) + print("Syntax error on line %d %s [type=%s]" % (p.lineno, p.value, p.type)) from . import yacc yacc.yacc()
@@ -112,5 +112,5 @@ test2 = """define(`all_filesystem_perms',`{ mount remount unmount getattr relabe define(`all_security_perms',`{ compute_av compute_create compute_member check_context load_policy compute_relabel compute_user setenforce setbool setsecparam setcheckreqprot }') """ result = yacc.parse(txt) -print result +print(result)
sepolgen/src/sepolgen/defaults.py +2 -2
@@ -36,14 +36,14 @@ class PathChoooser(object): if ignore.match(line): continue mo = consider.match(line) if not mo: - raise ValueError, "%s:%d: line is not in key = value format" % (pathname, lineno+1) + raise ValueError("%s:%d: line is not in key = value format" % (pathname, lineno+1)) self.config[mo.group(1)] = mo.group(2) # We're only exporting one useful function, so why not be a function def __call__(self, testfilename, pathset="SELINUX_DEVEL_PATH"): paths = self.config.get(pathset, None) if paths is None: - raise ValueError, "%s was not in %s" % (pathset, self.config_pathname) + raise ValueError("%s was not in %s" % (pathset, self.config_pathname)) paths = paths.split(":") for p in paths: target = os.path.join(p, testfilename)
sepolgen/src/sepolgen/interfaces.py +1 -1
@@ -276,7 +276,7 @@ class InterfaceVector: if attributes: for typeattribute in interface.typeattributes(): for attr in typeattribute.attributes: - if not attributes.attributes.has_key(attr): + if attr not in attributes.attributes: # print "missing attribute " + attr continue attr_vec = attributes.attributes[attr]
sepolgen/src/sepolgen/lex.py +62 -61
359 lines not on this page · raw message
sepolgen/src/sepolgen/module.py +5 -3
@@ -24,10 +24,12 @@ of module tress. import re import tempfile -import commands +try: + from subprocess import getstatusoutput +except ImportError: + from commands import getstatusoutput import os import os.path -import subprocess import shutil import selinux
@@ -131,7 +133,7 @@ class ModuleCompiler: def run(self, command): self.o(command) - rc, output = commands.getstatusoutput(command) + rc, output = getstatusoutput(command) self.o(output) return rc
sepolgen/src/sepolgen/objectmodel.py +1 -1
@@ -118,7 +118,7 @@ class PermMappings: continue if fields[0] == "class": c = fields[1] - if self.classes.has_key(c): + if c in self.classes: raise ValueError("duplicate class in perm map") self.classes[c] = { } cur = self.classes[c]
sepolgen/src/sepolgen/policygen.py +3 -3
@@ -170,7 +170,7 @@ class PolicyGenerator: if av.type == audit2why.BOOLEAN: if len(av.data) > 1: - rule.comment += "\n#!!!! This avc can be allowed using one of the these booleans:\n# %s" % ", ".join(map(lambda x: x[0], av.data)) + rule.comment += "\n#!!!! This avc can be allowed using one of the these booleans:\n# %s" % ", ".join([x[0] for x in av.data]) else: rule.comment += "\n#!!!! This avc can be allowed using the boolean '%s'" % av.data[0][0]
@@ -189,7 +189,7 @@ class PolicyGenerator: self.domains = seinfo(ATTRIBUTE, name="domain")[0]["types"] types=[] - for i in map(lambda x: x[TCONTEXT], sesearch([ALLOW], {SCONTEXT: av.src_type, CLASS: av.obj_class, PERMS: av.perms})): + for i in [x[TCONTEXT] for x in sesearch([ALLOW], {SCONTEXT: av.src_type, CLASS: av.obj_class, PERMS: av.perms})]: if i not in self.domains: types.append(i) if len(types) == 1:
@@ -299,7 +299,7 @@ def call_interface(interface, av): elif params[i].type == refpolicy.OBJ_CLASS: ifcall.args.append(av.obj_class) else: - print params[i].type + print(params[i].type) assert(0) assert(len(ifcall.args) > 0)
sepolgen/src/sepolgen/refparser.py +6 -6
@@ -268,7 +268,7 @@ def t_comment(t): t.lexer.lineno += 1 def t_error(t): - print "Illegal character '%s'" % t.value[0] + print("Illegal character '%s'" % t.value[0]) t.skip(1) def t_newline(t):
@@ -970,7 +970,7 @@ def p_optional_semi(p): def p_error(tok): global error, parse_file, success, parser error = "%s: Syntax error on line %d %s [type=%s]" % (parse_file, tok.lineno, tok.value, tok.type) - print error + print(error) success = False def prep_spt(spt):
@@ -1007,7 +1007,7 @@ def parse(text, module=None, support=None, debug=False): try: parser.parse(text, debug=debug, lexer=lexer) - except Exception, e: + except Exception as e: parser = None lexer = None error = "internal parser error: %s" % str(e) + "\n" + traceback.format_exc()
@@ -1074,9 +1074,9 @@ def parse_headers(root, output=None, expand=True, debug=False): fd.close() parse_file = f parse(txt, module, spt, debug) - except IOError, e: + except IOError as e: return - except ValueError, e: + except ValueError as e: raise ValueError("error parsing file %s: %s" % (f, str(e))) spt = None
@@ -1112,7 +1112,7 @@ def parse_headers(root, output=None, expand=True, debug=False): parse_file(x[1], m, spt) else: parse_file(x[1], m) - except ValueError, e: + except ValueError as e: o(str(e) + "\n") failures.append(x[1]) continue
sepolgen/src/sepolgen/refpolicy.py +19 -20
@@ -18,7 +18,6 @@ # import string -import itertools import selinux # OVERVIEW
@@ -85,53 +84,53 @@ class Node(PolicyBase): # Top level nodes def nodes(self): - return itertools.ifilter(lambda x: isinstance(x, Node), walktree(self)) + return filter(lambda x: isinstance(x, Node), walktree(self)) def modules(self): - return itertools.ifilter(lambda x: isinstance(x, Module), walktree(self)) + return filter(lambda x: isinstance(x, Module), walktree(self)) def interfaces(self): - return itertools.ifilter(lambda x: isinstance(x, Interface), walktree(self)) + return filter(lambda x: isinstance(x, Interface), walktree(self)) def templates(self): - return itertools.ifilter(lambda x: isinstance(x, Template), walktree(self)) + return filter(lambda x: isinstance(x, Template), walktree(self)) def support_macros(self): - return itertools.ifilter(lambda x: isinstance(x, SupportMacros), walktree(self)) + return filter(lambda x: isinstance(x, SupportMacros), walktree(self)) # Common policy statements def module_declarations(self): - return itertools.ifilter(lambda x: isinstance(x, ModuleDeclaration), walktree(self)) + return filter(lambda x: isinstance(x, ModuleDeclaration), walktree(self)) def interface_calls(self): - return itertools.ifilter(lambda x: isinstance(x, InterfaceCall), walktree(self)) + return filter(lambda x: isinstance(x, InterfaceCall), walktree(self)) def avrules(self): - return itertools.ifilter(lambda x: isinstance(x, AVRule), walktree(self)) + return filter(lambda x: isinstance(x, AVRule), walktree(self)) def typerules(self): - return itertools.ifilter(lambda x: isinstance(x, TypeRule), walktree(self)) + return filter(lambda x: isinstance(x, TypeRule), walktree(self)) def typeattributes(self): """Iterate over all of the TypeAttribute children of this Interface.""" - return itertools.ifilter(lambda x: isinstance(x, TypeAttribute), walktree(self)) + return filter(lambda x: isinstance(x, TypeAttribute), walktree(self)) def roleattributes(self): """Iterate over all of the RoleAttribute children of this Interface.""" - return itertools.ifilter(lambda x: isinstance(x, RoleAttribute), walktree(self)) + return filter(lambda x: isinstance(x, RoleAttribute), walktree(self)) def requires(self): - return itertools.ifilter(lambda x: isinstance(x, Require), walktree(self)) + return filter(lambda x: isinstance(x, Require), walktree(self)) def roles(self): - return itertools.ifilter(lambda x: isinstance(x, Role), walktree(self)) + return filter(lambda x: isinstance(x, Role), walktree(self)) def role_allows(self): - return itertools.ifilter(lambda x: isinstance(x, RoleAllow), walktree(self)) + return filter(lambda x: isinstance(x, RoleAllow), walktree(self)) def role_types(self): - return itertools.ifilter(lambda x: isinstance(x, RoleType), walktree(self)) + return filter(lambda x: isinstance(x, RoleType), walktree(self)) def __str__(self): if self.comment:
@@ -291,7 +290,7 @@ class SecurityContext(Leaf): self.type = fields[2] if len(fields) > 3: # FUTURE - normalize level fields to allow more comparisons to succeed. - self.level = string.join(fields[3:], ':') + self.level = ':'.join(fields[3:]) else: self.level = None
@@ -703,7 +702,7 @@ def print_tree(head): s = "" for i in range(depth): s = s + "\t" - print s + str(node) + print(s + str(node)) class Headers(Node):
@@ -810,7 +809,7 @@ class SupportMacros(Node): # are ordered correctly so that no macro is used before # it is defined s = set() - if self.map.has_key(perm): + if perm in self.map: for p in self.by_name(perm): s.update(self.__expand_perm(p)) else:
@@ -833,7 +832,7 @@ class SupportMacros(Node): def has_key(self, name): if not self.map: self.__gen_map() - return self.map.has_key(name) + return name in self.map class Require(Leaf): def __init__(self, parent=None):
sepolgen/src/sepolgen/yacc.py +76 -73
483 lines not on this page · raw message
Signature · 1 line
2.4.3
PATCH 10/11 sepolgen: Close files after reading/writing in tests.
In reply to Robert Kuska--- sepolgen/tests/test_audit.py | 1 + sepolgen/tests/test_interfaces.py | 1 + sepolgen/tests/test_objectmodel.py | 1 + 3 files changed, 3 insertions(+)
sepolgen/tests/test_audit.py +1 -0
@@ -166,6 +166,7 @@ class TestAuditParser(unittest.TestCase): f = open("audit.txt") a = sepolgen.audit.AuditParser() a.parse_file(f) + f.close() self.assertEqual(len(a.avc_msgs), 21) self.assertEqual(len(a.compute_sid_msgs), 0) self.assertEqual(len(a.invalid_msgs), 0)
sepolgen/tests/test_interfaces.py +1 -0
@@ -268,6 +268,7 @@ class TestInterfaceSet(unittest.TestCase): i2 = interfaces.InterfaceSet() f = open("output") i2.from_file(f) + f.close() if_status = [False, False, False] for ifv in i2.interfaces.values(): if ifv.name == "files_search_usr":
sepolgen/tests/test_objectmodel.py +1 -0
@@ -25,6 +25,7 @@ class TestInfoFlow(unittest.TestCase): info = sepolgen.objectmodel.PermMappings() fd = open("perm_map") info.from_file(fd) + fd.close() pm = info.get("filesystem", "mount") self.assertEqual(pm.perm, "mount")
Signature · 1 line
2.4.3
PATCH 11/11 sepolgen: Edit tests so they pass even on Python3 where hash is random.
In reply to Robert KuskaBy default in Python3 hash uses random seed as salt, this leads to different order in output from functions which rely on hash as are dicts and sets. Tests in sepolgen relied on the frozen order.
--- sepolgen/tests/test_access.py | 34 +++++++++++++++++++++++++++------- sepolgen/tests/test_refpolicy.py | 13 ++++++++++--- 2 files changed, 37 insertions(+), 10 deletions(-)
sepolgen/tests/test_access.py +27 -7
@@ -72,8 +72,10 @@ class TestAccessVector(unittest.TestCase): self.assertEqual(l[0], "foo") self.assertEqual(l[1], "bar") self.assertEqual(l[2], "file") - self.assertEqual(l[3], "read") - self.assertEqual(l[4], "write") + perms = l[3:] + perms.sort() + self.assertEqual(perms[0], "read") + self.assertEqual(perms[1], "write") def test_to_string(self): a = access.AccessVector()
@@ -82,8 +84,21 @@ class TestAccessVector(unittest.TestCase): a.obj_class = "file" a.perms.update(["read", "write"]) - self.assertEqual(str(a), "allow foo bar:file { read write };") - self.assertEqual(a.to_string(), "allow foo bar:file { read write };") + first, second = str(a).split(':') + self.assertEqual(first, "allow foo bar") + second = second.split(' ') + second.sort() + expected = "file { read write };".split(' ') + expected.sort() + self.assertEqual(second, expected) + + first, second = a.to_string().split(':') + self.assertEqual(first, "allow foo bar") + second = second.split(' ') + second.sort() + expected = "file { read write };".split(' ') + expected.sort() + self.assertEqual(second, expected) def test_cmp(self): a = access.AccessVector()
@@ -127,11 +142,9 @@ class TestAccessVector(unittest.TestCase): b.perms = refpolicy.IdSet(["read", "write", "append"]) self.assertNotEqual(a, b) - self.assertTrue(a < b) b.perms = refpolicy.IdSet(["read", "append"]) self.assertNotEqual(a, b) - self.assertTrue(a > b) class TestUtilFunctions(unittest.TestCase): def test_is_idparam(self):
@@ -227,15 +240,22 @@ class TestAccessVectorSet(unittest.TestCase): a.add("what", "bar", "file", refpolicy.IdSet(["read", "write"])) avl = a.to_list() + avl.sort() test_l = [['what','bar','file','read','write'], ['$1','foo','file','read','write'], ['$1','bar','file','read','write']] + test_l.sort() for a,b in zip(test_l, avl): self.assertEqual(len(a), len(b)) - for x,y in zip(a,b): + for x,y in list(zip(a,b))[:3]: self.assertEqual(x, y) + perms1 = a[3:] + perms2 = b[3:] + perms1.sort() + perms2.sort() + self.assertEqual(perms1, perms2) b = access.AccessVectorSet() b.from_list(avl)
sepolgen/tests/test_refpolicy.py +10 -3
@@ -24,7 +24,11 @@ import selinux class TestIdSet(unittest.TestCase): def test_set_to_str(self): s = refpolicy.IdSet(["read", "write", "getattr"]) - self.assertEqual(s.to_space_str(), "{ read write getattr }") + s = s.to_space_str().split(' ') + s.sort() + expected = "{ read write getattr }".split(' ') + expected.sort() + self.assertEqual(s, expected) s = refpolicy.IdSet() s.add("read") self.assertEqual(s.to_space_str(), "read")
@@ -100,8 +104,11 @@ class TestAVRule(unittest.TestCase): a.obj_classes.add("lnk_file") a.perms.add("write") # This test might need to go because set ordering is not guaranteed - self.assertEqual(a.to_string(), - "dontaudit { foo_t user_t } { user_home_t bar_t }:{ lnk_file file } { read write };") + a = a.to_string().split(' ') + a.sort() + b = "dontaudit { foo_t user_t } { user_home_t bar_t }:{ lnk_file file } { read write };".split(' ') + b.sort() + self.assertEqual(a, b) class TestTypeRule(unittest.TestCase): def test_init(self):
Signature · 1 line
2.4.3
Re: Python3 Support for Sepolgen module
In reply to Robert Kuska----- Original Message -----
Quoted 5 lines
From: "Robert Kuska" <[email protected]>
To: [email protected]
Sent: Thursday, July 16, 2015 1:48:10 PMThese patches aims to bring Python3 support to sepolgen module.
Refering to 11 patches I've sent.
Quoted 11 lines
They're made from the patch I've sent earlier which was a little bit big for a single review so I cut it into smaller patches.
_______________________________________________
Selinux mailing list
[email protected]
To unsubscribe, send email to [email protected]. To get help, send an email containing "help" to [email protected].
Looks like I messed up the --compose option of git send-email.
--
Robert Kuska
{rkuska}
Stephen Smalley
AppliedRe: Python3 Support for Sepolgen module
Quoted 10 lines · Robert Kuska
----- Original Message -----
Quoted 5 lines
From: "Robert Kuska" <[email protected]>
To: [email protected]
Sent: Thursday, July 16, 2015 1:48:10 PMThese patches aims to bring Python3 support to sepolgen module.
Refering to 11 patches I've sent.
Thanks, applied.
Re: Python3 Support for Sepolgen module
In reply to Robert KuskaQuoted 10 lines · Robert Kuska
----- Original Message -----
Quoted 5 lines
From: "Robert Kuska" <[email protected]>
To: [email protected]
Sent: Thursday, July 16, 2015 1:48:10 PMThese patches aims to bring Python3 support to sepolgen module.
Refering to 11 patches I've sent.
I read through all these patches, they all looked pretty reasonable. I tested it on gentoo, there were no problems building or anything but I keep hitting policycoreutils py3 issues so actually using semanage doesnt fully work yet.
How much progress do you have on porting policycoreutils? There are a lot of mismatched tabs/spaces in it which are causing problems in python3 and I havent gotten further yet. I started looking at fixing up these but if you've already done it then there is no point in me re-doing it.
-- Jason
Quoted 24 lines
Quoted 11 lines
They're made from the patch I've sent earlier which was a little bit big for a single review so I cut it into smaller patches.
_______________________________________________
Selinux mailing list
[email protected]
To unsubscribe, send email to [email protected]. To get help, send an email containing "help" to [email protected].Looks like I messed up the --compose option of git send-email.
--
Robert Kuska
{rkuska}
_______________________________________________
Selinux mailing list
[email protected]
To unsubscribe, send email to [email protected].
To get help, send an email containing "help" to [email protected].
Re: Python3 Support for Sepolgen module
----- Original Message -----
Quoted 23 lines
From: "Jason Zaman" <[email protected]>
To: "Robert Kuska" <[email protected]>
Cc: [email protected]
Sent: Friday, July 17, 2015 12:16:05 AM
Subject: Re: Python3 Support for Sepolgen moduleQuoted 10 lines · Robert Kuska
----- Original Message -----
Quoted 5 lines
From: "Robert Kuska" <[email protected]>
To: [email protected]
Sent: Thursday, July 16, 2015 1:48:10 PMThese patches aims to bring Python3 support to sepolgen module.
Refering to 11 patches I've sent.
I read through all these patches, they all looked pretty reasonable. I tested it on gentoo, there were no problems building or anything but I keep hitting policycoreutils py3 issues so actually using semanage doesnt fully work yet.
Quoted 5 lines
How much progress do you have on porting policycoreutils? There are a lot of mismatched tabs/spaces in it which are causing problems in python3 and I havent gotten further yet. I started looking at fixing up these but if you've already done it then there is no point in me re-doing it.
Sepolgen should be done.
There are still scripts which we already got ported and will be here for a review soon:
Quoted 1 line
$ rpm -ql policycoreutils-python | grep bin [±master ●▴]
/usr/bin/audit2allow/usr/bin/audit2why/usr/bin/chcat/usr/bin/sandbox/usr/bin/semodule_package/usr/sbin/semanage
Am I missing something?
Quoted 29 lines
-- Jason
Quoted 25 lines
Quoted 11 lines
They're made from the patch I've sent earlier which was a little bit big for a single review so I cut it into smaller patches.
_______________________________________________
Selinux mailing list
[email protected]
To unsubscribe, send email to [email protected]. To get help, send an email containing "help" to [email protected].Looks like I messed up the --compose option of git send-email.
--
Robert Kuska
{rkuska}
_______________________________________________
Selinux mailing list
[email protected]
To unsubscribe, send email to [email protected]. To get help, send an email containing "help" to [email protected].
--
Robert Kuska
{rkuska}
Re: Python3 Support for Sepolgen module
Quoted 10 lines · Robert Kuska
Quoted 5 lines
How much progress do you have on porting policycoreutils? There are a lot of mismatched tabs/spaces in it which are causing problems in python3 and I havent gotten further yet. I started looking at fixing up these but if you've already done it then there is no point in me re-doing it.
Sepolgen should be done.
There are still scripts which we already got ported and will be here for a review soon:
Quoted 1 line
$ rpm -ql policycoreutils-python | grep bin [±master ●▴]
Quoted 8 lines
/usr/bin/audit2allow/usr/bin/audit2why/usr/bin/chcat/usr/bin/sandbox/usr/bin/semodule_package/usr/sbin/semanageAm I missing something?
When I tried running semanage with python3, it needed a few more too:/usr/lib64/python*/site-packages/sepolicy/* /usr/lib64/python*/site-packages/seobject.py
I look forward to testing the rest of your patches :) -- Jason
Re: Python3 Support for Sepolgen module
----- Original Message -----
Quoted 26 lines
From: "Jason Zaman" <[email protected]>
To: "Robert Kuska" <[email protected]>
Cc: [email protected]
Sent: Friday, July 17, 2015 8:58:02 AM
Subject: Re: Python3 Support for Sepolgen moduleQuoted 19 lines · Robert Kuska
Quoted 5 lines
How much progress do you have on porting policycoreutils? There are a lot of mismatched tabs/spaces in it which are causing problems in python3 and I havent gotten further yet. I started looking at fixing up these but if you've already done it then there is no point in me re-doing it.
Sepolgen should be done.
There are still scripts which we already got ported and will be here for a review soon:
Quoted 2 lines
$ rpm -ql policycoreutils-python | grep bin [±master ●▴]
/usr/bin/audit2allow/usr/bin/audit2why/usr/bin/chcat/usr/bin/sandbox/usr/bin/semodule_package/usr/sbin/semanage
Quoted 9 lines
Quoted 1 line
Am I missing something?
When I tried running semanage with python3, it needed a few more too:
/usr/lib64/python*/site-packages/sepolicy/*/usr/lib64/python*/site-packages/seobject.pyI look forward to testing the rest of your patches :) -- Jason
I cc Petr in case he missed this mail.
Looking at policycoreutils-python3 it seems to me that sepolicy and seobject are already ported.
Quoted 1 line
$ rpm -ql policycoreutils-python3 | grep seobject [±master ●▴]
/usr/lib/python3.4/site-packages/seobject /usr/lib/python3.4/site-packages/seobject-0.1-py3.4.egg-info /usr/lib/python3.4/site-packages/seobject/__init__.py /usr/lib/python3.4/site-packages/seobject/__pycache__/__init__.cpython-34.pyc /usr/lib/python3.4/site-packages/seobject/__pycache__/__init__.cpython-34.pyo
Quoted 1 line
$ rpm -ql policycoreutils-python3 | grep sepolicy [±master ●▴]
/usr/lib64/python3.4/site-packages/sepolicy /usr/lib64/python3.4/site-packages/sepolicy-1.1-py3.4.egg-info /usr/lib64/python3.4/site-packages/sepolicy/__init__.py /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/__init__.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/__init__.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/booleans.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/booleans.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/communicate.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/communicate.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/generate.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/generate.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/gui.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/gui.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/interface.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/interface.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/manpage.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/manpage.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/network.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/network.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/sedbus.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/sedbus.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/transition.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/__pycache__/transition.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/booleans.py /usr/lib64/python3.4/site-packages/sepolicy/communicate.py /usr/lib64/python3.4/site-packages/sepolicy/help /usr/lib64/python3.4/site-packages/sepolicy/help/__init__.py /usr/lib64/python3.4/site-packages/sepolicy/help/__pycache__ /usr/lib64/python3.4/site-packages/sepolicy/help/__pycache__/__init__.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/help/__pycache__/__init__.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/help/booleans.png /usr/lib64/python3.4/site-packages/sepolicy/help/booleans.txt /usr/lib64/python3.4/site-packages/sepolicy/help/booleans_more.png /usr/lib64/python3.4/site-packages/sepolicy/help/booleans_more.txt /usr/lib64/python3.4/site-packages/sepolicy/help/booleans_more_show.png /usr/lib64/python3.4/site-packages/sepolicy/help/booleans_more_show.txt /usr/lib64/python3.4/site-packages/sepolicy/help/booleans_toggled.png /usr/lib64/python3.4/site-packages/sepolicy/help/booleans_toggled.txt /usr/lib64/python3.4/site-packages/sepolicy/help/file_equiv.png /usr/lib64/python3.4/site-packages/sepolicy/help/file_equiv.txt /usr/lib64/python3.4/site-packages/sepolicy/help/files_apps.png /usr/lib64/python3.4/site-packages/sepolicy/help/files_apps.txt /usr/lib64/python3.4/site-packages/sepolicy/help/files_exec.png /usr/lib64/python3.4/site-packages/sepolicy/help/files_exec.txt /usr/lib64/python3.4/site-packages/sepolicy/help/files_write.png /usr/lib64/python3.4/site-packages/sepolicy/help/files_write.txt /usr/lib64/python3.4/site-packages/sepolicy/help/lockdown.png /usr/lib64/python3.4/site-packages/sepolicy/help/lockdown.txt /usr/lib64/python3.4/site-packages/sepolicy/help/lockdown_permissive.png /usr/lib64/python3.4/site-packages/sepolicy/help/lockdown_permissive.txt /usr/lib64/python3.4/site-packages/sepolicy/help/lockdown_ptrace.png /usr/lib64/python3.4/site-packages/sepolicy/help/lockdown_ptrace.txt /usr/lib64/python3.4/site-packages/sepolicy/help/lockdown_unconfined.png /usr/lib64/python3.4/site-packages/sepolicy/help/lockdown_unconfined.txt /usr/lib64/python3.4/site-packages/sepolicy/help/login.png /usr/lib64/python3.4/site-packages/sepolicy/help/login.txt /usr/lib64/python3.4/site-packages/sepolicy/help/login_default.png /usr/lib64/python3.4/site-packages/sepolicy/help/login_default.txt /usr/lib64/python3.4/site-packages/sepolicy/help/ports_inbound.png /usr/lib64/python3.4/site-packages/sepolicy/help/ports_inbound.txt /usr/lib64/python3.4/site-packages/sepolicy/help/ports_outbound.png /usr/lib64/python3.4/site-packages/sepolicy/help/ports_outbound.txt /usr/lib64/python3.4/site-packages/sepolicy/help/start.png /usr/lib64/python3.4/site-packages/sepolicy/help/start.txt /usr/lib64/python3.4/site-packages/sepolicy/help/system.png /usr/lib64/python3.4/site-packages/sepolicy/help/system.txt /usr/lib64/python3.4/site-packages/sepolicy/help/system_boot_mode.png /usr/lib64/python3.4/site-packages/sepolicy/help/system_boot_mode.txt /usr/lib64/python3.4/site-packages/sepolicy/help/system_current_mode.png /usr/lib64/python3.4/site-packages/sepolicy/help/system_current_mode.txt /usr/lib64/python3.4/site-packages/sepolicy/help/system_export.png /usr/lib64/python3.4/site-packages/sepolicy/help/system_export.txt /usr/lib64/python3.4/site-packages/sepolicy/help/system_policy_type.png /usr/lib64/python3.4/site-packages/sepolicy/help/system_policy_type.txt /usr/lib64/python3.4/site-packages/sepolicy/help/system_relabel.png /usr/lib64/python3.4/site-packages/sepolicy/help/system_relabel.txt /usr/lib64/python3.4/site-packages/sepolicy/help/transition_file.png /usr/lib64/python3.4/site-packages/sepolicy/help/transition_file.txt /usr/lib64/python3.4/site-packages/sepolicy/help/transition_from.png /usr/lib64/python3.4/site-packages/sepolicy/help/transition_from.txt /usr/lib64/python3.4/site-packages/sepolicy/help/transition_from_boolean.png /usr/lib64/python3.4/site-packages/sepolicy/help/transition_from_boolean.txt /usr/lib64/python3.4/site-packages/sepolicy/help/transition_from_boolean_1.png /usr/lib64/python3.4/site-packages/sepolicy/help/transition_from_boolean_1.txt /usr/lib64/python3.4/site-packages/sepolicy/help/transition_from_boolean_2.png /usr/lib64/python3.4/site-packages/sepolicy/help/transition_from_boolean_2.txt /usr/lib64/python3.4/site-packages/sepolicy/help/transition_to.png /usr/lib64/python3.4/site-packages/sepolicy/help/transition_to.txt /usr/lib64/python3.4/site-packages/sepolicy/help/users.png /usr/lib64/python3.4/site-packages/sepolicy/help/users.txt /usr/lib64/python3.4/site-packages/sepolicy/interface.py /usr/lib64/python3.4/site-packages/sepolicy/manpage.py /usr/lib64/python3.4/site-packages/sepolicy/network.py /usr/lib64/python3.4/site-packages/sepolicy/policy.cpython-34m.so /usr/lib64/python3.4/site-packages/sepolicy/sedbus.py /usr/lib64/python3.4/site-packages/sepolicy/templates /usr/lib64/python3.4/site-packages/sepolicy/templates/__init__.py /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__ /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/__init__.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/__init__.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/boolean.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/boolean.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/etc_rw.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/etc_rw.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/executable.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/executable.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/network.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/network.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/rw.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/rw.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/script.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/script.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/semodule.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/semodule.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/spec.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/spec.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/test_module.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/test_module.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/tmp.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/tmp.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/unit_file.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/unit_file.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/user.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/user.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_cache.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_cache.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_lib.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_lib.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_log.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_log.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_run.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_run.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_spool.cpython-34.pyc /usr/lib64/python3.4/site-packages/sepolicy/templates/__pycache__/var_spool.cpython-34.pyo /usr/lib64/python3.4/site-packages/sepolicy/templates/boolean.py /usr/lib64/python3.4/site-packages/sepolicy/templates/etc_rw.py /usr/lib64/python3.4/site-packages/sepolicy/templates/executable.py /usr/lib64/python3.4/site-packages/sepolicy/templates/network.py /usr/lib64/python3.4/site-packages/sepolicy/templates/rw.py /usr/lib64/python3.4/site-packages/sepolicy/templates/script.py /usr/lib64/python3.4/site-packages/sepolicy/templates/semodule.py /usr/lib64/python3.4/site-packages/sepolicy/templates/spec.py /usr/lib64/python3.4/site-packages/sepolicy/templates/test_module.py /usr/lib64/python3.4/site-packages/sepolicy/templates/tmp.py /usr/lib64/python3.4/site-packages/sepolicy/templates/unit_file.py /usr/lib64/python3.4/site-packages/sepolicy/templates/user.py /usr/lib64/python3.4/site-packages/sepolicy/templates/var_cache.py /usr/lib64/python3.4/site-packages/sepolicy/templates/var_lib.py /usr/lib64/python3.4/site-packages/sepolicy/templates/var_log.py /usr/lib64/python3.4/site-packages/sepolicy/templates/var_run.py /usr/lib64/python3.4/site-packages/sepolicy/templates/var_spool.py
--
Robert Kuska
{rkuska}
--
Robert Kuska
{rkuska}
Re: Python3 Support for Sepolgen module
Quoted 35 lines · Robert Kuska
----- Original Message -----
Quoted 32 lines
From: "Jason Zaman" <[email protected]>
To: "Robert Kuska" <[email protected]>
Cc: [email protected]
Sent: Friday, July 17, 2015 8:58:02 AM
Subject: Re: Python3 Support for Sepolgen moduleQuoted 12 lines · Robert Kuska
Quoted 5 lines
How much progress do you have on porting policycoreutils? There are a lot of mismatched tabs/spaces in it which are causing problems in python3 and I havent gotten further yet. I started looking at fixing up these but if you've already done it then there is no point in me re-doing it.
Sepolgen should be done.
There are still scripts which we already got ported and will be here for a review soon:
Quoted 2 lines
$ rpm -ql policycoreutils-python | grep bin [±master ●▴]Quoted 8 lines
/usr/bin/audit2allow/usr/bin/audit2why/usr/bin/chcat/usr/bin/sandbox/usr/bin/semodule_package/usr/sbin/semanageAm I missing something?
When I tried running semanage with python3, it needed a few more too:
/usr/lib64/python*/site-packages/sepolicy/*/usr/lib64/python*/site-packages/seobject.py
Quoted 8 lines
Quoted 3 lines
I look forward to testing the rest of your patches :) -- Jason
I cc Petr in case he missed this mail.
Looking at policycoreutils-python3 it seems to me that sepolicy and seobject are already ported.
Hmm I suspect thats not right cuz I kept getting errors when using it. When I looked through as well, I saw lots of places where print() needs to be fixed as well as "except Error, e" and quite a lot of mixed tabs and spaces. 2to3 can fix most of that automatically tho.
As far as actual incompatibilities, I only saw a few issues with subcommand / process and str / unicode for internationalization so it should be pretty easy to fix up.
-- Jason
Re: Python3 Support for Sepolgen module
Quoted 8 lines · Jason Zaman
Quoted 1 line · Robert Kuska
Looking at policycoreutils-python3 it seems to me that sepolicy and seobject are already ported.
Hmm I suspect thats not right cuz I kept getting errors when using it. When I looked through as well, I saw lots of places where
print()needs to be fixed as well as "except Error, e" and quite a lot of mixed tabs and spaces. 2to3 can fix most of that automatically tho.
Quoted 5 lines
As far as actual incompatibilities, I only saw a few issues with subcommand / process and str / unicode for internationalization so it should be pretty easy to fix up.
-- Jason
I keep hitting this with python3, it seems to be much stricter than py2:
# semanage boolean -l
Traceback (most recent call last):
File "/usr/lib/python-exec/python3.3/semanage", line 27, in <module>
import seobject
File "/usr/lib64/python3.3/site-packages/seobject.py", line 154
context = "%s%s" % (filler, raw)
^
TabError: inconsistent use of tabs and spaces in indentationI want to fix all the whitespace and other style issues in one big pull request. Will it cause big problems for your porting? The upside is that it's only a one time issue for the repo.
If there are no objections, I'll send a pull request with the fix shortly. It is too big for an inline patch.
-- Jason
Re: Python3 Support for Sepolgen module
Quoted 11 lines · Jason Zaman
I keep hitting this with python3, it seems to be much stricter than py2:
# semanage boolean -l Traceback (most recent call last): File "/usr/lib/python-exec/python3.3/semanage", line 27, in <module> import seobject File "/usr/lib64/python3.3/site-packages/seobject.py", line 154 context = "%s%s" % (filler, raw) ^ TabError: inconsistent use of tabs and spaces in indentation
Quoted 6 lines
I want to fix all the whitespace and other style issues in one big pull request. Will it cause big problems for your porting? The upside is that it's only a one time issue for the repo.
If there are no objections, I'll send a pull request with the fix shortly. It is too big for an inline patch.
Hi Jason,
I am preparing patches for adding python3 support to scripts under policycoreutils/. No objections from me, please go ahead and apply your changes. I can rebase my patches, if there are any problems.
Regards
Michal
Quoted 7 lines
-- Jason
_______________________________________________
Selinux mailing list
[email protected]
To unsubscribe, send email to [email protected].
To get help, send an email containing "help" to [email protected].