models.py 73.1 KB
Newer Older
1
# -*- mode: python; coding: utf-8 -*-
2 3 4 5
# Re2o est un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
6
# Copyright © 2016-2018  Gabriel Détraz
7 8
# Copyright © 2017  Goulven Kermarec
# Copyright © 2017  Augustin Lemesle
9
# Copyright © 2018  Charlie Jacomme
10 11 12 13 14 15 16 17 18 19 20 21 22 23
#
# This program 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 2 of the License, or
# (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 25 26
"""machines.models
The models definitions for the Machines app
"""
27

28 29
from __future__ import unicode_literals

erdnaxe's avatar
erdnaxe committed
30 31
import base64
import hashlib
Gabriel Detraz's avatar
Gabriel Detraz committed
32
import re
erdnaxe's avatar
erdnaxe committed
33
from datetime import timedelta
34
from ipaddress import IPv6Address
35
from itertools import chain
Gabriel Detraz's avatar
Gabriel Detraz committed
36

erdnaxe's avatar
erdnaxe committed
37
from django.core.validators import MaxValueValidator, MinValueValidator
38
from django.db import models
39
from django.db.models import Q
Gabriel Detraz's avatar
Gabriel Detraz committed
40
from django.db.models.signals import post_save, post_delete
41
from django.dispatch import receiver
42
from django.forms import ValidationError
43
from django.utils import timezone
erdnaxe's avatar
erdnaxe committed
44
from django.utils.functional import cached_property
45
from django.utils.translation import ugettext_lazy as _
46
from macaddress.fields import MACAddressField
erdnaxe's avatar
erdnaxe committed
47
from netaddr import mac_bare, EUI, IPSet, IPRange, IPNetwork, IPAddress
48

erdnaxe's avatar
erdnaxe committed
49 50
import preferences.models
import users.models
51
from re2o.field_permissions import FieldPermissionModelMixin
52
from re2o.mixins import AclMixin, RevMixin
53

54

