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