3 import nepi.util.environ
8 # Unittest from Python 2.6 doesn't have these decorators
9 def _bannerwrap(f, text):
11 def banner(*args, **kwargs):
12 sys.stderr.write("*** WARNING: Skipping test %s: `%s'\n" %
17 return lambda f: _bannerwrap(f, text)
18 def skipUnless(cond, text):
19 return (lambda f: _bannerwrap(f, text)) if not cond else lambda f: f
20 def skipIf(cond, text):
21 return (lambda f: _bannerwrap(f, text)) if cond else lambda f: f
23 def ns3_bindings_path():
24 if "NEPI_NS3BINDINGS" in os.environ:
25 return os.environ["NEPI_NS3BINDINGS"]
28 def ns3_library_path():
29 if "NEPI_NS3LIBRARY" in os.environ:
30 return os.environ["NEPI_NS3LIBRARY"]
34 if ns3_library_path():
36 ctypes.CDLL(ns3_library_path(), ctypes.RTLD_GLOBAL)
40 if ns3_bindings_path():
41 sys.path.insert(0, ns3_bindings_path())
44 found = imp.find_module('ns3')
45 module = imp.load_module('ns3', *found)
49 if ns3_bindings_path():
55 def find_bin(name, extra_path = None):
57 if "PATH" in os.environ:
58 search += os.environ["PATH"].split(":")
59 for pref in ("/", "/usr/", "/usr/local/"):
60 for d in ("bin", "sbin"):
61 search.append(pref + d)
67 os.stat(d + "/" + name)
70 if e.errno != os.errno.ENOENT:
74 def find_bin_or_die(name, extra_path = None):
77 raise RuntimeError(("Cannot find `%s' command, impossible to " +
83 import os, os.path, re, signal, shutil, socket, subprocess, tempfile
84 def gen_ssh_keypair(filename):
85 ssh_keygen = nepi.util.environ.find_bin_or_die("ssh-keygen")
86 args = [ssh_keygen, '-q', '-N', '', '-f', filename]
87 assert subprocess.Popen(args).wait() == 0
88 return filename, "%s.pub" % filename
90 def add_key_to_agent(filename):
91 ssh_add = nepi.util.environ.find_bin_or_die("ssh-add")
92 args = [ssh_add, filename]
93 null = file("/dev/null", "w")
94 assert subprocess.Popen(args, stderr = null).wait() == 0
99 s.bind(("127.0.0.1", 0))
100 port = s.getsockname()[1]
103 _SSH_CONF = """ListenAddress 127.0.0.1:%d
106 UsePrivilegeSeparation no
107 PubkeyAuthentication yes
108 PasswordAuthentication no
109 AuthorizedKeysFile %s
111 AllowAgentForwarding yes
114 PermitUserEnvironment yes
117 def gen_sshd_config(filename, port, server_key, auth_keys):
118 conf = open(filename, "w")
119 text = _SSH_CONF % (port, server_key, auth_keys)
124 def gen_auth_keys(pubkey, output, environ):
125 #opts = ['from="127.0.0.1/32"'] # fails in stupid yans setup
127 for k, v in environ.items():
128 opts.append('environment="%s=%s"' % (k, v))
130 lines = file(pubkey).readlines()
131 pubkey = lines[0].split()[0:2]
132 out = file(output, "w")
133 out.write("%s %s %s\n" % (",".join(opts), pubkey[0], pubkey[1]))
137 def start_ssh_agent():
138 ssh_agent = nepi.util.environ.find_bin_or_die("ssh-agent")
139 proc = subprocess.Popen([ssh_agent], stdout = subprocess.PIPE)
140 (out, foo) = proc.communicate()
141 assert proc.returncode == 0
143 for l in out.split("\n"):
144 match = re.search("^(\w+)=([^ ;]+);.*", l)
147 k, v = match.groups()
152 def stop_ssh_agent(data):
153 # No need to gather the pid, ssh-agent knows how to kill itself; after we
154 # had set up the environment
155 ssh_agent = nepi.util.environ.find_bin_or_die("ssh-agent")
156 null = file("/dev/null", "w")
157 proc = subprocess.Popen([ssh_agent, "-k"], stdout = null)
159 assert proc.wait() == 0
163 class test_environment(object):
165 sshd = find_bin_or_die("sshd")
167 if 'PYTHONPATH' in os.environ:
168 environ['PYTHONPATH'] = ":".join(map(os.path.realpath,
169 os.environ['PYTHONPATH'].split(":")))
170 if 'NEPI_NS3BINDINGS' in os.environ:
171 environ['NEPI_NS3BINDINGS'] = \
172 os.path.realpath(os.environ['NEPI_NS3BINDINGS'])
173 if 'NEPI_NS3LIBRARY' in os.environ:
174 environ['NEPI_NS3LIBRARY'] = \
175 os.path.realpath(os.environ['NEPI_NS3LIBRARY'])
177 self.dir = tempfile.mkdtemp()
178 self.server_keypair = gen_ssh_keypair(
179 os.path.join(self.dir, "server_key"))
180 self.client_keypair = gen_ssh_keypair(
181 os.path.join(self.dir, "client_key"))
182 self.authorized_keys = gen_auth_keys(self.client_keypair[1],
183 os.path.join(self.dir, "authorized_keys"), environ)
184 self.port = get_free_port()
185 self.sshd_conf = gen_sshd_config(
186 os.path.join(self.dir, "sshd_config"),
187 self.port, self.server_keypair[0], self.authorized_keys)
189 self.sshd = subprocess.Popen([sshd, '-q', '-D', '-f', self.sshd_conf])
190 self.ssh_agent_vars = start_ssh_agent()
191 add_key_to_agent(self.client_keypair[0])
195 os.kill(self.sshd.pid, signal.SIGTERM)
197 if self.ssh_agent_vars:
198 stop_ssh_agent(self.ssh_agent_vars)
199 shutil.rmtree(self.dir)