Tunnel between 2 ns-3s in remote PL hosts:q
[nepi.git] / src / nepi / resources / planetlab / scripts / pl-fd-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
10 from optparse import OptionParser
11
12 IFF_TUN     = 0x0001
13 IFF_TAP     = 0x0002
14
15 # Trak SIGTERM, and set global termination flag instead of dying
16 TERMINATE = []
17 STARTED = False
18
19 def _finalize(sig,frame):
20     global TERMINATE
21     global STARTED
22     
23     if STARTED:
24         TERMINATE.append(None)
25     else:
26         signal.signal(signal.SIGTERM, signal.SIG_DFL)
27         os.kill(os.getpid(), signal.SIGTERM)
28
29 signal.signal(signal.SIGTERM, _finalize)
30
31 # SIGUSR1 suspends forwading, SIGUSR2 resumes forwarding
32 SUSPEND = []
33 def _suspend(sig,frame):
34     global SUSPEND
35     if not SUSPEND:
36         SUSPEND.append(None)
37 signal.signal(signal.SIGUSR1, _suspend)
38
39 def _resume(sig,frame):
40     global SUSPEND
41     if SUSPEND:
42         SUSPEND.remove(None)
43 signal.signal(signal.SIGUSR2, _resume)
44
45 def get_options():
46     usage = ("usage: %prog -a <address> -b <bwlimit> -c <cipher> "
47             "- k <cipher-key> -q <txqueuelen> -p <local-port-file> "
48             "-P <remote-port-file> -o <local-ip> -O <remote-ip> "
49             "-r <ret-file> ")
50     
51     parser = OptionParser(usage = usage)
52
53     parser.add_option("-a", "--address", dest="address",
54         help="Socket address to send file descriptor to", type="str")
55
56     parser.add_option("-b", "--bwlimit", dest="bwlimit",
57         help="Specifies the interface's emulated bandwidth in bytes ",
58         default=None, type="int")
59     parser.add_option("-q", "--txqueuelen", dest="txqueuelen",
60         help="Specifies the interface's transmission queue length. ",
61         default=1000, type="int")
62     parser.add_option("-c", "--cipher", dest="cipher",
63         help="Cipher to encript communication. "
64             "One of PLAIN, AES, Blowfish, DES, DES3. ",
65         default=None, type="str")
66     parser.add_option("-k", "--cipher-key", dest="cipher_key",
67         help="Specify a symmetric encryption key with which to protect "
68             "packets across the tunnel. python-crypto must be installed "
69             "on the system." ,
70         default=None, type="str")
71
72     parser.add_option("-p", "--local-port-file", dest="local_port_file",
73         help = "File where to store the local binded UDP port number ", 
74         default = "local_port_file", type="str")
75     parser.add_option("-P", "--remote-port-file", dest="remote_port_file",
76         help = "File where to read the remote UDP port number to connect to", 
77         default = "remote_port_file", type="str")
78     parser.add_option("-o", "--local-ip", dest="local_ip",
79         help = "Local host IP", type="str")
80     parser.add_option("-O", "--remote-ip", dest="remote_ip",
81         help = "Remote host IP", type="str")
82     parser.add_option("-R", "--ret-file", dest="ret_file",
83         help = "File where to store return code (success of connection) ", 
84         default = "ret_file", type="str")
85
86     (options, args) = parser.parse_args()
87        
88     address = base64.b64decode(options.address)
89
90     return (address, options.local_port_file, options.remote_port_file, 
91             options.local_ip, options.remote_ip, options.ret_file, 
92             options.bwlimit, options.cipher, options.cipher_key, 
93             options.txqueuelen)
94
95 if __name__ == '__main__':
96
97     (address, local_port_file, remote_port_file, local_ip, remote_ip, 
98             ret_file, bwlimit, cipher, cipher_key, txqueuelen) = get_options()
99
100     # Create a local socket to stablish the tunnel connection
101     rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
102     rsock.bind((local_ip, 0))
103     (local_host, local_port) = rsock.getsockname()
104
105     # Save local port information to file
106     f = open(local_port_file, 'w')
107     f.write("%d\n" % local_port)
108     f.close()
109
110     # Wait until remote port information is available
111     while not os.path.exists(remote_port_file):
112         time.sleep(2)
113
114     remote_port = ''
115     # Read remote port from file
116     # Try until something is read...
117     # xxx: There seems to be a weird behavior where
118     #       even if the file exists and had the port number,
119     #       the read operation returns empty string!
120     #       Maybe a race condition?
121     for i in xrange(10):
122         f = open(remote_port_file, 'r')
123         remote_port = f.read()
124         f.close()
125
126         if remote_port:
127             break
128         
129         time.sleep(2)
130     
131     remote_port = remote_port.strip()
132     remote_port = int(remote_port)
133
134     # Connect local socket to remote port
135     rsock.connect((remote_ip, remote_port))
136     remote = os.fdopen(rsock.fileno(), 'r+b', 0)
137
138     # create local socket to pass to fd-net-device, the other is for the tunnel
139     fd, tun = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM, 0)
140
141     # pass one end of the socket pair to the fd-net-device
142     sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
143     sock.connect(address)
144     passfd.sendfd(sock, fd, '0')
145
146     # TODO: Test connectivity!    
147
148     # Create a ret_file to indicate success
149     f = open(ret_file, 'w')
150     f.write("0")
151     f.close()
152
153     STARTED = True
154
155     # Establish tunnel
156     tunchannel.tun_fwd(tun, remote,
157         with_pi = True, # No PI headers 
158         ether_mode = IFF_TAP, # Ns-3 generates ethernet pkts
159         udp = True,
160         cipher_key = cipher_key,
161         cipher = cipher,
162         TERMINATE = TERMINATE,
163         SUSPEND = SUSPEND,
164         tunqueue = txqueuelen,
165         tunkqueue = 500,
166         bwlimit = bwlimit
167     ) 
168