1# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
2# Copyright (C) 2014 YAMAMOTO Takashi <yamamoto at valinux co jp>
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8#    http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
13# implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import platform
18import socket
19import struct
20
21from ryu.lib import addrconv
22
23
24system = platform.system()
25if system == 'Linux':
26    # on linux,
27    #    no ss_len
28    #    u16 ss_family
29    _HDR_FMT = "H"
30    _HAVE_SS_LEN = False
31else:
32    # assume
33    #    u8 ss_len
34    #    u8 ss_family
35    _HDR_FMT = "BB"
36    _HAVE_SS_LEN = True
37
38
39# RFC 2553
40_SS_MAXSIZE = 128
41_SS_ALIGNSIZE = 8
42
43_SIN_SIZE = 16  # sizeof(struct sockaddr_in)
44
45_HDR_LEN = struct.calcsize(_HDR_FMT)
46
47
48def _hdr(ss_len, af):
49    if _HAVE_SS_LEN:
50        return struct.pack(_HDR_FMT, ss_len, af)
51    else:
52        return struct.pack(_HDR_FMT, af)
53
54
55def _pad_to(data, total_len):
56    pad_len = total_len - len(data)
57    return data + pad_len * '\0'
58
59
60def sa_in4(addr, port=0):
61    data = struct.pack("!H4s", port, addrconv.ipv4.text_to_bin(addr))
62    hdr = _hdr(_SIN_SIZE, socket.AF_INET)
63    return _pad_to(hdr + data, _SIN_SIZE)
64
65
66def sa_in6(addr, port=0, flowinfo=0, scope_id=0):
67    data = struct.pack("!HI16sI", port, flowinfo,
68                       addrconv.ipv6.text_to_bin(addr), scope_id)
69    hdr = _hdr(_HDR_LEN + len(data), socket.AF_INET6)
70    return hdr + data
71
72
73def sa_to_ss(sa):
74    return _pad_to(sa, _SS_MAXSIZE)
75