backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / lib / packet / ipv6.py
1 # Copyright (C) 2012 Nippon Telegraph and Telephone Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 import abc
17 import six
18 import struct
19 from . import packet_base
20 from . import icmpv6
21 from . import tcp
22 from . import udp
23 from . import sctp
24 from . import gre
25 from . import in_proto as inet
26 from ryu.lib import addrconv
27 from ryu.lib import stringify
28
29
30 IPV6_ADDRESS_PACK_STR = '!16s'
31 IPV6_ADDRESS_LEN = struct.calcsize(IPV6_ADDRESS_PACK_STR)
32 IPV6_PSEUDO_HEADER_PACK_STR = '!16s16s3xB'
33
34
35 class ipv6(packet_base.PacketBase):
36     """IPv6 (RFC 2460) header encoder/decoder class.
37
38     An instance has the following attributes at least.
39     Most of them are same to the on-wire counterparts but in host byte order.
40     IPv6 addresses are represented as a string like 'ff02::1'.
41     __init__ takes the corresponding args in this order.
42
43     .. tabularcolumns:: |l|p{30em}|l|
44
45     ============== ======================================== ==================
46     Attribute      Description                              Example
47     ============== ======================================== ==================
48     version        Version
49     traffic_class  Traffic Class
50     flow_label     When decoding, Flow Label.
51                    When encoding, the most significant 8
52                    bits of Flow Label.
53     payload_length Payload Length
54     nxt            Next Header
55     hop_limit      Hop Limit
56     src            Source Address                           'ff02::1'
57     dst            Destination Address                      '::'
58     ext_hdrs       Extension Headers
59     ============== ======================================== ==================
60     """
61
62     _PACK_STR = '!IHBB16s16s'
63     _MIN_LEN = struct.calcsize(_PACK_STR)
64     _IPV6_EXT_HEADER_TYPE = {}
65     _TYPE = {
66         'ascii': [
67             'src', 'dst'
68         ]
69     }
70
71     @staticmethod
72     def register_header_type(type_):
73         def _register_header_type(cls):
74             ipv6._IPV6_EXT_HEADER_TYPE[type_] = cls
75             return cls
76         return _register_header_type
77
78     def __init__(self, version=6, traffic_class=0, flow_label=0,
79                  payload_length=0, nxt=inet.IPPROTO_TCP, hop_limit=255,
80                  src='10::10', dst='20::20', ext_hdrs=None):
81         super(ipv6, self).__init__()
82         self.version = version
83         self.traffic_class = traffic_class
84         self.flow_label = flow_label
85         self.payload_length = payload_length
86         self.nxt = nxt
87         self.hop_limit = hop_limit
88         self.src = src
89         self.dst = dst
90         ext_hdrs = ext_hdrs or []
91         assert isinstance(ext_hdrs, list)
92         for ext_hdr in ext_hdrs:
93             assert isinstance(ext_hdr, header)
94         self.ext_hdrs = ext_hdrs
95
96     @classmethod
97     def parser(cls, buf):
98         (v_tc_flow, payload_length, nxt, hlim, src, dst) = struct.unpack_from(
99             cls._PACK_STR, buf)
100         version = v_tc_flow >> 28
101         traffic_class = (v_tc_flow >> 20) & 0xff
102         flow_label = v_tc_flow & 0xfffff
103         hop_limit = hlim
104         offset = cls._MIN_LEN
105         last = nxt
106         ext_hdrs = []
107         while True:
108             cls_ = cls._IPV6_EXT_HEADER_TYPE.get(last)
109             if not cls_:
110                 break
111             hdr = cls_.parser(buf[offset:])
112             ext_hdrs.append(hdr)
113             offset += len(hdr)
114             last = hdr.nxt
115         msg = cls(version, traffic_class, flow_label, payload_length,
116                   nxt, hop_limit, addrconv.ipv6.bin_to_text(src),
117                   addrconv.ipv6.bin_to_text(dst), ext_hdrs)
118         return (msg, ipv6.get_packet_type(last),
119                 buf[offset:offset + payload_length])
120
121     def serialize(self, payload, prev):
122         hdr = bytearray(40)
123         v_tc_flow = (self.version << 28 | self.traffic_class << 20 |
124                      self.flow_label)
125         struct.pack_into(ipv6._PACK_STR, hdr, 0, v_tc_flow,
126                          self.payload_length, self.nxt, self.hop_limit,
127                          addrconv.ipv6.text_to_bin(self.src),
128                          addrconv.ipv6.text_to_bin(self.dst))
129         if self.ext_hdrs:
130             for ext_hdr in self.ext_hdrs:
131                 hdr.extend(ext_hdr.serialize())
132         if 0 == self.payload_length:
133             payload_length = len(payload)
134             for ext_hdr in self.ext_hdrs:
135                 payload_length += len(ext_hdr)
136             self.payload_length = payload_length
137             struct.pack_into('!H', hdr, 4, self.payload_length)
138         return hdr
139
140     def __len__(self):
141         ext_hdrs_len = 0
142         for ext_hdr in self.ext_hdrs:
143             ext_hdrs_len += len(ext_hdr)
144         return self._MIN_LEN + ext_hdrs_len
145
146
147 ipv6.register_packet_type(icmpv6.icmpv6, inet.IPPROTO_ICMPV6)
148 ipv6.register_packet_type(tcp.tcp, inet.IPPROTO_TCP)
149 ipv6.register_packet_type(udp.udp, inet.IPPROTO_UDP)
150 ipv6.register_packet_type(sctp.sctp, inet.IPPROTO_SCTP)
151 ipv6.register_packet_type(gre.gre, inet.IPPROTO_GRE)
152
153
154 @six.add_metaclass(abc.ABCMeta)
155 class header(stringify.StringifyMixin):
156     """extension header abstract class."""
157
158     def __init__(self, nxt):
159         self.nxt = nxt
160
161     @classmethod
162     @abc.abstractmethod
163     def parser(cls, buf):
164         pass
165
166     @abc.abstractmethod
167     def serialize(self):
168         pass
169
170     @abc.abstractmethod
171     def __len__(self):
172         pass
173
174
175 class opt_header(header):
176     """an abstract class for Hop-by-Hop Options header and destination
177     header."""
178
179     _PACK_STR = '!BB'
180     _MIN_LEN = struct.calcsize(_PACK_STR)
181     _FIX_SIZE = 8
182     _class_prefixes = ['option']
183
184     @abc.abstractmethod
185     def __init__(self, nxt, size, data):
186         super(opt_header, self).__init__(nxt)
187         assert not (size % 8)
188         self.size = size
189         self.data = data
190
191     @classmethod
192     def parser(cls, buf):
193         (nxt, len_) = struct.unpack_from(cls._PACK_STR, buf)
194         data_len = cls._FIX_SIZE + int(len_)
195         data = []
196         size = cls._MIN_LEN
197         while size < data_len:
198             (type_, ) = struct.unpack_from('!B', buf[size:])
199             if type_ == 0:
200                 opt = option(type_, -1, None)
201                 size += 1
202             else:
203                 opt = option.parser(buf[size:])
204                 size += len(opt)
205             data.append(opt)
206         return cls(nxt, len_, data)
207
208     def serialize(self):
209         buf = struct.pack(self._PACK_STR, self.nxt, self.size)
210         buf = bytearray(buf)
211         if self.data is None:
212             self.data = [option(type_=1, len_=4,
213                                 data=b'\x00\x00\x00\x00')]
214         for opt in self.data:
215             buf.extend(opt.serialize())
216         return buf
217
218     def __len__(self):
219         return self._FIX_SIZE + self.size
220
221
222 @ipv6.register_header_type(inet.IPPROTO_HOPOPTS)
223 class hop_opts(opt_header):
224     """IPv6 (RFC 2460) Hop-by-Hop Options header encoder/decoder class.
225
226     This is used with ryu.lib.packet.ipv6.ipv6.
227
228     An instance has the following attributes at least.
229     Most of them are same to the on-wire counterparts but in host byte order.
230     __init__ takes the corresponding args in this order.
231
232     .. tabularcolumns:: |l|L|
233
234     ============== =======================================
235     Attribute      Description
236     ============== =======================================
237     nxt            Next Header
238     size           the length of the Hop-by-Hop Options header,
239                    not include the first 8 octet.
240     data           IPv6 options.
241     ============== =======================================
242     """
243     TYPE = inet.IPPROTO_HOPOPTS
244
245     def __init__(self, nxt=inet.IPPROTO_TCP, size=0, data=None):
246         super(hop_opts, self).__init__(nxt, size, data)
247
248
249 @ipv6.register_header_type(inet.IPPROTO_DSTOPTS)
250 class dst_opts(opt_header):
251     """IPv6 (RFC 2460) destination header encoder/decoder class.
252
253     This is used with ryu.lib.packet.ipv6.ipv6.
254
255     An instance has the following attributes at least.
256     Most of them are same to the on-wire counterparts but in host byte order.
257     __init__ takes the corresponding args in this order.
258
259     .. tabularcolumns:: |l|L|
260
261     ============== =======================================
262     Attribute      Description
263     ============== =======================================
264     nxt            Next Header
265     size           the length of the destination header,
266                    not include the first 8 octet.
267     data           IPv6 options.
268     ============== =======================================
269     """
270     TYPE = inet.IPPROTO_DSTOPTS
271
272     def __init__(self, nxt=inet.IPPROTO_TCP, size=0, data=None):
273         super(dst_opts, self).__init__(nxt, size, data)
274
275
276 class option(stringify.StringifyMixin):
277     r"""IPv6 (RFC 2460) Options header encoder/decoder class.
278
279     This is used with ryu.lib.packet.ipv6.hop_opts or
280                       ryu.lib.packet.ipv6.dst_opts.
281
282     An instance has the following attributes at least.
283     Most of them are same to the on-wire counterparts but in host byte order.
284     __init__ takes the corresponding args in this order.
285
286     .. tabularcolumns:: |l|L|
287
288     ============== =======================================
289     Attribute      Description
290     ============== =======================================
291     type\_         option type.
292     len\_          the length of data. -1 if type\_ is 0.
293     data           an option value. None if len\_ is 0 or -1.
294     ============== =======================================
295     """
296
297     _PACK_STR = '!BB'
298     _MIN_LEN = struct.calcsize(_PACK_STR)
299
300     def __init__(self, type_=0, len_=-1, data=None):
301         self.type_ = type_
302         self.len_ = len_
303         self.data = data
304
305     @classmethod
306     def parser(cls, buf):
307         (type_, ) = struct.unpack_from('!B', buf)
308         if not type_:
309             cls_ = cls(type_, -1, None)
310         else:
311             data = None
312             (type_, len_) = struct.unpack_from(cls._PACK_STR, buf)
313             if len_:
314                 form = "%ds" % len_
315                 (data, ) = struct.unpack_from(form, buf, cls._MIN_LEN)
316             cls_ = cls(type_, len_, data)
317         return cls_
318
319     def serialize(self):
320         data = None
321         if not self.type_:
322             data = struct.pack('!B', self.type_)
323         elif not self.len_:
324             data = struct.pack(self._PACK_STR, self.type_, self.len_)
325         else:
326             form = "%ds" % self.len_
327             data = struct.pack(self._PACK_STR + form, self.type_,
328                                self.len_, self.data)
329         return data
330
331     def __len__(self):
332         return self._MIN_LEN + self.len_
333
334
335 @ipv6.register_header_type(inet.IPPROTO_ROUTING)
336 class routing(header):
337     """An IPv6 Routing Header decoder class.
338     This class has only the parser method.
339
340     IPv6 Routing Header types.
341
342     http://www.iana.org/assignments/ipv6-parameters/ipv6-parameters.xhtml
343
344     +-----------+----------------------------------+-------------------+
345     | Value     | Description                      | Reference         |
346     +===========+==================================+===================+
347     | 0         | Source Route (DEPRECATED)        | [[IPV6]][RFC5095] |
348     +-----------+----------------------------------+-------------------+
349     | 1         | Nimrod (DEPRECATED 2009-05-06)   |                   |
350     +-----------+----------------------------------+-------------------+
351     | 2         | Type 2 Routing Header            | [RFC6275]         |
352     +-----------+----------------------------------+-------------------+
353     | 3         | RPL Source Route Header          | [RFC6554]         |
354     +-----------+----------------------------------+-------------------+
355     | 4 - 252   | Unassigned                       |                   |
356     +-----------+----------------------------------+-------------------+
357     | 253       | RFC3692-style Experiment 1 [2]   | [RFC4727]         |
358     +-----------+----------------------------------+-------------------+
359     | 254       | RFC3692-style Experiment 2 [2]   | [RFC4727]         |
360     +-----------+----------------------------------+-------------------+
361     | 255       | Reserved                         |                   |
362     +-----------+----------------------------------+-------------------+
363     """
364
365     TYPE = inet.IPPROTO_ROUTING
366
367     _OFFSET_LEN = struct.calcsize('!2B')
368
369     # IPv6 Routing Header Type
370     ROUTING_TYPE_2 = 0x02
371     ROUTING_TYPE_3 = 0x03
372
373     @classmethod
374     def parser(cls, buf):
375         (type_, ) = struct.unpack_from('!B', buf, cls._OFFSET_LEN)
376         switch = {
377             # TODO: make parsers of type2.
378             cls.ROUTING_TYPE_2: None,
379             cls.ROUTING_TYPE_3: routing_type3
380         }
381         cls_ = switch.get(type_)
382         if cls_:
383             return cls_.parser(buf)
384         else:
385             return None
386
387
388 class routing_type3(header):
389     """
390     An IPv6 Routing Header for Source Routes with the RPL (RFC 6554)
391     encoder/decoder class.
392
393     This is used with ryu.lib.packet.ipv6.ipv6.
394
395     An instance has the following attributes at least.
396     Most of them are same to the on-wire counterparts but in host byte order.
397     __init__ takes the corresponding args in this order.
398
399     .. tabularcolumns:: |l|L|
400
401     ============== =======================================
402     Attribute      Description
403     ============== =======================================
404     nxt            Next Header
405     size           The length of the Routing header,
406                    not include the first 8 octet.
407                    (0 means automatically-calculate when encoding)
408     type           Identifies the particular Routing header variant.
409     seg            Number of route segments remaining.
410     cmpi           Number of prefix octets from segments 1 through n-1.
411     cmpe           Number of prefix octets from segment n.
412     pad            Number of octets that are used for padding
413                    after Address[n] at the end of the SRH.
414     adrs           Vector of addresses, numbered 1 to n.
415     ============== =======================================
416     """
417
418     _PACK_STR = '!BBBBBB2x'
419     _MIN_LEN = struct.calcsize(_PACK_STR)
420     _TYPE = {
421         'asciilist': [
422             'adrs'
423         ]
424     }
425
426     def __init__(self, nxt=inet.IPPROTO_TCP, size=0,
427                  type_=3, seg=0, cmpi=0, cmpe=0, adrs=None):
428         super(routing_type3, self).__init__(nxt)
429         self.size = size
430         self.type_ = type_
431         self.seg = seg
432         self.cmpi = cmpi
433         self.cmpe = cmpe
434         adrs = adrs or []
435         assert isinstance(adrs, list)
436         self.adrs = adrs
437         self._pad = (8 - ((len(self.adrs) - 1) * (16 - self.cmpi) +
438                           (16 - self.cmpe) % 8)) % 8
439
440     @classmethod
441     def _get_size(cls, size):
442         return (int(size) + 1) * 8
443
444     @classmethod
445     def parser(cls, buf):
446         (nxt, size, type_, seg, cmp_, pad) = struct.unpack_from(
447             cls._PACK_STR, buf)
448         data = cls._MIN_LEN
449         header_len = cls._get_size(size)
450         cmpi = int(cmp_ >> 4)
451         cmpe = int(cmp_ & 0xf)
452         pad = int(pad >> 4)
453         adrs = []
454         if size:
455             # Address[1..n-1] has size (16 - CmprI) octets
456             adrs_len_i = 16 - cmpi
457             # Address[n] has size (16 - CmprE) octets
458             adrs_len_e = 16 - cmpe
459             form_i = "%ds" % adrs_len_i
460             form_e = "%ds" % adrs_len_e
461             while data < (header_len - (adrs_len_e + pad)):
462                 (adr, ) = struct.unpack_from(form_i, buf[data:])
463                 adr = (b'\x00' * cmpi) + adr
464                 adrs.append(addrconv.ipv6.bin_to_text(adr))
465                 data += adrs_len_i
466             (adr, ) = struct.unpack_from(form_e, buf[data:])
467             adr = (b'\x00' * cmpe) + adr
468             adrs.append(addrconv.ipv6.bin_to_text(adr))
469         return cls(nxt, size, type_, seg, cmpi, cmpe, adrs)
470
471     def serialize(self):
472         if self.size == 0:
473             self.size = ((len(self.adrs) - 1) * (16 - self.cmpi) +
474                          (16 - self.cmpe) + self._pad) // 8
475         buf = struct.pack(self._PACK_STR, self.nxt, self.size,
476                           self.type_, self.seg, (self.cmpi << 4) | self.cmpe,
477                           self._pad << 4)
478         buf = bytearray(buf)
479         if self.size:
480             form_i = "%ds" % (16 - self.cmpi)
481             form_e = "%ds" % (16 - self.cmpe)
482             slice_i = slice(self.cmpi, 16)
483             slice_e = slice(self.cmpe, 16)
484             for adr in self.adrs[:-1]:
485                 buf.extend(
486                     struct.pack(
487                         form_i, addrconv.ipv6.text_to_bin(adr)[slice_i]))
488             buf.extend(struct.pack(
489                 form_e,
490                 addrconv.ipv6.text_to_bin(self.adrs[-1])[slice_e]))
491         return buf
492
493     def __len__(self):
494         return routing_type3._get_size(self.size)
495
496
497 @ipv6.register_header_type(inet.IPPROTO_FRAGMENT)
498 class fragment(header):
499     r"""IPv6 (RFC 2460) fragment header encoder/decoder class.
500
501     This is used with ryu.lib.packet.ipv6.ipv6.
502
503     An instance has the following attributes at least.
504     Most of them are same to the on-wire counterparts but in host byte order.
505     __init__ takes the corresponding args in this order.
506
507     .. tabularcolumns:: |l|L|
508
509     ============== =======================================
510     Attribute      Description
511     ============== =======================================
512     nxt            Next Header
513     offset         offset, in 8-octet units, relative to
514                    the start of the fragmentable part of
515                    the original packet.
516     more           1 means more fragments follow;
517                    0 means last fragment.
518     id\_           packet identification value.
519     ============== =======================================
520     """
521     TYPE = inet.IPPROTO_FRAGMENT
522
523     _PACK_STR = '!BxHI'
524     _MIN_LEN = struct.calcsize(_PACK_STR)
525
526     def __init__(self, nxt=inet.IPPROTO_TCP, offset=0, more=0, id_=0):
527         super(fragment, self).__init__(nxt)
528         self.offset = offset
529         self.more = more
530         self.id_ = id_
531
532     @classmethod
533     def parser(cls, buf):
534         (nxt, off_m, id_) = struct.unpack_from(cls._PACK_STR, buf)
535         offset = off_m >> 3
536         more = off_m & 0x1
537         return cls(nxt, offset, more, id_)
538
539     def serialize(self):
540         off_m = (self.offset << 3 | self.more)
541         buf = struct.pack(self._PACK_STR, self.nxt, off_m, self.id_)
542         return buf
543
544     def __len__(self):
545         return self._MIN_LEN
546
547
548 @ipv6.register_header_type(inet.IPPROTO_AH)
549 class auth(header):
550     """IP Authentication header (RFC 2402) encoder/decoder class.
551
552     This is used with ryu.lib.packet.ipv6.ipv6.
553
554     An instance has the following attributes at least.
555     Most of them are same to the on-wire counterparts but in host byte order.
556     __init__ takes the corresponding args in this order.
557
558     .. tabularcolumns:: |l|L|
559
560     ============== =======================================
561     Attribute      Description
562     ============== =======================================
563     nxt            Next Header
564     size           the length of the Authentication Header
565                    in 64-bit words, subtracting 1.
566     spi            security parameters index.
567     seq            sequence number.
568     data           authentication data.
569     ============== =======================================
570     """
571     TYPE = inet.IPPROTO_AH
572
573     _PACK_STR = '!BB2xII'
574     _MIN_LEN = struct.calcsize(_PACK_STR)
575
576     def __init__(self, nxt=inet.IPPROTO_TCP, size=2, spi=0, seq=0,
577                  data=b'\x00\x00\x00\x00'):
578         super(auth, self).__init__(nxt)
579         assert data is not None
580         self.size = size
581         self.spi = spi
582         self.seq = seq
583         self.data = data
584
585     @classmethod
586     def _get_size(cls, size):
587         return (int(size) + 2) * 4
588
589     @classmethod
590     def parser(cls, buf):
591         (nxt, size, spi, seq) = struct.unpack_from(cls._PACK_STR, buf)
592         form = "%ds" % (cls._get_size(size) - cls._MIN_LEN)
593         (data, ) = struct.unpack_from(form, buf, cls._MIN_LEN)
594         return cls(nxt, size, spi, seq, data)
595
596     def serialize(self):
597         buf = struct.pack(self._PACK_STR, self.nxt, self.size, self.spi,
598                           self.seq)
599         buf = bytearray(buf)
600         form = "%ds" % (auth._get_size(self.size) - self._MIN_LEN)
601         buf.extend(struct.pack(form, self.data))
602         return buf
603
604     def __len__(self):
605         return auth._get_size(self.size)
606
607
608 ipv6.set_classes(ipv6._IPV6_EXT_HEADER_TYPE)