fa16879bc7b1cbd0f86b72e3b2d327a79b4bfc93
[nepi.git] / src / nepi / resources / planetlab / scripts / pl-vif-udp-connect.py
1 import base64
2 import errno
3 import os
4 import passfd
5 import signal
6 import socket
7 import time
8 import tunchannel
9 import vsys
10
11 from optparse import OptionParser
12
13 PASSFD_MSG = "PASSFD"
14
15 # Trak SIGTERM, and set global termination flag instead of dying
16 TERMINATE = []
17 def _finalize(sig,frame):
18     global TERMINATE
19     TERMINATE.append(None)
20 signal.signal(signal.SIGTERM, _finalize)
21
22 # SIGUSR1 suspends forwading, SIGUSR2 resumes forwarding
23 SUSPEND = []
24 def _suspend(sig,frame):
25     global SUSPEND
26     if not SUSPEND:
27         SUSPEND.append(None)
28 signal.signal(signal.SIGUSR1, _suspend)
29
30 def _resume(sig,frame):
31     global SUSPEND
32     if SUSPEND:
33         SUSPEND.remove(None)
34 signal.signal(signal.SIGUSR2, _resume)
35
36 def get_fd(socket_name):
37     # Socket to recive the file descriptor
38     fdsock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
39     fdsock.bind("")
40     address = fdsock.getsockname()
41
42     # Socket to connect to the pl-vif-create process 
43     # and send the PASSFD message
44     sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
45     sock.connect(socket_name)
46     emsg = base64.b64encode(PASSFD_MSG)
47     eargs = base64.b64encode(address)
48     encoded = "%s|%s\n" % (emsg, eargs)
49     sock.send(encoded)
50
51     # Receive fd
52     (fd, msg) = passfd.recvfd(fdsock)
53     
54     # Receive reply
55     reply = sock.recv(1024)
56     reply = base64.b64decode(reply)
57
58     sock.close()
59     fdsock.close()
60     return fd
61
62 def get_options():
63     usage = ("usage: %prog -t <vif-type> -S <fd-socket-name> "
64             "-b <bwlimit> -c <cipher> -k <cipher-key> -q <txqueuelen> " 
65             "-l <local-port-file> -r <remote-port-file> -H <remote-host> "
66             "-R <ret-file> ")
67     
68     parser = OptionParser(usage = usage)
69
70     parser.add_option("-t", "--vif-type", dest="vif_type",
71         help = "Virtual interface type. Either IFF_TAP or IFF_TUN. "
72             "Defaults to IFF_TAP. ", type="str")
73     parser.add_option("-S", "--fd-socket-name", dest="fd_socket_name",
74         help = "Name for the unix socket to request the TAP file descriptor", 
75         default = "tap.sock", type="str")
76
77     parser.add_option("-b", "--bwlimit", dest="bwlimit",
78         help = "Specifies the interface's emulated bandwidth in bytes ",
79         default = None, type="int")
80     parser.add_option("-q", "--txqueuelen", dest="txqueuelen",
81         help = "Specifies the interface's transmission queue length. ",
82         default = 1000, type="int")
83     parser.add_option("-c", "--cipher", dest="cipher",
84         help = "Cipher to encript communication. "
85             "One of PLAIN, AES, Blowfish, DES, DES3. ",
86         default = None, type="str")
87     parser.add_option("-k", "--cipher-key", dest="cipher_key",
88         help = "Specify a symmetric encryption key with which to protect "
89             "packets across the tunnel. python-crypto must be installed "
90             "on the system." ,
91         default = None, type="str")
92
93     parser.add_option("-l", "--local-port-file", dest="local_port_file",
94         help = "File where to store the local binded UDP port number ", 
95         default = "local_port_file", type="str")
96     parser.add_option("-r", "--remote-port-file", dest="remote_port_file",
97         help = "File where to read the remote UDP port number to connect to", 
98         default = "remote_port_file", type="str")
99     parser.add_option("-H", "--remote-host", dest="remote_host",
100         help = "Remote host IP", 
101         default = "remote_host", type="str")
102     parser.add_option("-R", "--ret-file", dest="ret_file",
103         help = "File where to store return code (success of connection) ", 
104         default = "ret_file", type="str")
105
106     (options, args) = parser.parse_args()
107        
108     vif_type = vsys.IFF_TAP
109     if options.vif_type and options.vif_type == "IFF_TUN":
110         vif_type = vsys.IFF_TUN
111
112     return ( vif_type, options.fd_socket_name, options.local_port_file,
113             options.remote_port_file, options.remote_host, options.ret_file, 
114             options.bwlimit, options.cipher, options.cipher_key,
115             options.txqueuelen )
116
117 if __name__ == '__main__':
118
119     ( vif_type, socket_name, local_port_file, remote_port_file,
120       remote_host, ret_file, bwlimit, cipher, cipher_key, txqueuelen 
121          ) = get_options()
122    
123     # Get the file descriptor of the TAP device from the process
124     # that created it
125     fd = get_fd(socket_name)
126     tun = os.fdopen(int(fd), 'r+b', 0)
127
128     # Create a local socket to stablish the tunnel connection
129     hostaddr = socket.gethostbyname(socket.gethostname())
130     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
131     sock.bind((hostaddr, 0))
132     (local_host, local_port) = sock.getsockname()
133
134     # Save local port information to file
135     f = open(local_port_file, 'w')
136     f.write("%d\n" % local_port)
137     f.close()
138
139     # Wait until remote port information is available
140     while not os.path.exists(remote_port_file):
141         time.sleep(2)
142
143     remote_port = ''
144     # Read remote port from file
145     # Try until something is read...
146     # xxx: There seems to be a weird behavior where
147     #       even if the file exists and had the port number,
148     #       the read operation returns empty string!
149     #       Maybe a race condition?
150     for i in xrange(10):
151         f = open(remote_port_file, 'r')
152         remote_port = f.read()
153         f.close()
154
155         if remote_port:
156             break
157         
158         time.sleep(2)
159     
160     remote_port = remote_port.strip()
161     remote_port = int(remote_port)
162
163     # Connect local socket to remote port
164     sock.connect((remote_host, remote_port))
165     remote = os.fdopen(sock.fileno(), 'r+b', 0)
166
167     # TODO: Test connectivity!    
168
169     # Create a ret_file to indicate success
170     f = open(ret_file, 'w')
171     f.write("0")
172     f.close()
173
174     # Establish tunnel
175     tunchannel.tun_fwd(tun, remote,
176         with_pi = True, # Planetlab TAP devices add PI headers 
177         ether_mode = (vif_type == vsys.IFF_TAP),
178         udp = True,
179         cipher_key = cipher_key,
180         cipher = cipher,
181         TERMINATE = TERMINATE,
182         SUSPEND = SUSPEND,
183         tunqueue = txqueuelen,
184         tunkqueue = 500,
185         bwlimit = bwlimit
186     ) 
187  
188