backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / lib / sockopt.py
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
17 import platform
18 import socket
19 import struct
20
21 from ryu.lib import sockaddr
22
23
24 TCP_MD5SIG_LINUX = 0x0e
25 TCP_MD5SIG_BSD = 0x10
26
27
28 def _set_tcp_md5sig_linux(s, addr, key):
29     # struct tcp_md5sig {
30     #     struct sockaddr_storage addr;
31     #     u16 pad1;
32     #     u16 keylen;
33     #     u32 pad2;
34     #     u8 key[80];
35     # }
36     af = s.family
37     if af == socket.AF_INET:
38         sa = sockaddr.sa_in4(addr)
39     elif af == socket.AF_INET6:
40         sa = sockaddr.sa_in6(addr)
41     else:
42         raise ValueError("unsupported af %s" % (af,))
43     ss = sockaddr.sa_to_ss(sa)
44     tcp_md5sig = ss + struct.pack("2xH4x80s", len(key), key)
45     s.setsockopt(socket.IPPROTO_TCP, TCP_MD5SIG_LINUX, tcp_md5sig)
46
47
48 def _set_tcp_md5sig_bsd(s, _addr, _key):
49     # NOTE: On this platform, address and key need to be set using setkey(8).
50     tcp_md5sig = struct.pack("I", 1)
51     s.setsockopt(socket.IPPROTO_TCP, TCP_MD5SIG_BSD, tcp_md5sig)
52
53
54 def set_tcp_md5sig(s, addr, key):
55     """Enable TCP-MD5 on the given socket.
56
57     :param s: Socket
58     :param addr: Associated address.  On some platforms, this has no effect.
59     :param key: Key.  On some platforms, this has no effect.
60     """
61     impls = {
62         'FreeBSD': _set_tcp_md5sig_bsd,
63         'Linux': _set_tcp_md5sig_linux,
64         'NetBSD': _set_tcp_md5sig_bsd,
65     }
66     system = platform.system()
67     try:
68         impl = impls[system]
69     except KeyError:
70         raise NotImplementedError("TCP-MD5 unsupported on this platform")
71     impl(s, addr, key)