Linux/Ns-3/Dce cross experiments
[nepi.git] / src / nepi / resources / linux / scripts / linux-passfd.py
1 import base64
2 import errno
3 import fcntl
4 import os
5 import passfd
6 import socket
7 import struct
8
9 from optparse import OptionParser
10
11 IFF_TUN     = 0x0001
12 IFF_TAP     = 0x0002
13 IFF_NO_PI   = 0x1000
14 TUNSETIFF   = 0x400454ca
15
16 def get_options():
17     usage = ("usage: %prog -a <address> -N <vif_name> -t <vif-type> -p <pi> ")
18     
19     parser = OptionParser(usage = usage)
20
21     parser.add_option("-a", "--address", dest="address",
22         help="Socket address to send file descriptor to", type="str")
23     parser.add_option("-N", "--vif-name", dest="vif_name",
24         help="The name of the virtual interface", type="str")
25     parser.add_option("-t", "--vif-type", dest="vif_type",
26         help="Virtual interface type. Either IFF_TAP or IFF_TUN. "
27             "Defaults to IFF_TAP. ", default=IFF_TAP, type="str")
28     parser.add_option("-p", "--pi", dest="pi", action="store_true", 
29             default=False, help="Enable PI header")
30
31     (options, args) = parser.parse_args()
32        
33     vif_type = IFF_TAP
34     if options.vif_type and options.vif_type == "IFF_TUN":
35         vif_type = IFF_TUN
36
37     return (options.address, options.vif_name, vif_type, options.pi)
38
39 if __name__ == '__main__':
40
41     (address, vif_name, vif_type, pi) = get_options()
42
43     flags = 0
44     flags |= vif_type
45
46     if not pi:
47         flags |= IFF_NO_PI
48
49     fd = os.open("/dev/net/tun", os.O_RDWR)
50
51     err = fcntl.ioctl(fd, TUNSETIFF, struct.pack("16sH", vif_name, flags))
52     if err < 0:
53         os.close(fd)
54         raise RuntimeError("Could not retrive file descriptor from %s" % vif_name)
55
56     address = base64.b64decode(address)
57
58     sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
59     sock.connect(address)
60     passfd.sendfd(sock, fd, '0')
61