#!/usr/bin/env python # -*- coding: utf-8 -*- # # MIDTOOLS.PY -- Gestion de la conversion mid <-> IP # # Copyright (C) 2010 Olivier Iffrig # Authors: Olivier Iffrig # # 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 3 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, see . import config import iptools class Mid(object): """ Permet de décortiquer un mid et d'obtenir les IP correspondantes """ def __init__(self, mid=None): if mid is not None: self.parse(mid) else: self.mid = None self.reste = False self.type = None self.ipv4_dispo = False self.priv = False def parse(self, mid): self.mid = mid self.type = None for tp in config.mid.keys(): if mid <= config.mid[tp][1] and mid >= config.mid[tp][0]: self.type = tp if self.type is None: raise ValueError("mid inconnu : %d" % mid) self.ipv4_dispo = False if (mid & (1 << 15)) == 0 and self.type != 'special': self.ipv4_dispo = True self.priv = True if (mid & (1 << 14)) == 0: self.priv = False self.reste = mid & 0x7ff # if self.type == 'ens': # Inutile pour l'instant # self.reste &= 0xff def from_ipv4(self, ip): """ Met à jour l' instance pour correspondre à l'IPv4 donnée """ self.ipv4_dispo = True self.priv = ip.startswith('10.') for tp in ['fil', 'wifi', 'adm', 'gratuit', 'ens']: if iptools.AddrInNet(ip, config.NETs[tp]): self.type = tp break if self.type is None: raise ValueError("Impossible de convertir l'adresse IP") self.mid = int(iptools.QuadToDec(ip)) self.mid -= int(iptools.param(config.NETs[self.type][0], True)['network']) self.reste = self.mid & 0x7ff return self.mid # if self.type == 'ens': # Inutile pour l'instant # self.reste &= 0xff def to_ipv4(self): """ Génère l'IPv4 associée à la machine """ if not self.ipv4_dispo: raise ValueError("Pas d'adresse ipv4 disponible pour la machine") ip = iptools.param(config.NETs[self.type][0], True)['network'] ip += self.reste return iptools.DecToQuad(ip) def to_ipv6_vlan(self): """ Génère le préfix IPv6 associé à la machine """ if self.priv: raise ValueError("Pas de prefix ipv6 disponible pour cette machine") ip = config.prefix['subnet'][0].split(":/")[0] ip += hex(self.mid)[2:] ip += "::/64" return ip