fields.py 11.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# Copyright 2014 Budapest University of Technology and Economics (BME IK)
#
# This file is part of CIRCLE Cloud.
#
# CIRCLE is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# CIRCLE is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along
# with CIRCLE.  If not, see <http://www.gnu.org/licenses/>.

from string import ascii_letters
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.ipv6 import is_valid_ipv6_address
from django import forms
from netaddr import (IPAddress, IPNetwork, AddrFormatError, ZEROFILL,
                     EUI, mac_unix, AddrConversionError)
import re

Szeberényi Imre committed
28 29 30 31 32
try:
    # Python 2: "unicode" is built-in
    unicode
except NameError:
    unicode = str
33 34 35 36 37 38 39 40 41 42 43 44 45 46

alfanum_re = re.compile(r'^[A-Za-z0-9_-]+$')
domain_re = re.compile(r'^([A-Za-z0-9_/-]\.?)+$')
domain_wildcard_re = re.compile(r'^(\*\.)?([A-Za-z0-9_/-]\.?)+$')
ipv4_re = re.compile('^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$')
reverse_domain_re = re.compile(r'^(%\([abcd]\)d|[a-z0-9./-])+$')


class mac_custom(mac_unix):
    word_fmt = '%.2X'


class MACAddressFormField(forms.Field):
    default_error_messages = {
Kohl Krisztofer committed
47
        'invalid': _('Enter a valid MAC address. %s'),
48 49 50 51
    }

    def validate(self, value):
        try:
Kohl Krisztofer committed
52
            return MACAddressField.to_python
53 54
        except (AddrFormatError, TypeError, ValidationError) as e:
            raise ValidationError(self.default_error_messages['invalid']
Szeberényi Imre committed
55
                                  % unicode(e))
56 57 58 59 60 61 62 63 64 65 66 67 68 69