55
class Machine(RevMixin, FieldPermissionModelMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
56 57
    """ Class définissant une machine, object parent user, objets fils
    interfaces"""
58
    user = models.ForeignKey('users.User', on_delete=models.CASCADE)
Gabriel Detraz's avatar
Gabriel Detraz committed
59 60
    name = models.CharField(
        max_length=255,
61
        help_text=_("Optional"),
Gabriel Detraz's avatar
Gabriel Detraz committed
62 63 64
        blank=True,
        null=True
    )
65
    active = models.BooleanField(default=True)
66

67 68
    class Meta:
        permissions = (
69
            ("view_machine", _("Can view a machine object")),
70
            ("change_machine_user",
71
             _("Can change the user of a machine")),
72
        )
73 74
        verbose_name = _("machine")
        verbose_name_plural = _("machines")
75

76 77
    @classmethod
    def get_instance(cls, machineid, *_args, **_kwargs):
78 79 80 81
        """Get the Machine instance with machineid.
        :param userid: The id
        :return: The user
        """
82
        return cls.objects.get(pk=machineid)
83

84 85 86
    def linked_objects(self):
        """Return linked objects : machine and domain.
        Usefull in history display"""
87 88 89 90 91 92
        return chain(
            self.interface_set.all(),
            Domain.objects.filter(
                interface_parent__in=self.interface_set.all()
            )
        )
93

94
    @staticmethod
95
    def can_change_user(user_request, *_args, **_kwargs):
96 97 98 99 100 101 102 103 104 105
        """Checks if an user is allowed to change the user who owns a
        Machine.

        Args:
            user_request: The user requesting to change owner.

        Returns:
            A tuple with a boolean stating if edition is allowed and an
            explanation message.
        """
106
        return (user_request.has_perm('machines.change_machine_user'),
107
                _("You don't have the right to change the machine's user."))
108

109 110
    @staticmethod
    def can_view_all(user_request, *_args, **_kwargs):
111 112 113 114 115
        """Vérifie qu'on peut bien afficher l'ensemble des machines,
        droit particulier correspondant
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
        if not user_request.has_perm('machines.view_machine'):
116
            return False, _("You don't have the right to view all the"
erdnaxe's avatar
erdnaxe committed
117
                            " machines.")
118 119
        return True, None

120 121
    @staticmethod
    def can_create(user_request, userid, *_args, **_kwargs):
122 123 124 125 126
        """Vérifie qu'un user qui fait la requète peut bien créer la machine
        et n'a pas atteint son quota, et crée bien une machine à lui
        :param user_request: Utilisateur qui fait la requête
        :param userid: id de l'user dont on va créer une machine
        :return: soit True, soit False avec la raison de l'échec"""
Maël Kervella's avatar
Maël Kervella committed
127
        try:
128
            user = users.models.User.objects.get(pk=userid)
Maël Kervella's avatar
Maël Kervella committed
129
        except users.models.User.DoesNotExist:
130
            return False, _("Nonexistent user.")
131
        max_lambdauser_interfaces = (preferences.models.OptionalMachine
erdnaxe's avatar
erdnaxe committed
132 133 134
            .get_cached_value(
            'max_lambdauser_interfaces'
        ))
135
        if not user_request.has_perm('machines.add_machine'):
136 137
            if not (preferences.models.OptionalMachine
                    .get_cached_value('create_machine')):
138
                return False, (_("You don't have the right to add a machine."))
Maël Kervella's avatar
Maël Kervella committed
139
            if user != user_request:
140 141
                return False, (_("You don't have the right to add a machine"
                                 " to another user."))
Maël Kervella's avatar
Maël Kervella committed
142
            if user.user_interfaces().count() >= max_lambdauser_interfaces:
143 144 145
                return False, (_("You reached the maximum number of interfaces"
                                 " that you are allowed to create yourself"
                                 " (%s)." % max_lambdauser_interfaces))
Maël Kervella's avatar
Maël Kervella committed
146 147
        return True, None

148
    def can_edit(self, user_request, *args, **kwargs):
149 150 151 152 153
        """Vérifie qu'on peut bien éditer cette instance particulière (soit
        machine de soi, soit droit particulier
        :param self: instance machine à éditer
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison le cas échéant"""
154
        if self.user != user_request:
155 156 157 158 159 160
            if (not user_request.has_perm('machines.change_interface') or
                    not self.user.can_edit(
                        self.user,
                        user_request,
                        *args,
                        **kwargs
161 162 163
                    )[0]):
                return False, (_("You don't have the right to edit a machine"
                                 " of another user."))
164 165
        return True, None

166
    def can_delete(self, user_request, *args, **kwargs):
167 168 169 170 171
        """Vérifie qu'on peut bien supprimer cette instance particulière (soit
        machine de soi, soit droit particulier
        :param self: instance machine à supprimer
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
172
        if self.user != user_request:
173 174 175 176 177 178
            if (not user_request.has_perm('machines.change_interface') or
                    not self.user.can_edit(
                        self.user,
                        user_request,
                        *args,
                        **kwargs
179 180
                    )[0]):
                return False, _("You don't have the right to delete a machine"
erdnaxe's avatar
erdnaxe committed
181
                                " of another user.")
182 183
        return True, None

184
    def can_view(self, user_request, *_args, **_kwargs):
185 186 187 188 189
        """Vérifie qu'on peut bien voir cette instance particulière (soit
        machine de soi, soit droit particulier
        :param self: instance machine à éditer
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
190 191
        if (not user_request.has_perm('machines.view_machine') and
                self.user != user_request):
192
            return False, _("You don't have the right to view other machines"
erdnaxe's avatar
erdnaxe committed
193
                            " than yours.")
194
        return True, None
195

196 197 198 199
    @cached_property
    def short_name(self):
        """Par defaut, renvoie le nom de la première interface
        de cette machine"""
200 201 202 203 204
        interfaces_set = self.interface_set.first()
        if interfaces_set:
            return str(interfaces_set.domain.name)
        else:
            return "None"
205

206 207 208 209 210 211
    @cached_property
    def complete_name(self):
        """Par defaut, renvoie le nom de la première interface
        de cette machine"""
        return str(self.interface_set.first())

212 213 214 215 216 217
    @cached_property
    def all_short_names(self):
        """Renvoie de manière unique, le nom des interfaces de cette
        machine"""
        return Domain.objects.filter(
            interface_parent__machine=self
erdnaxe's avatar
erdnaxe committed
218
        ).values_list('name', flat=True).distinct()
219

220 221 222 223 224
    @cached_property
    def get_name(self):
        """Return a name : user provided name or first interface name"""
        return self.name or self.short_name

225 226 227 228 229
    @cached_property
    def all_complete_names(self):
        """Renvoie tous les tls complets de la machine"""
        return [str(domain) for domain in Domain.objects.filter(
            Q(cname__interface_parent__machine=self) | Q(interface_parent__machine=self)
erdnaxe's avatar
erdnaxe committed
230
        )]
231

232 233 234
    def __init__(self, *args, **kwargs):
        super(Machine, self).__init__(*args, **kwargs)
        self.field_permissions = {
235
            'user': self.can_change_user,
236 237
        }

238
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
239 240
        return str(self.user) + ' - ' + str(self.id) + ' - ' + str(self.name)

241

242
class MachineType(RevMixin, AclMixin, models.Model):
243
    """ Type de machine, relié à un type d'ip, affecté aux interfaces"""
244
    type = models.CharField(max_length=255)
Gabriel Detraz's avatar
Gabriel Detraz committed
245 246 247 248 249 250
    ip_type = models.ForeignKey(
        'IpType',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
251

252 253
    class Meta:
        permissions = (
254 255
            ("view_machinetype", _("Can view a machine type object")),
            ("use_all_machinetype", _("Can use all machine types")),
256
        )
257 258
        verbose_name = _("machine type")
        verbose_name_plural = _("machine types")
259

260
    def all_interfaces(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
261 262
        """ Renvoie toutes les interfaces (cartes réseaux) de type
        machinetype"""
263 264
        return Interface.objects.filter(type=self)

265 266
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
267 268 269 270 271 272 273 274
        """Check if an user can use every MachineType.

        Args:
            user_request: The user requesting edition.
        Returns:
            A tuple with a boolean stating if user can acces and an explanation
            message is acces is not allowed.
        """
275
        if not user_request.has_perm('machines.use_all_machinetype'):
276 277
            return False, (_("You don't have the right to use all machine"
                             " types."))
278 279
        return True, None

280
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
281 282
        return self.type

283

284
class IpType(RevMixin, AclMixin, models.Model):
285
    """ Type d'ip, définissant un range d'ip, affecté aux machine types"""
286
    type = models.CharField(max_length=255)
287
    extension = models.ForeignKey('Extension', on_delete=models.PROTECT)
288
    need_infra = models.BooleanField(default=False)
289 290
    domaine_ip_start = models.GenericIPAddressField(protocol='IPv4')
    domaine_ip_stop = models.GenericIPAddressField(protocol='IPv4')
291 292 293 294
    domaine_ip_network = models.GenericIPAddressField(
        protocol='IPv4',
        null=True,
        blank=True,
295
        help_text=_("Network containing the domain's IPv4 range (optional)")
296 297 298 299 300 301 302
    )
    domaine_ip_netmask = models.IntegerField(
        default=24,
        validators=[
            MaxValueValidator(31),
            MinValueValidator(8)
        ],
303
        help_text=_("Netmask for the domain's IPv4 range")
304
    )
305
    reverse_v4 = models.BooleanField(
erdnaxe's avatar
erdnaxe committed
306 307
        default=False,
        help_text=_("Enable reverse DNS for IPv4"),
308
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
309 310 311 312 313
    prefix_v6 = models.GenericIPAddressField(
        protocol='IPv6',
        null=True,
        blank=True
    )
314 315 316 317 318 319
    prefix_v6_length = models.IntegerField(
        default=64,
        validators=[
            MaxValueValidator(128),
            MinValueValidator(0)
        ]
erdnaxe's avatar
erdnaxe committed
320
    )
321
    reverse_v6 = models.BooleanField(
erdnaxe's avatar
erdnaxe committed
322 323
        default=False,
        help_text=_("Enable reverse DNS for IPv6"),
324
    )
Gabriel Detraz's avatar
Gabriel Detraz committed
325 326 327 328 329 330 331 332 333 334 335
    vlan = models.ForeignKey(
        'Vlan',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
    ouverture_ports = models.ForeignKey(
        'OuverturePortList',
        blank=True,
        null=True
    )
336

337 338
    class Meta:
        permissions = (
339 340
            ("view_iptype", _("Can view an IP type object")),
            ("use_all_iptype", _("Can use all IP types")),
341
        )
342
        verbose_name = _("IP type")
erdnaxe's avatar
erdnaxe committed
343
        verbose_name_plural = "IP types"
344

345
    @cached_property
346
    def ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
347 348
        """ Renvoie un objet IPRange à partir de l'objet IpType"""
        return IPRange(self.domaine_ip_start, end=self.domaine_ip_stop)
349 350 351

    @cached_property
    def ip_set(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
352
        """ Renvoie une IPSet à partir de l'iptype"""
353
        return IPSet(self.ip_range)
354 355 356

    @cached_property
    def ip_set_as_str(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
357
        """ Renvoie une liste des ip en string"""
358 359
        return [str(x) for x in self.ip_set]

360 361 362 363 364
    @cached_property
    def ip_set_cidrs_as_str(self):
        """Renvoie la liste des cidrs du range en str"""
        return [str(ip_range) for ip_range in self.ip_set.iter_cidrs()]

365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    @cached_property
    def ip_set_full_info(self):
        """Iter sur les range cidr, et renvoie network, broacast , etc"""
        return [
            {
                'network': str(ip_set.network),
                'netmask': str(ip_set.netmask),
                'netmask_cidr': str(ip_set.prefixlen),
                'broadcast': str(ip_set.broadcast),
                'vlan': str(self.vlan),
                'vlan_id': self.vlan.vlan_id
            } for ip_set in self.ip_set.iter_cidrs()
        ]

    @cached_property
    def ip6_set_full_info(self):
        if self.prefix_v6:
            return {
erdnaxe's avatar
erdnaxe committed
383 384 385
                'network': str(self.prefix_v6),
                'netmask': 'ffff:ffff:ffff:ffff::',
                'netmask_cidr': str(self.prefix_v6_length),
386
                'vlan': str(self.vlan),
387
                'vlan_id': self.vlan.vlan_id
388 389 390 391
            }
        else:
            return None

392 393 394 395 396 397 398 399 400 401 402 403
    @cached_property
    def ip_network(self):
        """Renvoie le network parent du range start-stop, si spécifié
        Différent de ip_set_cidrs ou iP_set, car lui est supérieur ou égal"""
        if self.domaine_ip_network:
            return IPNetwork(str(self.domaine_ip_network) + '/' + str(self.domaine_ip_netmask))
        return None

    @cached_property
    def ip_net_full_info(self):
        """Renvoie les infos du network contenant du range"""
        return {
erdnaxe's avatar
erdnaxe committed
404 405 406 407
            'network': str(self.ip_network.network),
            'netmask': str(self.ip_network.netmask),
            'broadcast': str(self.ip_network.broadcast),
            'netmask_cidr': str(self.ip_network.prefixlen),
408 409
        }

410 411 412 413 414
    @cached_property
    def complete_prefixv6(self):
        """Return the complete prefix v6 as cidr"""
        return str(self.prefix_v6) + "/" + str(self.prefix_v6_length)

415
    def ip_objects(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
416
        """ Renvoie tous les objets ipv4 relié à ce type"""
417 418 419
        return IpList.objects.filter(ip_type=self)

    def free_ip(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
420
        """ Renvoie toutes les ip libres associées au type donné (self)"""
Gabriel Detraz's avatar
Gabriel Detraz committed
421 422 423
        return IpList.objects.filter(
            interface__isnull=True
        ).filter(ip_type=self)
424 425

    def gen_ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
426 427 428
        """ Cree les IpList associées au type self. Parcours pédestrement et
        crée les ip une par une. Si elles existent déjà, met à jour le type
        associé à l'ip"""
429
        # Creation du range d'ip dans les objets iplist
430
        ip_obj = [IpList(ip_type=self, ipv4=str(ip)) for ip in self.ip_range]
Gabriel Detraz's avatar
Gabriel Detraz committed
431
        listes_ip = IpList.objects.filter(
432
            ipv4__in=[str(ip) for ip in self.ip_range]
Gabriel Detraz's avatar
Gabriel Detraz committed
433
        )
434 435 436 437 438 439
        # Si il n'y a pas d'ip, on les crée
        if not listes_ip:
            IpList.objects.bulk_create(ip_obj)
        # Sinon on update l'ip_type
        else:
            listes_ip.update(ip_type=self)
440
        return
441 442

    def del_ip_range(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
443 444
        """ Methode dépréciée, IpList est en mode cascade et supprimé
        automatiquement"""
445
        if Interface.objects.filter(ipv4__in=self.ip_objects()):
446 447 448
            raise ValidationError(_("One or several IP addresses from the"
                                    " range are affected, impossible to delete"
                                    " the range."))
449 450 451
        for ip in self.ip_objects():
            ip.delete()

452 453 454 455 456
    def check_replace_prefixv6(self):
        """Remplace les prefixv6 des interfaces liées à ce type d'ip"""
        if not self.prefix_v6:
            return
        else:
457
            for ipv6 in Ipv6List.objects.filter(
erdnaxe's avatar
erdnaxe committed
458 459 460
                    interface__in=Interface.objects.filter(
                        type__in=MachineType.objects.filter(ip_type=self)
                    )
461
            ):
462 463
                ipv6.check_and_replace_prefix(prefix=self.prefix_v6)

464 465
    def get_associated_ptr_records(self):
        from re2o.utils import all_active_assigned_interfaces
466 467 468 469 470 471
        if self.reverse_v4:
            return (all_active_assigned_interfaces()
                    .filter(type__ip_type=self)
                    .filter(ipv4__isnull=False))
        else:
            return None
472 473 474

    def get_associated_ptr_v6_records(self):
        from re2o.utils import all_active_interfaces
475 476 477 478 479
        if self.reverse_v6:
            return (all_active_interfaces(full=True)
                    .filter(type__ip_type=self))
        else:
            return None
480

481
    def clean(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
482 483 484 485 486
        """ Nettoyage. Vérifie :
        - Que ip_stop est après ip_start
        - Qu'on ne crée pas plus gros qu'un /16
        - Que le range crée ne recoupe pas un range existant
        - Formate l'ipv6 donnée en /64"""
487
        if IPAddress(self.domaine_ip_start) > IPAddress(self.domaine_ip_stop):
488
            raise ValidationError(_("Range end must be after range start..."))
489 490
        # On ne crée pas plus grand qu'un /16
        if self.ip_range.size > 65536:
491 492
            raise ValidationError(_("The range is too large, you can't create"
                                    " a larger one than a /16."))
493
        # On check que les / ne se recoupent pas
494
        for element in IpType.objects.all().exclude(pk=self.pk):
495
            if not self.ip_set.isdisjoint(element.ip_set):
496 497
                raise ValidationError(_("The specified range is not disjoint"
                                        " from existing ranges."))
498 499 500
        # On formate le prefix v6
        if self.prefix_v6:
            self.prefix_v6 = str(IPNetwork(self.prefix_v6 + '/64').network)
501 502 503
        # On vérifie qu'un domaine network/netmask contiens bien le domaine ip start-stop
        if self.domaine_ip_network:
            if not self.domaine_ip_start in self.ip_network or not self.domaine_ip_stop in self.ip_network:
504 505 506
                raise ValidationError(_("If you specify a domain network or"
                                        " netmask, it must contain the"
                                        " domain's IP range."))
507 508 509 510 511 512
        return

    def save(self, *args, **kwargs):
        self.clean()
        super(IpType, self).save(*args, **kwargs)

513 514
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
515 516
        """Superdroit qui permet d'utiliser toutes les extensions sans
        restrictions
517 518
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
519
        return user_request.has_perm('machines.use_all_iptype'), None
520

521 522
    def __str__(self):
        return self.type
chirac's avatar
chirac committed
523

Gabriel Detraz's avatar
Gabriel Detraz committed
524

525
class Vlan(RevMixin, AclMixin, models.Model):
526 527 528
    """ Un vlan : vlan_id et nom
    On limite le vlan id entre 0 et 4096, comme défini par la norme"""
    vlan_id = models.PositiveIntegerField(validators=[MaxValueValidator(4095)])
529 530
    name = models.CharField(max_length=256)
    comment = models.CharField(max_length=256, blank=True)
531 532 533 534
    #Réglages supplémentaires
    arp_protect = models.BooleanField(default=False)
    dhcp_snooping = models.BooleanField(default=False)
    dhcpv6_snooping = models.BooleanField(default=False)
535 536 537 538 539 540 541 542 543
    igmp = models.BooleanField(
        default=False,
        help_text="Gestion multicast v4"
    )
    mld = models.BooleanField(
        default=False,
        help_text="Gestion multicast v6"
    )

544 545
    class Meta:
        permissions = (
546
            ("view_vlan", _("Can view a VLAN object")),
547
        )
548 549
        verbose_name = _("VLAN")
        verbose_name_plural = _("VLANs")
550

551 552 553
    def __str__(self):
        return self.name

Gabriel Detraz's avatar
Gabriel Detraz committed
554

555
class Nas(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
556
    """ Les nas. Associé à un machine_type.
Gabriel Detraz's avatar
Gabriel Detraz committed
557 558
    Permet aussi de régler le port_access_mode (802.1X ou mac-address) pour
    le radius. Champ autocapture de la mac à true ou false"""
559 560 561 562 563 564
    default_mode = '802.1X'
    AUTH = (
        ('802.1X', '802.1X'),
        ('Mac-address', 'Mac-address'),
    )

565
    name = models.CharField(max_length=255, unique=True)
Gabriel Detraz's avatar
Gabriel Detraz committed
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
    nas_type = models.ForeignKey(
        'MachineType',
        on_delete=models.PROTECT,
        related_name='nas_type'
    )
    machine_type = models.ForeignKey(
        'MachineType',
        on_delete=models.PROTECT,
        related_name='machinetype_on_nas'
    )
    port_access_mode = models.CharField(
        choices=AUTH,
        default=default_mode,
        max_length=32
    )
581
    autocapture_mac = models.BooleanField(default=False)
582

583 584
    class Meta:
        permissions = (
585
            ("view_nas", _("Can view a NAS device object")),
586
        )
587 588
        verbose_name = _("NAS device")
        verbose_name_plural = _("NAS devices")
589

590 591 592
    def __str__(self):
        return self.name

Gabriel Detraz's avatar
Gabriel Detraz committed
593

594
class SOA(RevMixin, AclMixin, models.Model):
595 596 597 598 599
    """
    Un enregistrement SOA associé à une extension
    Les valeurs par défault viennent des recommandations RIPE :
    https://www.ripe.net/publications/docs/ripe-203
    """
600
    name = models.CharField(max_length=255)
601
    mail = models.EmailField(
602
        help_text=_("Contact email address for the zone")
603 604
    )
    refresh = models.PositiveIntegerField(
605
        default=86400,  # 24 hours
606 607
        help_text=_("Seconds before the secondary DNS have to ask the primary"
                    " DNS serial to detect a modification")
608 609
    )
    retry = models.PositiveIntegerField(
610
        default=7200,  # 2 hours
611 612
        help_text=_("Seconds before the secondary DNS ask the serial again in"
                    " case of a primary DNS timeout")
613 614
    )
    expire = models.PositiveIntegerField(
615
        default=3600000,  # 1000 hours
616 617
        help_text=_("Seconds before the secondary DNS stop answering requests"
                    " in case of primary DNS timeout")
618 619 620
    )
    ttl = models.PositiveIntegerField(
        default=172800,  # 2 days
621
        help_text=_("Time to Live")
622 623
    )

624 625
    class Meta:
        permissions = (
626
            ("view_soa", _("Can view an SOA record object")),
627
        )
628 629
        verbose_name = _("SOA record")
        verbose_name_plural = _("SOA records")
630

631 632 633 634 635 636 637 638 639 640 641 642 643
    def __str__(self):
        return str(self.name)

    @cached_property
    def dns_soa_param(self):
        """
        Renvoie la partie de l'enregistrement SOA correspondant aux champs :
            <refresh>   ; refresh
            <retry>     ; retry
            <expire>    ; expire
            <ttl>       ; TTL
        """
        return (
644 645 646 647
            '    {refresh}; refresh\n'
            '    {retry}; retry\n'
            '    {expire}; expire\n'
            '    {ttl}; TTL'
648
        ).format(
649 650 651 652
            refresh=str(self.refresh).ljust(12),
            retry=str(self.retry).ljust(12),
            expire=str(self.expire).ljust(12),
            ttl=str(self.ttl).ljust(12)
653 654 655 656 657 658
        )

    @cached_property
    def dns_soa_mail(self):
        """ Renvoie le mail dans l'enregistrement SOA """
        mail_fields = str(self.mail).split('@')
659
        return mail_fields[0].replace('.', '\\.') + '.' + mail_fields[1] + '.'
660 661 662 663 664 665 666

    @classmethod
    def new_default_soa(cls):
        """ Fonction pour créer un SOA par défaut, utile pour les nouvelles
        extensions .
        /!\ Ne jamais supprimer ou renommer cette fonction car elle est
        utilisée dans les migrations de la BDD. """
667
        return cls.objects.get_or_create(
668
            name=_("SOA to edit"),
669 670
            mail="postmaser@example.com"
        )[0].pk
671 672


673
class Extension(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
674 675
    """ Extension dns type example.org. Précise si tout le monde peut
    l'utiliser, associé à un origin (ip d'origine)"""
Gabriel Detraz's avatar
Gabriel Detraz committed
676 677 678
    name = models.CharField(
        max_length=255,
        unique=True,
679
        help_text=_("Zone name, must begin with a dot (.example.org)")
Gabriel Detraz's avatar
Gabriel Detraz committed
680
    )
681
    need_infra = models.BooleanField(default=False)
682
    origin = models.ForeignKey(
Gabriel Detraz's avatar
Gabriel Detraz committed
683 684 685
        'IpList',
        on_delete=models.PROTECT,
        blank=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
686
        null=True,
687
        help_text=_("A record associated with the zone")
Gabriel Detraz's avatar
Gabriel Detraz committed
688
    )
689 690 691
    origin_v6 = models.GenericIPAddressField(
        protocol='IPv6',
        null=True,
Gabriel Detraz's avatar
Gabriel Detraz committed
692
        blank=True,
693
        help_text=_("AAAA record associated with the zone")
694
    )
695 696
    soa = models.ForeignKey(
        'SOA',
697
        on_delete=models.CASCADE
698
    )
699

700 701
    class Meta:
        permissions = (
702 703
            ("view_extension", _("Can view an extension object")),
            ("use_all_extension", _("Can use all extensions")),
704
        )
705 706
        verbose_name = _("DNS extension")
        verbose_name_plural = _("DNS extensions")
707

708 709
    @cached_property
    def dns_entry(self):
710 711 712
        """ Une entrée DNS A et AAAA sur origin (zone self)"""
        entry = ""
        if self.origin:
713
            entry += "@               IN  A       " + str(self.origin)
714 715 716
        if self.origin_v6:
            if entry:
                entry += "\n"
717
            entry += "@               IN  AAAA    " + str(self.origin_v6)
718
        return entry
719

720
    def get_associated_sshfp_records(self):
721 722 723
        from re2o.utils import all_active_assigned_interfaces
        return (all_active_assigned_interfaces()
                .filter(type__ip_type__extension=self)
724
                .filter(machine__id__in=SshFp.objects.values('machine')))
725

726
    def get_associated_a_records(self):
727 728
        from re2o.utils import all_active_assigned_interfaces
        return (all_active_assigned_interfaces()
729
                .filter(type__ip_type__extension=self)
730
                .filter(ipv4__isnull=False))
731 732

    def get_associated_aaaa_records(self):
733 734 735
        from re2o.utils import all_active_interfaces
        return (all_active_interfaces(full=True)
                .filter(type__ip_type__extension=self))
736 737

    def get_associated_cname_records(self):
738
        from re2o.utils import all_active_assigned_interfaces
739 740
        return (Domain.objects
                .filter(extension=self)
Charlie Jacomme's avatar
Charlie Jacomme committed
741
                .filter(cname__interface_parent__in=all_active_assigned_interfaces())
742
                .prefetch_related('cname'))
743

744 745
    @staticmethod
    def can_use_all(user_request, *_args, **_kwargs):
746 747
        """Superdroit qui permet d'utiliser toutes les extensions sans
        restrictions
748 749
        :param user_request: instance user qui fait l'edition
        :return: True ou False avec la raison de l'échec le cas échéant"""
750
        return user_request.has_perm('machines.use_all_extension'), None
751

752 753
    def __str__(self):
        return self.name
chirac's avatar
chirac committed
754

755
    def clean(self, *args, **kwargs):
Gabriel Detraz's avatar
Gabriel Detraz committed
756
        if self.name and self.name[0] != '.':
757
            raise ValidationError(_("An extension must begin with a dot."))
Gabriel Detraz's avatar
Gabriel Detraz committed
758 759
        super(Extension, self).clean(*args, **kwargs)

Gabriel Detraz's avatar
Gabriel Detraz committed
760

761
class Mx(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
762 763
    """ Entrées des MX. Enregistre la zone (extension) associée et la
    priorité
Gabriel Detraz's avatar
Gabriel Detraz committed
764
    Todo : pouvoir associer un MX à une interface """
765
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
766 767
    priority = models.PositiveIntegerField()
    name = models.ForeignKey('Domain', on_delete=models.PROTECT)
768

769 770
    class Meta:
        permissions = (
771
            ("view_mx", _("Can view an MX record object")),
772
        )
773 774
        verbose_name = _("MX record")
        verbose_name_plural = _("MX records")
775

776 777
    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
778 779
        """Renvoie l'entrée DNS complète pour un MX à mettre dans les
        fichiers de zones"""
780 781
        return "@               IN  MX  {prior} {name}".format(
            prior=str(self.priority).ljust(3),
Maël Kervella's avatar
Maël Kervella committed
782
            name=str(self.name)
783
        )
784

785 786 787
    def __str__(self):
        return str(self.zone) + ' ' + str(self.priority) + ' ' + str(self.name)

Gabriel Detraz's avatar
Gabriel Detraz committed
788

789
class Ns(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
790
    """Liste des enregistrements name servers par zone considéérée"""
791
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
792
    ns = models.ForeignKey('Domain', on_delete=models.PROTECT)
793

794 795
    class Meta:
        permissions = (
796
            ("view_ns", _("Can view an NS record object")),
797
        )
798 799
        verbose_name = _("NS record")
        verbose_name_plural = _("NS records")
800

801 802
    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
803
        """Renvoie un enregistrement NS complet pour les filezones"""
804
        return "@               IN  NS      " + str(self.ns)
805

806
    def __str__(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
807
        return str(self.zone) + ' ' + str(self.ns)
808

Gabriel Detraz's avatar
Gabriel Detraz committed
809

810
class Txt(RevMixin, AclMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
811
    """ Un enregistrement TXT associé à une extension"""
Gabriel Detraz's avatar
Gabriel Detraz committed
812 813
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
    field1 = models.CharField(max_length=255)
814
    field2 = models.TextField(max_length=2047)
Gabriel Detraz's avatar
Gabriel Detraz committed
815

816 817
    class Meta:
        permissions = (
818
            ("view_txt", _("Can view a TXT record object")),
819
        )
820 821
        verbose_name = _("TXT record")
        verbose_name_plural = _("TXT records")
822

Gabriel Detraz's avatar
Gabriel Detraz committed
823
    def __str__(self):
erdnaxe's avatar
erdnaxe committed
824 825
        return str(self.zone) + " : " + str(self.field1) + " " + \
               str(self.field2)
Gabriel Detraz's avatar
Gabriel Detraz committed
826 827 828

    @cached_property
    def dns_entry(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
829
        """Renvoie l'enregistrement TXT complet pour le fichier de zone"""
830
        return str(self.field1).ljust(15) + " IN  TXT     " + str(self.field2)
Gabriel Detraz's avatar
Gabriel Detraz committed
831

Gabriel Detraz's avatar
Gabriel Detraz committed
832

Charlie Jacomme's avatar
Charlie Jacomme committed
833
class DName(RevMixin, AclMixin, models.Model):
Maël Kervella's avatar
Maël Kervella committed
834
    """A DNAME entry for the DNS."""
Charlie Jacomme's avatar
Charlie Jacomme committed
835 836 837 838 839
    zone = models.ForeignKey('Extension', on_delete=models.PROTECT)
    alias = models.CharField(max_length=255)

    class Meta:
        permissions = (
840
            ("view_dname", _("Can view a DNAME record object")),
Charlie Jacomme's avatar
Charlie Jacomme committed
841
        )
842 843
        verbose_name = _("DNAME record")
        verbose_name_plural = _("DNAME records")
Charlie Jacomme's avatar
Charlie Jacomme committed
844 845 846 847 848 849

    def __str__(self):
        return str(self.zone) + " : " + str(self.alias)

    @cached_property
    def dns_entry(self):
Maël Kervella's avatar
Maël Kervella committed
850
        """Returns the DNAME record for the DNS zone file."""
chirac's avatar
chirac committed
851
        return str(self.alias).ljust(15) + " IN  DNAME   " + str(self.zone)
Charlie Jacomme's avatar
Charlie Jacomme committed
852 853


854
class Srv(RevMixin, AclMixin, models.Model):
855
    """ A SRV record """
Gabriel Detraz's avatar
Gabriel Detraz committed
856 857 858
    TCP = 'TCP'
    UDP = 'UDP'

859
    service = models.CharField(max_length=31)
Gabriel Detraz's avatar
Gabriel Detraz committed
860 861 862 863 864
    protocole = models.CharField(
        max_length=3,
        choices=(
            (TCP, 'TCP'),
            (UDP, 'UDP'),
865
        ),
Gabriel Detraz's avatar
Gabriel Detraz committed
866 867 868 869 870
        default=TCP,
    )
    extension = models.ForeignKey('Extension', on_delete=models.PROTECT)
    ttl = models.PositiveIntegerField(
        default=172800,  # 2 days
871
        help_text=_("Time to Live")
Gabriel Detraz's avatar
Gabriel Detraz committed
872 873
    )
    priority = models.PositiveIntegerField(
874
        default=0,
Gabriel Detraz's avatar
Gabriel Detraz committed
875
        validators=[MaxValueValidator(65535)],
876 877 878
        help_text=_("Priority of the target server (positive integer value,"
                    " the lower it is, the more the server will be used if"
                    " available)")
Gabriel Detraz's avatar
Gabriel Detraz committed
879 880
    )
    weight = models.PositiveIntegerField(
881
        default=0,
Gabriel Detraz's avatar
Gabriel Detraz committed
882
        validators=[MaxValueValidator(65535)],
883
        help_text=_("Relative weight for records with the same priority"
erdnaxe's avatar
erdnaxe committed
884
                    " (integer value between 0 and 65535)")
Gabriel Detraz's avatar
Gabriel Detraz committed
885 886 887
    )
    port = models.PositiveIntegerField(
        validators=[MaxValueValidator(65535)],
888
        help_text=_("TCP/UDP port")
Gabriel Detraz's avatar
Gabriel Detraz committed
889 890 891 892
    )
    target = models.ForeignKey(
        'Domain',
        on_delete=models.PROTECT,
893
        help_text=_("Target server")
Gabriel Detraz's avatar
Gabriel Detraz committed
894 895
    )

896 897
    class Meta:
        permissions = (
898
            ("view_srv", _("Can view an SRV record object")),
899
        )
900 901
        verbose_name = _("SRV record")
        verbose_name_plural = _("SRV records")
902

Gabriel Detraz's avatar
Gabriel Detraz committed
903
    def __str__(self):
erdnaxe's avatar
erdnaxe committed
904 905 906
        return str(self.service) + ' ' + str(self.protocole) + ' ' + \
               str(self.extension) + ' ' + str(self.priority) + \
               ' ' + str(self.weight) + str(self.port) + str(self.target)
Gabriel Detraz's avatar
Gabriel Detraz committed
907 908 909 910

    @cached_property
    def dns_entry(self):
        """Renvoie l'enregistrement SRV complet pour le fichier de zone"""
erdnaxe's avatar
erdnaxe committed
911 912 913 914
        return str(self.service) + '._' + str(self.protocole).lower() + \
               str(self.extension) + '. ' + str(self.ttl) + ' IN SRV ' + \
               str(self.priority) + ' ' + str(self.weight) + ' ' + \
               str(self.port) + ' ' + str(self.target) + '.'
Gabriel Detraz's avatar
Gabriel Detraz committed
915 916


917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
class SshFp(RevMixin, AclMixin, models.Model):
    """A fingerprint of an SSH public key"""

    ALGO = (
        ("ssh-rsa", "ssh-rsa"),
        ("ssh-ed25519", "ssh-ed25519"),
        ("ecdsa-sha2-nistp256", "ecdsa-sha2-nistp256"),
        ("ecdsa-sha2-nistp384", "ecdsa-sha2-nistp384"),
        ("ecdsa-sha2-nistp521", "ecdsa-sha2-nistp521"),
    )

    machine = models.ForeignKey('Machine', on_delete=models.CASCADE)
    pub_key_entry = models.TextField(
        help_text="SSH public key",
        max_length=2048
    )
    algo = models.CharField(
        choices=ALGO,
        max_length=32
    )
    comment = models.CharField(
        help_text="Comment",
        max_length=255,
        null=True,
        blank=True
    )

    @cached_property
    def algo_id(self):
        """Return the id of the algorithm for this key"""
        if "ecdsa" in self.algo:
            return 3
        elif "rsa" in self.algo:
            return 1
        else:
            return 2

    @cached_property
    def hash(self):
        """Return the hashess for the pub key with correct id
        cf RFC, 1 is sha1 , 2 sha256"""
        return {
erdnaxe's avatar
erdnaxe committed
959 960
            "1": hashlib.sha1(base64.b64decode(self.pub_key_entry)).hexdigest(),
            "2": hashlib.sha256(base64.b64decode(self.pub_key_entry)).hexdigest(),
961 962 963 964
        }

    class Meta:
        permissions = (
965
            ("view_sshfp", _("Can view an SSHFP record object")),
966
        )
967 968
        verbose_name = _("SSHFP record")
        verbose_name_plural = _("SSHFP records")
969 970 971 972 973 974 975 976 977 978 979 980 981 982

    def can_view(self, user_request, *_args, **_kwargs):
        return self.machine.can_view(user_request, *_args, **_kwargs)

    def can_edit(self, user_request, *args, **kwargs):
        return self.machine.can_edit(user_request, *args, **kwargs)

    def can_delete(self, user_request, *args, **kwargs):
        return self.machine.can_delete(user_request, *args, **kwargs)

    def __str__(self):
        return str(self.algo) + ' ' + str(self.comment)


983
class Interface(RevMixin, AclMixin, FieldPermissionModelMixin, models.Model):
Gabriel Detraz's avatar
Gabriel Detraz committed
984 985 986
    """ Une interface. Objet clef de l'application machine :
    - une address mac unique. Possibilité de la rendre unique avec le
    typemachine
Gabriel Detraz's avatar
Gabriel Detraz committed
987 988 989 990
    - une onetoone vers IpList pour attribution ipv4
    - le type parent associé au range ip et à l'extension
    - un objet domain associé contenant son nom
    - la liste des ports oiuvert"""
Gabriel Detraz's avatar
Gabriel Detraz committed
991 992 993 994 995 996
    ipv4 = models.OneToOneField(
        'IpList',
        on_delete=models.PROTECT,
        blank=True,
        null=True
    )
997
    mac_address = MACAddressField(integer=False)
998
    machine = models.ForeignKey('Machine', on_delete=models.CASCADE)
999
    type = models.ForeignKey('MachineType', on_delete=models.PROTECT)
1000
    details = models.CharField(max_length=255, blank=True)
1001
    port_lists = models.ManyToManyField('OuverturePortList', blank=True)
chirac's avatar
chirac committed
1002

1003 1004
    class Meta:
        permissions = (
1005
            ("view_interface", _("Can view an interface object")),
1006
            ("change_interface_machine",
1007
             _("Can change the owner of an interface")),
1008
        )
1009 1010
        verbose_name = _("interface")
        verbose_name_plural = _("interfaces")
1011

1012
    @cached_property
Dalahro's avatar
Dalahro committed
1013 1014 1015 1016
    def is_active(self):
        """ Renvoie si une interface doit avoir accès ou non """
        machine = self.machine
        user = self.machine.user
1017
        return machine.active and user.has_access()
Dalahro's avatar
Dalahro committed
1018

1019
    @cached_property
1020
    def ipv6_slaac(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1021 1022
        """ Renvoie un objet type ipv6 à partir du prefix associé à
        l'iptype parent"""
1023
        if self.type.ip_type.prefix_v6:
Gabriel Detraz's avatar
Gabriel Detraz committed
1024 1025 1026
            return EUI(self.mac_address).ipv6(
                IPNetwork(self.type.ip_type.prefix_v6).network
            )
1027 1028 1029
        else:
            return None

1030 1031 1032
    @cached_property
    def gen_ipv6_dhcpv6(self):
        """Cree une ip, à assigner avec dhcpv6 sur une machine"""
1033
        prefix_v6 = self.type.ip_type.prefix_v6.encode().decode('utf-8')
1034 1035
        if not prefix_v6:
            return None
1036 1037 1038 1039
        return IPv6Address(
            IPv6Address(prefix_v6).exploded[:20] +
            IPv6Address(self.id).exploded[20:]
        )
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052

    def sync_ipv6_dhcpv6(self):
        """Affecte une ipv6 dhcpv6 calculée à partir de l'id de la machine"""
        ipv6_dhcpv6 = self.gen_ipv6_dhcpv6
        if not ipv6_dhcpv6:
            return
        ipv6 = Ipv6List.objects.filter(ipv6=str(ipv6_dhcpv6)).first()
        if not ipv6:
            ipv6 = Ipv6List(ipv6=str(ipv6_dhcpv6))
        ipv6.interface = self
        ipv6.save()
        return

1053 1054 1055 1056 1057 1058 1059 1060
    def sync_ipv6_slaac(self):
        """Cree, mets à jour et supprime si il y a lieu l'ipv6 slaac associée
        à la machine
        Sans prefixe ipv6, on return
        Si l'ip slaac n'est pas celle qu'elle devrait être, on maj"""
        ipv6_slaac = self.ipv6_slaac
        if not ipv6_slaac:
            return
1061 1062 1063
        ipv6_object = (Ipv6List.objects
                       .filter(interface=self, slaac_ip=True)
                       .first())
1064 1065 1066 1067 1068 1069
        if not ipv6_object:
            ipv6_object = Ipv6List(interface=self, slaac_ip=True)
        if ipv6_object.ipv6 != str(ipv6_slaac):
            ipv6_object.ipv6 = str(ipv6_slaac)
            ipv6_object.save()

1070 1071
    def sync_ipv6(self):
        """Cree et met à jour l'ensemble des ipv6 en fonction du mode choisi"""
1072 1073
        if (preferences.models.OptionalMachine
                .get_cached_value('ipv6_mode') == 'SLAAC'):
1074
            self.sync_ipv6_slaac()
1075
        elif (preferences.models.OptionalMachine
erdnaxe's avatar
erdnaxe committed
1076
                      .get_cached_value('ipv6_mode') == 'DHCPV6'):
1077 1078 1079 1080
            self.sync_ipv6_dhcpv6()
        else:
            return

1081
    def ipv6(self):
1082
        """ Renvoie le queryset de la liste des ipv6
1083 1084 1085 1086
        On renvoie l'ipv6 slaac que si le mode slaac est activé
        (et non dhcpv6)"""
        if (preferences.models.OptionalMachine
                .get_cached_value('ipv6_mode') == 'SLAAC'):
1087
            return self.ipv6list.all()
1088
        elif (preferences.models.OptionalMachine
erdnaxe's avatar
erdnaxe committed
1089
                      .get_cached_value('ipv6_mode') == 'DHCPV6'):
1090
            return self.ipv6list.filter(slaac_ip=False)
1091 1092
        else:
            return None
1093

1094
    def mac_bare(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1095
        """ Formatage de la mac type mac_bare"""
1096 1097
        return str(EUI(self.mac_address, dialect=mac_bare)).lower()

1098
    def filter_macaddress(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1099 1100
        """ Tente un formatage mac_bare, si échoue, lève une erreur de
        validation"""
1101 1102
        try:
            self.mac_address = str(EUI(self.mac_address))
Gabriel Detraz's avatar
Gabriel Detraz committed
1103
        except:
1104
            raise ValidationError(_("The given MAC address is invalid."))
1105

1106
    def clean(self, *args, **kwargs):
Gabriel Detraz's avatar
Gabriel Detraz committed
1107 1108
        """ Formate l'addresse mac en mac_bare (fonction filter_mac)
        et assigne une ipv4 dans le bon range si inexistante ou incohérente"""
1109 1110 1111 1112 1113 1114 1115
        # If type was an invalid value, django won't create an attribute type
        # but try clean() as we may be able to create it from another value
        # so even if the error as yet been detected at this point, django
        # continues because the error might not prevent us from creating the
        # instance.
        # But in our case, it's impossible to create a type value so we raise
        # the error.
1116
        if not hasattr(self, 'type'):
1117
            raise ValidationError(_("The selected IP type is invalid."))
1118
        self.filter_macaddress()
1119
        self.mac_address = str(EUI(self.mac_address)) or None
1120
        if not self.ipv4 or self.type.ip_type != self.ipv4.ip_type:
1121
            self.assign_ipv4()
1122
        super(Interface, self).clean(*args, **kwargs)
1123 1124 1125 1126 1127 1128 1129

    def assign_ipv4(self):
        """ Assigne une ip à l'interface """
        free_ips = self.type.ip_type.free_ip()
        if free_ips:
            self.ipv4 = free_ips[0]
        else:
1130 1131
            raise ValidationError(_("There is no IP address available in the"
                                    " slash."))
1132 1133 1134
        return

    def unassign_ipv4(self):
Gabriel Detraz's avatar
Gabriel Detraz committed
1135
        """ Sans commentaire, désassigne une ipv4"""
1136
        self.ipv4 = None
1137

1138 1139 1140 1141 1142
    def update_type(self):
        """ Lorsque le machinetype est changé de type d'ip, on réassigne"""
        self.clean()
        self.save()

1143
    def save(self, *args, **kwargs):
1144
        self.filter_macaddress()
1145
        # On verifie la cohérence en forçant l'extension par la méthode
1146 1147
        if self.ipv4:
            if self.type.ip_type != self.ipv4.ip_type:
1148 1149
                raise ValidationError(_("The IPv4 address and the machine type"
                                        " don't match."))
1150 1151
        super(Interface, self).save(*args, **kwargs)

1152 1153
    @staticmethod
    def can_create(user_request, machineid, *_args, **_kwargs):
1154 1155 1156 1157 1158
        """Verifie que l'user a les bons droits infra pour créer
        une interface, ou bien que la machine appartient bien à l'user
        :param macineid: Id de la machine parente de l'interface
        :param user_request: instance utilisateur qui fait la requête
        :return: soit True, soit False avec la raison de l'échec"""
1159
        try:
1160
            machine = Machine.objects.get(pk=machineid)
1161
        except Machine.DoesNotExist:
1162
            return False, _("Nonexistent machine.")
1163
        if not user_request.has_perm('machines.add_interface'):
1164 1165
            if not (preferences.models.OptionalMachine
                    .get_cached_value('create_machine')):
1166
                return False, _("You can't add a machine.")
1167
            max_lambdauser_interfaces = (preferences.models.OptionalMachine
erdnaxe's avatar
erdnaxe committed
1168 1169 1170
                .get_cached_value(
                'max_lambdauser_interfaces'
            ))
1171
            if machine.user != user_request:
1172 1173
                return False, _("You don't have the right to add an interface"
                                " to a machine of another user.")
1174 1175
            if (machine.user.user_interfaces().count() >=
                    max_lambdauser_interfaces):
1176 1177 1178
                return False, (_("You reached the maximum number of interfaces"
                                 " that you are allowed to create yourself"
                                 " (%s)." % max_lambdauser_interfaces))
1179 1180
        return True, None

1181
    @staticmethod