1 # Copyright (C) 2012 Nippon Telegraph and Telephone Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
19 from . import packet_base
25 from . import in_proto as inet
26 from ryu.lib import addrconv
27 from ryu.lib import stringify
30 IPV6_ADDRESS_PACK_STR = '!16s'
31 IPV6_ADDRESS_LEN = struct.calcsize(IPV6_ADDRESS_PACK_STR)
32 IPV6_PSEUDO_HEADER_PACK_STR = '!16s16s3xB'
35 class ipv6(packet_base.PacketBase):
36 """IPv6 (RFC 2460) header encoder/decoder class.
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.
43 .. tabularcolumns:: |l|p{30em}|l|
45 ============== ======================================== ==================
46 Attribute Description Example
47 ============== ======================================== ==================
49 traffic_class Traffic Class
50 flow_label When decoding, Flow Label.
51 When encoding, the most significant 8
53 payload_length Payload Length
56 src Source Address 'ff02::1'
57 dst Destination Address '::'
58 ext_hdrs Extension Headers
59 ============== ======================================== ==================
62 _PACK_STR = '!IHBB16s16s'
63 _MIN_LEN = struct.calcsize(_PACK_STR)
64 _IPV6_EXT_HEADER_TYPE = {}
72 def register_header_type(type_):
73 def _register_header_type(cls):
74 ipv6._IPV6_EXT_HEADER_TYPE[type_] = cls
76 return _register_header_type
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
87 self.hop_limit = hop_limit
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
98 (v_tc_flow, payload_length, nxt, hlim, src, dst) = struct.unpack_from(
100 version = v_tc_flow >> 28
101 traffic_class = (v_tc_flow >> 20) & 0xff
102 flow_label = v_tc_flow & 0xfffff
104 offset = cls._MIN_LEN
108 cls_ = cls._IPV6_EXT_HEADER_TYPE.get(last)
111 hdr = cls_.parser(buf[offset:])
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])
121 def serialize(self, payload, prev):
123 v_tc_flow = (self.version << 28 | self.traffic_class << 20 |
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))
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)
142 for ext_hdr in self.ext_hdrs:
143 ext_hdrs_len += len(ext_hdr)
144 return self._MIN_LEN + ext_hdrs_len
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)
154 @six.add_metaclass(abc.ABCMeta)
155 class header(stringify.StringifyMixin):
156 """extension header abstract class."""
158 def __init__(self, nxt):
163 def parser(cls, buf):
175 class opt_header(header):
176 """an abstract class for Hop-by-Hop Options header and destination
180 _MIN_LEN = struct.calcsize(_PACK_STR)
182 _class_prefixes = ['option']
185 def __init__(self, nxt, size, data):
186 super(opt_header, self).__init__(nxt)
187 assert not (size % 8)
192 def parser(cls, buf):
193 (nxt, len_) = struct.unpack_from(cls._PACK_STR, buf)
194 data_len = cls._FIX_SIZE + int(len_)
197 while size < data_len:
198 (type_, ) = struct.unpack_from('!B', buf[size:])
200 opt = option(type_, -1, None)
203 opt = option.parser(buf[size:])
206 return cls(nxt, len_, data)
209 buf = struct.pack(self._PACK_STR, self.nxt, self.size)
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())
219 return self._FIX_SIZE + self.size
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.
226 This is used with ryu.lib.packet.ipv6.ipv6.
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.
232 .. tabularcolumns:: |l|L|
234 ============== =======================================
235 Attribute Description
236 ============== =======================================
238 size the length of the Hop-by-Hop Options header,
239 not include the first 8 octet.
241 ============== =======================================
243 TYPE = inet.IPPROTO_HOPOPTS
245 def __init__(self, nxt=inet.IPPROTO_TCP, size=0, data=None):
246 super(hop_opts, self).__init__(nxt, size, data)
249 @ipv6.register_header_type(inet.IPPROTO_DSTOPTS)
250 class dst_opts(opt_header):
251 """IPv6 (RFC 2460) destination header encoder/decoder class.
253 This is used with ryu.lib.packet.ipv6.ipv6.
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.
259 .. tabularcolumns:: |l|L|
261 ============== =======================================
262 Attribute Description
263 ============== =======================================
265 size the length of the destination header,
266 not include the first 8 octet.
268 ============== =======================================
270 TYPE = inet.IPPROTO_DSTOPTS
272 def __init__(self, nxt=inet.IPPROTO_TCP, size=0, data=None):
273 super(dst_opts, self).__init__(nxt, size, data)
276 class option(stringify.StringifyMixin):
277 r"""IPv6 (RFC 2460) Options header encoder/decoder class.
279 This is used with ryu.lib.packet.ipv6.hop_opts or
280 ryu.lib.packet.ipv6.dst_opts.
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.
286 .. tabularcolumns:: |l|L|
288 ============== =======================================
289 Attribute Description
290 ============== =======================================
292 len\_ the length of data. -1 if type\_ is 0.
293 data an option value. None if len\_ is 0 or -1.
294 ============== =======================================
298 _MIN_LEN = struct.calcsize(_PACK_STR)
300 def __init__(self, type_=0, len_=-1, data=None):
306 def parser(cls, buf):
307 (type_, ) = struct.unpack_from('!B', buf)
309 cls_ = cls(type_, -1, None)
312 (type_, len_) = struct.unpack_from(cls._PACK_STR, buf)
315 (data, ) = struct.unpack_from(form, buf, cls._MIN_LEN)
316 cls_ = cls(type_, len_, data)
322 data = struct.pack('!B', self.type_)
324 data = struct.pack(self._PACK_STR, self.type_, self.len_)
326 form = "%ds" % self.len_
327 data = struct.pack(self._PACK_STR + form, self.type_,
328 self.len_, self.data)
332 return self._MIN_LEN + self.len_
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.
340 IPv6 Routing Header types.
342 http://www.iana.org/assignments/ipv6-parameters/ipv6-parameters.xhtml
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 +-----------+----------------------------------+-------------------+
362 +-----------+----------------------------------+-------------------+
365 TYPE = inet.IPPROTO_ROUTING
367 _OFFSET_LEN = struct.calcsize('!2B')
369 # IPv6 Routing Header Type
370 ROUTING_TYPE_2 = 0x02
371 ROUTING_TYPE_3 = 0x03
374 def parser(cls, buf):
375 (type_, ) = struct.unpack_from('!B', buf, cls._OFFSET_LEN)
377 # TODO: make parsers of type2.
378 cls.ROUTING_TYPE_2: None,
379 cls.ROUTING_TYPE_3: routing_type3
381 cls_ = switch.get(type_)
383 return cls_.parser(buf)
388 class routing_type3(header):
390 An IPv6 Routing Header for Source Routes with the RPL (RFC 6554)
391 encoder/decoder class.
393 This is used with ryu.lib.packet.ipv6.ipv6.
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.
399 .. tabularcolumns:: |l|L|
401 ============== =======================================
402 Attribute Description
403 ============== =======================================
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 ============== =======================================
418 _PACK_STR = '!BBBBBB2x'
419 _MIN_LEN = struct.calcsize(_PACK_STR)
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)
435 assert isinstance(adrs, list)
437 self._pad = (8 - ((len(self.adrs) - 1) * (16 - self.cmpi) +
438 (16 - self.cmpe) % 8)) % 8
441 def _get_size(cls, size):
442 return (int(size) + 1) * 8
445 def parser(cls, buf):
446 (nxt, size, type_, seg, cmp_, pad) = struct.unpack_from(
449 header_len = cls._get_size(size)
450 cmpi = int(cmp_ >> 4)
451 cmpe = int(cmp_ & 0xf)
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))
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)
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,
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]:
487 form_i, addrconv.ipv6.text_to_bin(adr)[slice_i]))
488 buf.extend(struct.pack(
490 addrconv.ipv6.text_to_bin(self.adrs[-1])[slice_e]))
494 return routing_type3._get_size(self.size)
497 @ipv6.register_header_type(inet.IPPROTO_FRAGMENT)
498 class fragment(header):
499 r"""IPv6 (RFC 2460) fragment header encoder/decoder class.
501 This is used with ryu.lib.packet.ipv6.ipv6.
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.
507 .. tabularcolumns:: |l|L|
509 ============== =======================================
510 Attribute Description
511 ============== =======================================
513 offset offset, in 8-octet units, relative to
514 the start of the fragmentable part of
516 more 1 means more fragments follow;
517 0 means last fragment.
518 id\_ packet identification value.
519 ============== =======================================
521 TYPE = inet.IPPROTO_FRAGMENT
524 _MIN_LEN = struct.calcsize(_PACK_STR)
526 def __init__(self, nxt=inet.IPPROTO_TCP, offset=0, more=0, id_=0):
527 super(fragment, self).__init__(nxt)
533 def parser(cls, buf):
534 (nxt, off_m, id_) = struct.unpack_from(cls._PACK_STR, buf)
537 return cls(nxt, offset, more, id_)
540 off_m = (self.offset << 3 | self.more)
541 buf = struct.pack(self._PACK_STR, self.nxt, off_m, self.id_)
548 @ipv6.register_header_type(inet.IPPROTO_AH)
550 """IP Authentication header (RFC 2402) encoder/decoder class.
552 This is used with ryu.lib.packet.ipv6.ipv6.
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.
558 .. tabularcolumns:: |l|L|
560 ============== =======================================
561 Attribute Description
562 ============== =======================================
564 size the length of the Authentication Header
565 in 64-bit words, subtracting 1.
566 spi security parameters index.
568 data authentication data.
569 ============== =======================================
571 TYPE = inet.IPPROTO_AH
573 _PACK_STR = '!BB2xII'
574 _MIN_LEN = struct.calcsize(_PACK_STR)
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
586 def _get_size(cls, size):
587 return (int(size) + 2) * 4
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)
597 buf = struct.pack(self._PACK_STR, self.nxt, self.size, self.spi,
600 form = "%ds" % (auth._get_size(self.size) - self._MIN_LEN)
601 buf.extend(struct.pack(form, self.data))
605 return auth._get_size(self.size)
608 ipv6.set_classes(ipv6._IPV6_EXT_HEADER_TYPE)