ce869f7ca9f208668ecabd47b049b41ba2166733
[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",
64         type="str")
65
66     parser.add_option("-t", "--vif-type", dest="vif_type",
67         help = "Virtual interface type. Either IFF_TAP or IFF_TUN. "
68             "Defaults to IFF_TAP. ", 
69         default = IFF_TAP,
70         type="str")
71
72     parser.add_option("-n", "--pi", dest="pi", 
73             action="store_true", 
74             default = False,
75             help="Enable PI header")
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
81     parser.add_option("-q", "--txqueuelen", dest="txqueuelen",
82         help = "Specifies the interface's transmission queue length. ",
83         default = 1000, type="int")
84
85     parser.add_option("-c", "--cipher", dest="cipher",
86         help = "Cipher to encript communication. "
87             "One of PLAIN, AES, Blowfish, DES, DES3. ",
88         default = None, type="str")
89
90     parser.add_option("-k", "--cipher-key", dest="cipher_key",
91         help = "Specify a symmetric encryption key with which to protect "
92             "packets across the tunnel. python-crypto must be installed "
93             "on the system." ,
94         default = None, type="str")
95
96     parser.add_option("-l", "--local-port-file", dest="local_port_file",
97         help = "File where to store the local binded UDP port number ", 
98         default = "local_port_file", type="str")
99
100     parser.add_option("-r", "--remote-port-file", dest="remote_port_file",
101         help = "File where to read the remote UDP port number to connect to", 
102         default = "remote_port_file", type="str")
103
104     parser.add_option("-H", "--remote-host", dest="remote_host",
105         help = "Remote host IP", 
106         default = "remote_host", type="str")
107
108     parser.add_option("-R", "--ret-file", dest="ret_file",
109         help = "File where to store return code (success of connection) ", 
110         default = "ret_file", type="str")
111
112     (options, args) = parser.parse_args()
113        
114     if options.vif_type == "IFF_TUN":
115         vif_type = IFF_TUN
116
117     return ( options.vif_name, vif_type, options.pi, 
118             options.local_port_file, options.remote_port_file, 
119             options.remote_host, options.ret_file, options.bwlimit, 
120             options.cipher, options.cipher_key, options.txqueuelen )
121
122 if __name__ == '__main__':
123
124     ( vif_name, vif_type, pi, local_port_file, remote_port_file,
125       remote_host, ret_file, bwlimit, cipher, cipher_key, txqueuelen 
126          ) = get_options()
127    
128     # Get the file descriptor of the TAP device from the process
129     # that created it
130     fd = open_tap(vif_name, vif_type, pi)
131
132     # Create a local socket to stablish the tunnel connection
133     hostaddr = socket.gethostbyname(socket.gethostname())
134     sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
135     sock.bind((hostaddr, 0))
136     (local_host, local_port) = sock.getsockname()
137
138     # Save local port information to file
139     f = open(local_port_file, 'w')
140     f.write("%d\n" % local_port)
141     f.close()
142
143     # Wait until remote port information is available
144     while not os.path.exists(remote_port_file):
145         time.sleep(2)
146
147     remote_port = ''
148     # Read remote port from file
149     # Try until something is read...
150     # xxx: There seems to be a weird behavior where
151     #       even if the file exists and had the port number,
152     #       the read operation returns empty string!
153     #       Maybe a race condition?
154     for i in xrange(10):
155         f = open(remote_port_file, 'r')
156         remote_port = f.read()
157         f.close()
158
159         if remote_port:
160             break
161         
162         time.sleep(2)
163     
164     remote_port = remote_port.strip()
165     remote_port = int(remote_port)
166
167     # Connect local socket to remote port
168     sock.connect((remote_host, remote_port))
169     remote = os.fdopen(sock.fileno(), 'r+b', 0)
170
171     # TODO: Test connectivity!    
172
173     # Create a ret_file to indicate success
174     f = open(ret_file, 'w')
175     f.write("0")
176     f.close()
177
178     # Establish tunnel
179     tunchannel.tun_fwd(tun, remote,
180         with_pi = True, # Planetlab TAP devices add PI headers 
181         ether_mode = (vif_type == IFF_TAP),
182         udp = True,
183         cipher_key = cipher_key,
184         cipher = cipher,
185         TERMINATE = TERMINATE,
186         SUSPEND = SUSPEND,
187         tunqueue = txqueuelen,
188         tunkqueue = 500,
189         bwlimit = bwlimit
190     ) 
191