diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml new file mode 100644 index 0000000..efc2167 --- /dev/null +++ b/.github/workflows/build.yaml @@ -0,0 +1,85 @@ +name: Build & Test +on: + push: + branches: + - main + tags: + - "v*" + pull_request: + +jobs: + build-and-test: + runs-on: ubuntu-20.04 + strategy: + matrix: + python-version: + - "3.7" + - "3.8" + - "3.9" + - "3.10" + - "3.11" + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Build package + run: | + python -m pip install --upgrade build twine + python -m build + twine check --strict dist/* + - name: Install coveralls + run: sudo pip install coveralls + - name: Run tests + run: sudo PATH=$PATH coverage run setup.py test + + release: + runs-on: ubuntu-20.04 + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') + needs: + - build-and-test + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.x" + - name: Build package + run: | + python -m pip install --upgrade build twine + python -m build + twine check --strict dist/* + rm -f dist/*.whl + - name: Publish package + uses: pypa/gh-action-pypi-publish@release/v1 + with: + user: __token__ + password: ${{ secrets.PYPI_API_TOKEN }} + - name: Create GitHub release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: ${{ github.ref }} + draft: false + prerelease: false + - name: Set asset name + run: | + export PKG=$(ls dist/ | grep tar) + set -- $PKG + echo "name=$1" >> $GITHUB_ENV + - name: Upload release asset to GitHub + id: upload-release-asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: dist/${{ env.name }} + asset_name: ${{ env.name }} + asset_content_type: application/zip diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index e7f9a8c..0000000 --- a/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -dist: xenial -language: python -python: - - "2.7" - - "3.4" - - "3.5" - - "3.6" - - "3.7" -install: - - python setup.py build - - python setup.py install - - sudo pip install coveralls -script: - - sudo PATH=$PATH coverage run setup.py test -after_success: - coveralls diff --git a/README.md b/README.md old mode 100755 new mode 100644 diff --git a/doc/conf.py b/doc/conf.py index 6abeedf..ea780c0 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -196,6 +196,6 @@ # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {'http://docs.python.org/': None} +intersphinx_mapping = {'python': ('http://docs.python.org/', None)} autoclass_content="both" diff --git a/iptc/ip4tc.py b/iptc/ip4tc.py index 4c5d690..90f5ee7 100644 --- a/iptc/ip4tc.py +++ b/iptc/ip4tc.py @@ -9,7 +9,7 @@ import struct import weakref -from .util import find_library, load_kernel +from .util import find_library, load_kernel, find_libc from .xtables import (XT_INV_PROTO, NFPROTO_IPV4, XTablesError, xtables, xt_align, xt_counters, xt_entry_target, xt_entry_match) @@ -26,7 +26,7 @@ _IFNAMSIZ = 16 -_libc = ct.CDLL("libc.so.6") +_libc = find_libc() _get_errno_loc = _libc.__errno_location _get_errno_loc.restype = ct.POINTER(ct.c_int) _malloc = _libc.malloc @@ -42,10 +42,14 @@ def is_table_available(name): try: + if name in Table.existing_table_names: + return Table.existing_table_names[name] Table(name) + Table.existing_table_names[name] = True return True except IPTCError: pass + Table.existing_table_names[name] = False return False @@ -669,6 +673,11 @@ class Target(IPTCModule): does not take any value in the iptables extension, an empty string i.e. "" should be used. """ + + STANDARD_TARGETS = ["", "ACCEPT", "DROP", "REJECT", "RETURN", "REDIRECT", "SNAT", "DNAT", \ + "MASQUERADE", "MIRROR", "TOS", "MARK", "QUEUE", "LOG"] + """This is the constant for all standard targets.""" + def __init__(self, rule, name=None, target=None, revision=None, goto=None): """ *rule* is the Rule object this match belongs to; it can be changed @@ -784,6 +793,8 @@ def _create_buffer(self, target): self.reset() def _is_standard_target(self): + if self._name in Target.STANDARD_TARGETS: + return False for t in self._rule.tables: if t.is_chain(self._name): return True @@ -1572,6 +1583,8 @@ class Table(object): """This is the constant for all tables.""" _cache = dict() + existing_table_names = dict() + """Dictionary to check faster if a table is available.""" def __new__(cls, name, autocommit=None): obj = Table._cache.get(name, None) diff --git a/iptc/ip6tc.py b/iptc/ip6tc.py index ed10e17..e0d8787 100644 --- a/iptc/ip6tc.py +++ b/iptc/ip6tc.py @@ -19,10 +19,14 @@ def is_table6_available(name): try: + if name in Table6.existing_table_names: + return Table6.existing_table_names[name] Table6(name) + Table6.existing_table_names[name] = True return True except IPTCError: pass + Table6.existing_table_names[name] = False return False @@ -412,22 +416,19 @@ def set_dst(self, dst): def get_in_interface(self): intf = "" if self.entry.ipv6.invflags & ip6t_ip6.IP6T_INV_VIA_IN: - intf = "".join(["!", intf]) - iface = bytearray(_IFNAMSIZ) - iface[:len(self.entry.ipv6.iniface)] = self.entry.ipv6.iniface - mask = bytearray(_IFNAMSIZ) - mask[:len(self.entry.ipv6.iniface_mask)] = self.entry.ipv6.iniface_mask - if mask[0] == 0: + intf = "!" + + iface = self.entry.ipv6.iniface.decode() + mask = self.entry.ipv6.iniface_mask + + if len(mask) == 0: return None - for i in range(_IFNAMSIZ): - if mask[i] != 0: - intf = "".join([intf, chr(iface[i])]) - else: - if iface[i - 1] != 0: - intf = "".join([intf, "+"]) - else: - intf = intf[:-1] - break + + intf += iface + if len(iface) == len(mask): + intf += '+' + intf = intf[:_IFNAMSIZ] + return intf def set_in_interface(self, intf): @@ -456,23 +457,19 @@ def set_in_interface(self, intf): def get_out_interface(self): intf = "" if self.entry.ipv6.invflags & ip6t_ip6.IP6T_INV_VIA_OUT: - intf = "".join(["!", intf]) - iface = bytearray(_IFNAMSIZ) - iface[:len(self.entry.ipv6.outiface)] = self.entry.ipv6.outiface - mask = bytearray(_IFNAMSIZ) - mask[:len(self.entry.ipv6.outiface_mask)] = \ - self.entry.ipv6.outiface_mask - if mask[0] == 0: + intf = "!" + + iface = self.entry.ipv6.outiface.decode() + mask = self.entry.ipv6.outiface_mask + + if len(mask) == 0: return None - for i in range(_IFNAMSIZ): - if mask[i] != 0: - intf = "".join([intf, chr(iface[i])]) - else: - if iface[i - 1] != 0: - intf = "".join([intf, "+"]) - else: - intf = intf[:-1] - break + + intf += iface + if len(iface) == len(mask): + intf += '+' + intf = intf[:_IFNAMSIZ] + return intf def set_out_interface(self, intf): @@ -579,6 +576,8 @@ class Table6(Table): """This is the constant for all tables.""" _cache = dict() + existing_table_names = dict() + """Dictionary to check faster if a table is available.""" def __new__(cls, name, autocommit=None): obj = Table6._cache.get(name, None) diff --git a/iptc/util.py b/iptc/util.py index ae5fb9b..6c1592c 100644 --- a/iptc/util.py +++ b/iptc/util.py @@ -3,7 +3,6 @@ import sys import ctypes import ctypes.util -from distutils.sysconfig import get_python_lib from itertools import product from subprocess import Popen, PIPE from sys import version_info @@ -14,6 +13,12 @@ def get_config_var(name): if name == 'SO': return '.so' raise Exception('Not implemented') +try: + from distutils.sysconfig import get_python_lib +except ModuleNotFoundError: + import sysconfig + def get_python_lib(): + return sysconfig.get_path("purelib") def _insert_ko(modprobe, modname): @@ -80,12 +85,19 @@ def _do_find_library(name): def _find_library(*names): + exts = [] if version_info >= (3, 3): - ext = get_config_var("EXT_SUFFIX") + exts.append(get_config_var("EXT_SUFFIX")) else: - ext = get_config_var('SO') + exts.append(get_config_var('SO')) + + if version_info >= (3, 5): + exts.append('.so') + for name in names: - libnames = [name, "lib" + name, name + ext, "lib" + name + ext] + libnames = [name, "lib" + name] + for ext in exts: + libnames += [name + ext, "lib" + name + ext] libdir = os.environ.get('IPTABLES_LIBDIR', None) if libdir is not None: libdirs = libdir.split(':') @@ -109,3 +121,19 @@ def find_library(*names): major = int(m.group(1)) return lib, major return None, None + + +def find_libc(): + lib = ctypes.util.find_library('c') + if lib is not None: + return ctypes.CDLL(lib, mode=ctypes.RTLD_GLOBAL) + + libnames = ['libc.so.6', 'libc.so.0', 'libc.so'] + for name in libnames: + try: + lib = ctypes.CDLL(name, mode=ctypes.RTLD_GLOBAL) + return lib + except: + pass + + return None diff --git a/iptc/version.py b/iptc/version.py index 1ded765..f6a5157 100644 --- a/iptc/version.py +++ b/iptc/version.py @@ -1,4 +1,4 @@ # -*- coding: utf-8 -*- __pkgname__ = "python-iptables" -__version__ = "0.15.0-dev" +__version__ = "1.2.0" diff --git a/iptc/xtables.py b/iptc/xtables.py index fafb6af..024779c 100644 --- a/iptc/xtables.py +++ b/iptc/xtables.py @@ -6,7 +6,7 @@ import weakref from . import version -from .util import find_library +from .util import find_library, find_libc from .errors import * XT_INV_PROTO = 0x40 # invert the sense of PROTO @@ -792,7 +792,7 @@ class xtables_target(ct.Union): ("v12", _xtables_target_v12)] -_libc, _ = find_library("c") +_libc = find_libc() _optind = ct.c_long.in_dll(_libc, "optind") _optarg = ct.c_char_p.in_dll(_libc, "optarg") @@ -805,7 +805,7 @@ class xtables_target(ct.Union): _xtables_libdir = os.getenv("XTABLES_LIBDIR") if _xtables_libdir is None: import re - ldconfig_path_regex = re.compile('^(/.*):$') + ldconfig_path_regex = re.compile('^(/.*):($| \(.*\)$)') import subprocess ldconfig = subprocess.Popen( ('/sbin/ldconfig', '-N', '-v'), @@ -1020,10 +1020,6 @@ def find_match(self, name): if ext is not None: return ext - xtables._xtables_matches.value = ct.c_void_p(None).value - if xtables._xtables_pending_matches: - xtables._xtables_pending_matches.value = ct.c_void_p(None).value - match = xtables._xtables_find_match(name, XTF_TRY_LOAD, None) if not match: self._try_register(name) @@ -1045,10 +1041,6 @@ def find_target(self, name): if ext is not None: return ext - xtables._xtables_targets.value = ct.c_void_p(None).value - if xtables._xtables_pending_targets: - xtables._xtables_pending_targets.value = ct.c_void_p(None).value - target = xtables._xtables_find_target(name, XTF_TRY_LOAD) if not target: self._try_register(name) diff --git a/setup.py b/setup.py index 145f0c3..1929f93 100644 --- a/setup.py +++ b/setup.py @@ -3,7 +3,6 @@ """python-iptables setup script""" from setuptools import setup, Extension -#from distutils.core import setup, Extension # make pyflakes happy __pkgname__ = None @@ -15,6 +14,8 @@ name=__pkgname__, version=__version__, description="Python bindings for iptables", + long_description="Python bindings for classic iptables", + long_description_content_type="text/x-rst", author="Vilmos Nebehaj", author_email="v.nebehaj@gmail.com", url="https://github.com/ldx/python-iptables", @@ -38,10 +39,7 @@ "Topic :: System :: Networking :: Firewalls", "Topic :: System :: Systems Administration", "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.3", - "Programming Language :: Python :: 3.4", "Programming Language :: Python :: Implementation :: CPython", ], license="Apache License, Version 2.0", diff --git a/tests/test_iptc.py b/tests/test_iptc.py index d630c87..816df86 100755 --- a/tests/test_iptc.py +++ b/tests/test_iptc.py @@ -423,7 +423,9 @@ def test_rule_address(self): def test_rule_interface(self): # valid interfaces rule = iptc.Rule6() - for intf in ["eth0", "eth+", "ip6tnl1", "ip6tnl+", "!ppp0", "!ppp+"]: + + max_length_valid_interface_name = "0123456789abcde" + for intf in ["eth0", "eth+", "ip6tnl1", "ip6tnl+", "!ppp0", "!ppp+", max_length_valid_interface_name]: rule.in_interface = intf self.assertEquals(intf, rule.in_interface) rule.out_interface = intf