class MACAddressField(models.Field):
    description = _('MAC Address object')

    def __init__(self, *args, **kwargs):
        kwargs['max_length'] = 17
        super(MACAddressField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(MACAddressField, self).deconstruct()
        del kwargs['max_length']
        return name, path, args, kwargs

Kohl Krisztofer committed
70
    def from_db_value(self, value, expression, connection, context=None):
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
        return self.to_python(value)

    def to_python(self, value):
        if not value:
            return None

        if isinstance(value, EUI):
            return value

        return EUI(value, dialect=mac_custom)

    def get_internal_type(self):
        return 'CharField'

    def get_prep_value(self, value, prepared=False):
        if not value:
            return None

        if isinstance(value, EUI):
            return str(value)

        return value

    def formfield(self, **kwargs):
        defaults = {'form_class': MACAddressFormField}
        defaults.update(kwargs)
        return super(MACAddressField, self).formfield(**defaults)


class IPAddressFormField(forms.Field):
    default_error_messages = {
Kohl Krisztofer committed
102
        'invalid': _('Enter a valid IP address. %s'),
103 104 105 106 107 108 109
    }

    def validate(self, value):
        try:
            IPAddressField(version=self.version).to_python(value)
        except (AddrFormatError, TypeError, ValueError) as e:
            raise ValidationError(self.default_error_messages['invalid']
Kohl Krisztofer committed
110
                                  % str(e))
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

    def __init__(self, *args, **kwargs):
        self.version = kwargs['version']
        del kwargs['version']
        super(IPAddressFormField, self).__init__(*args, **kwargs)


class IPAddressField(models.Field):
    description = _('IP Network object')

    def __init__(self, version=4, serialize=True, *args, **kwargs):
        kwargs['max_length'] = 100
        self.version = version
        super(IPAddressField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(IPAddressField, self).deconstruct()
        del kwargs['max_length']
        if self.version != 4:
            kwargs['version'] = self.version
        return name, path, args, kwargs

    def get_internal_type(self):
        return "CharField"

Kohl Krisztofer committed
136
    def from_db_value(self, value, expression, connection, context=None):
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
        return self.to_python(value)

    def to_python(self, value):
        if not value:
            return None

        if isinstance(value, IPAddress):
            return value

        return IPAddress(value.split('/')[0], version=self.version,
                         flags=ZEROFILL)

    def get_prep_value(self, value, prepared=False):
        if not value:
            return None

        if isinstance(value, IPAddress):
            if self.version == 4:
                return '.'.join("%03d" % x for x in value.words)
            else:
                return ':'.join("%04X" % x for x in value.words)
        return value

    def formfield(self, **kwargs):
        defaults = {'form_class': IPAddressFormField}
        defaults['version'] = self.version
        defaults.update(kwargs)
        return super(IPAddressField, self).formfield(**defaults)


class IPNetworkFormField(forms.Field):
    default_error_messages = {
Kohl Krisztofer committed
169
        'invalid': _('Enter a valid IP network. %s'),
170 171 172 173 174 175 176
    }

    def validate(self, value):
        try:
            return IPNetworkField(version=self.version).to_python(value)
        except (AddrFormatError, TypeError) as e:
            raise ValidationError(self.default_error_messages['invalid']
Szeberényi Imre committed
177
                                  % unicode(e))
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

    def __init__(self, *args, **kwargs):
        self.version = kwargs['version']
        del kwargs['version']
        super(IPNetworkFormField, self).__init__(*args, **kwargs)


class IPNetworkField(models.Field):
    description = _('IP Network object')

    def __init__(self, version=4, serialize=True, *args, **kwargs):
        kwargs['max_length'] = 100
        self.version = version
        super(IPNetworkField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(IPNetworkField, self).deconstruct()
        del kwargs['max_length']
        if self.version != 4:
            kwargs['version'] = self.version
        return name, path, args, kwargs

Kohl Krisztofer committed
200
    def from_db_value(self, value, expression, connection, context=None):
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
        return self.to_python(value)

    def to_python(self, value):
        if not value:
            return None

        if isinstance(value, IPNetwork):
            return value

        return IPNetwork(value, version=self.version)

    def get_internal_type(self):
        return "CharField"

    def get_prep_value(self, value, prepared=False):
        if not value:
            return None

        if isinstance(value, IPNetwork):
            if self.version == 4:
                return ('.'.join("%03d" % x for x in value.ip.words) +
                        '/%02d' % value.prefixlen)
            else:
                return (':'.join("%04X" % x for x in value.ip.words) +
                        '/%03d' % value.prefixlen)
        return value

    def formfield(self, **kwargs):
        defaults = {'form_class': IPNetworkFormField}
        defaults['version'] = self.version
        defaults.update(kwargs)
        return super(IPNetworkField, self).formfield(**defaults)


def val_alfanum(value):
    """Validate whether the parameter is a valid alphanumeric value."""
    if not alfanum_re.match(value):
Kohl Krisztofer committed
238
        raise ValidationError(_('%s - only letters, numbers, underscores '
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
                                'and hyphens are allowed!') % value)


def is_valid_domain(value):
    """Check whether the parameter is a valid domain name."""
    return domain_re.match(value) is not None


def is_valid_domain_wildcard(value):
    """Check whether the parameter is a valid domain name."""
    return domain_wildcard_re.match(value) is not None


def val_domain(value):
    """Validate whether the parameter is a valid domin name."""
    if not is_valid_domain(value):
Kohl Krisztofer committed
255
        raise ValidationError(_('%s - invalid domain name') % value)
256 257 258 259 260


def val_domain_wildcard(value):
    """Validate whether the parameter is a valid domin name."""
    if not is_valid_domain_wildcard(value):
Kohl Krisztofer committed
261
        raise ValidationError(_('%s - invalid domain name') % value)
262 263 264 265 266 267 268 269 270 271


def is_valid_reverse_domain(value):
    """Check whether the parameter is a valid reverse domain name."""
    return reverse_domain_re.match(value) is not None


def val_reverse_domain(value):
    """Validate whether the parameter is a valid reverse domain name."""
    if not is_valid_reverse_domain(value):
Kohl Krisztofer committed
272
        raise ValidationError('%s - invalid reverse domain name' % value)
273 274 275 276 277 278 279 280 281


def val_ipv6_template(value):
    """Validate whether the parameter is a valid ipv6 template.

    Normal use:
    >>> val_ipv6_template("123::%(a)d:%(b)d:%(c)d:%(d)d")
    >>> val_ipv6_template("::%(a)x:%(b)x:%(c)d:%(d)d")

Szeberényi Imre committed
282
    Don't have to use all unicode from the left (no a):
283 284 285 286 287 288
    >>> val_ipv6_template("::%(b)x:%(c)d:%(d)d")

    But have to use all ones to the right (a, but no b):
    >>> val_ipv6_template("::%(a)x:%(c)d:%(d)d")
    Traceback (most recent call last):
        ...
289
    django.core.exceptions.ValidationError: ["template doesn't use parameter b"]
290 291 292 293 294

    Detects valid templates building invalid ips:
    >>> val_ipv6_template("xxx::%(a)d:%(b)d:%(c)d:%(d)d")
    Traceback (most recent call last):
        ...
295
    django.core.exceptions.ValidationError: ['template renders invalid IPv6 address']
296 297 298 299 300

    Also IPv4-compatible addresses are invalid:
    >>> val_ipv6_template("::%(a)02x%(b)02x:%(c)d:%(d)d")
    Traceback (most recent call last):
        ...
301
    django.core.exceptions.ValidationError: ['template results in IPv4 address']
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    """
    tpl = {ascii_letters[i]: 255 for i in range(4)}
    try:
        v6 = value % tpl
    except:
        raise ValidationError(_('%s: invalid template') % value)

    used = False
    for i in ascii_letters[:4]:
        try:
            value % {k: tpl[k] for k in tpl if k != i}
        except KeyError:
            used = True  # ok, it misses this key
        else:
            if used:
                raise ValidationError(
                    _("template doesn't use parameter %s") % i)
    try:
        v6 = IPAddress(v6, 6)
    except:
        raise ValidationError(_('template renders invalid IPv6 address'))
    try:
        v6.ipv4()
    except (AddrConversionError, AddrFormatError):
        pass  # can't converted to ipv4 == it's real ipv6
    else:
        raise ValidationError(_('template results in IPv4 address'))


def is_valid_ipv4_address(value):
    """Check whether the parameter is a valid IPv4 address."""
    return ipv4_re.match(value) is not None


def val_ipv4(value):
    """Validate whether the parameter is a valid IPv4 address."""
    if not is_valid_ipv4_address(value):
Kohl Krisztofer committed
339
        raise ValidationError(_('%s - not an IPv4 address') % value)
340 341 342 343 344


def val_ipv6(value):
    """Validate whether the parameter is a valid IPv6 address."""
    if not is_valid_ipv6_address(value):
Kohl Krisztofer committed
345
        raise ValidationError(_('%s - not an IPv6 address') % value)
346 347 348 349 350 351 352 353 354 355 356 357


def val_mx(value):
    """Validate whether the parameter is a valid MX address definition.

    Expected form is <priority>:<hostname>.
    """
    mx = value.split(':', 1)
    if not (len(mx) == 2 and mx[0].isdigit() and
            domain_re.match(mx[1])):
        raise ValidationError(_("Bad MX address format. "
                                "Should be: <priority>:<hostname>"))