Fixing UdpTunnel unit tests for PlanetLab
[nepi.git] / src / nepi / resources / planetlab / scripts / pl-vif-create.py
1 #
2 #    NEPI, a framework to manage network experiments
3 #    Copyright (C) 2013 INRIA
4 #
5 #    This program is free software: you can redistribute it and/or modify
6 #    it under the terms of the GNU General Public License as published by
7 #    the Free Software Foundation, either version 3 of the License, or
8 #    (at your option) any later version.
9 #
10 #    This program is distributed in the hope that it will be useful,
11 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #    GNU General Public License for more details.
14 #
15 #    You should have received a copy of the GNU General Public License
16 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 #
18 # Author: Alina Quereilhac <alina.quereilhac@inria.fr>
19
20 import base64
21 import errno
22 import passfd
23 import socket
24 import vsys
25 from optparse import OptionParser, SUPPRESS_HELP
26
27 # TODO: GRE OPTION!! CONFIGURE THE VIF-UP IN GRE MODE!!
28
29 STOP_MSG = "STOP"
30 PASSFD_MSG = "PASSFD"
31
32 def create_socket(socket_name):
33     sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
34     sock.bind(socket_name)
35     return sock
36
37 def recv_msg(conn):
38     msg = []
39     chunk = ''
40
41     while '\n' not in chunk:
42         try:
43             chunk = conn.recv(1024)
44         except (OSError, socket.error), e:
45             if e[0] != errno.EINTR:
46                 raise
47             # Ignore eintr errors
48             continue
49
50         if chunk:
51             msg.append(chunk)
52         else:
53             # empty chunk = EOF
54             break
55
56     msg = ''.join(msg).split('\n')[0]
57     # The message might have arguments that will be appended
58     # as a '|' separated list after the message type
59     args = msg.split("|")
60     msg = args.pop(0)
61
62     dmsg = base64.b64decode(msg)
63     dargs = []
64     for arg in args:
65         darg = base64.b64decode(arg)
66         dargs.append(darg.rstrip())
67
68     return (dmsg.rstrip(), dargs)
69
70 def send_reply(conn, reply):
71     encoded = base64.b64encode(reply)
72     conn.send("%s\n" % encoded)
73
74 def stop_action():
75     return "STOP-ACK"
76
77 def passfd_action(fd, args):
78     """ Sends the file descriptor associated to the TAP device 
79     to another process through a unix socket.
80     """
81     address = args.pop(0)
82     print address
83     sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
84     sock.connect(address)
85     passfd.sendfd(sock, fd, '0')
86     return "PASSFD-ACK"
87
88 def get_options():
89     usage = ("usage: %prog -t <vif-type> -a <ip4-address> -n <net-prefix> "
90         "-s <snat> -p <pointopoint> -f <if-name-file> -S <socket-name>")
91     
92     parser = OptionParser(usage = usage)
93
94     parser.add_option("-t", "--vif-type", dest="vif_type",
95         help = "Virtual interface type. Either IFF_TAP or IFF_TUN. "
96             "Defaults to IFF_TAP. ", type="str")
97
98     parser.add_option("-a", "--ip4-address", dest="ip4_address",
99         help = "IPv4 address to assign to interface. It must belong to the "
100             "network segment owned by the slice, given by the vsys_vnet tag. ",
101         type="str")
102
103     parser.add_option("-n", "--net-prefix", dest="net_prefix",
104         help = "IPv4 network prefix for the interface. It must be the one "
105             "given by the slice's vsys_vnet tag. ",
106         type="int")
107
108     parser.add_option("-s", "--snat", dest="snat", default = False,
109         action="store_true", help="Enable SNAT for the interface")
110
111     parser.add_option("-p", "--pointopoint", dest="pointopoint",
112         help = "Peer end point for the interface  ", default = None,
113         type="str")
114
115     parser.add_option("-f", "--if-name-file", dest="if_name_file",
116         help = "File to store the interface name assigned by the OS", 
117         default = "if_name", type="str")
118
119     parser.add_option("-S", "--socket-name", dest="socket_name",
120         help = "Name for the unix socket used to interact with this process", 
121         default = "tap.sock", type="str")
122
123     (options, args) = parser.parse_args()
124     
125     vif_type = vsys.IFF_TAP
126     if options.vif_type and options.vif_type == "IFF_TUN":
127         vif_type = vsys.IFF_TUN
128
129     return (vif_type, options.ip4_address, options.net_prefix, options.snat,
130             options.pointopoint, options.if_name_file, options.socket_name)
131
132 if __name__ == '__main__':
133
134     (vif_type, ip4_address, net_prefix, snat, pointopoint,
135             if_name_file, socket_name) = get_options()
136
137     (fd, if_name) = vsys.fd_tuntap(vif_type)
138     vsys.vif_up(if_name, ip4_address, net_prefix, snat, pointopoint)
139     
140     # Saving interface name to 'if_name_file
141     f = open(if_name_file, 'w')
142     f.write(if_name)
143     f.close()
144
145     # create unix socket to receive instructions
146     sock = create_socket(socket_name)
147     sock.listen(0)
148
149     # wait for messages to arrive and process them
150     stop = False
151
152     while not stop:
153         conn, addr = sock.accept()
154         conn.settimeout(5)
155
156         while not stop:
157             try:
158                 (msg, args) = recv_msg(conn)
159             except socket.timeout, e:
160                 # Ingore time-out
161                 continue
162
163             if not msg:
164                 # Ignore - connection lost
165                 break
166
167             if msg == STOP_MSG:
168                 stop = True
169                 reply = stop_action()
170             elif msg == PASSFD_MSG:
171                 reply = passfd_action(fd, args)
172
173             try:
174                 send_reply(conn, reply)
175             except socket.error:
176                 break
177