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