2 # vim:ts=4:sw=4:et:ai:sts=4
5 import nepi.util.environ
7 # Unittest from Python 2.6 doesn't have these decorators
8 def _bannerwrap(f, text):
10 def banner(*args, **kwargs):
11 sys.stderr.write("*** WARNING: Skipping test %s: `%s'\n" %
16 return lambda f: _bannerwrap(f, text)
17 def skipUnless(cond, text):
18 return (lambda f: _bannerwrap(f, text)) if not cond else lambda f: f
19 def skipIf(cond, text):
20 return (lambda f: _bannerwrap(f, text)) if cond else lambda f: f
22 def find_bin(name, extra_path = None):
24 if "PATH" in os.environ:
25 search += os.environ["PATH"].split(":")
26 for pref in ("/", "/usr/", "/usr/local/"):
27 for d in ("bin", "sbin"):
28 search.append(pref + d)
34 os.stat(d + "/" + name)
37 if e.errno != os.errno.ENOENT:
41 def find_bin_or_die(name, extra_path = None):
44 raise RuntimeError(("Cannot find `%s' command, impossible to " +
50 import os, os.path, re, signal, shutil, socket, subprocess, tempfile
51 def gen_ssh_keypair(filename):
52 ssh_keygen = nepi.util.environ.find_bin_or_die("ssh-keygen")
53 args = [ssh_keygen, '-q', '-N', '', '-f', filename]
54 assert subprocess.Popen(args).wait() == 0
55 return filename, "%s.pub" % filename
57 def add_key_to_agent(filename):
58 ssh_add = nepi.util.environ.find_bin_or_die("ssh-add")
59 args = [ssh_add, filename]
60 null = file("/dev/null", "w")
61 assert subprocess.Popen(args, stderr = null).wait() == 0
66 s.bind(("127.0.0.1", 0))
67 port = s.getsockname()[1]
70 _SSH_CONF = """ListenAddress 127.0.0.1:%d
73 UsePrivilegeSeparation no
74 PubkeyAuthentication yes
75 PasswordAuthentication no
78 AllowAgentForwarding yes
81 PermitUserEnvironment yes
84 def gen_sshd_config(filename, port, server_key, auth_keys):
85 conf = open(filename, "w")
86 text = _SSH_CONF % (port, server_key, auth_keys)
91 def gen_auth_keys(pubkey, output, environ):
92 #opts = ['from="127.0.0.1/32"'] # fails in stupid yans setup
94 for k, v in environ.items():
95 opts.append('environment="%s=%s"' % (k, v))
97 lines = file(pubkey).readlines()
98 pubkey = lines[0].split()[0:2]
99 out = file(output, "w")
100 out.write("%s %s %s\n" % (",".join(opts), pubkey[0], pubkey[1]))
104 def start_ssh_agent():
105 ssh_agent = nepi.util.environ.find_bin_or_die("ssh-agent")
106 proc = subprocess.Popen([ssh_agent], stdout = subprocess.PIPE)
107 (out, foo) = proc.communicate()
108 assert proc.returncode == 0
110 for l in out.split("\n"):
111 match = re.search("^(\w+)=([^ ;]+);.*", l)
114 k, v = match.groups()
119 def stop_ssh_agent(data):
120 # No need to gather the pid, ssh-agent knows how to kill itself; after we
121 # had set up the environment
122 ssh_agent = nepi.util.environ.find_bin_or_die("ssh-agent")
123 null = file("/dev/null", "w")
124 proc = subprocess.Popen([ssh_agent, "-k"], stdout = null)
126 assert proc.wait() == 0
130 class test_environment(object):
132 sshd = find_bin_or_die("sshd")
134 if 'PYTHONPATH' in os.environ:
135 environ['PYTHONPATH'] = ":".join(map(os.path.realpath,
136 os.environ['PYTHONPATH'].split(":")))
137 if 'NEPI_NS3BINDINGS' in os.environ:
138 environ['NEPI_NS3BINDINGS'] = \
139 os.path.realpath(os.environ['NEPI_NS3BINDINGS'])
140 if 'NEPI_NS3LIBRARY' in os.environ:
141 environ['NEPI_NS3LIBRARY'] = \
142 os.path.realpath(os.environ['NEPI_NS3LIBRARY'])
144 self.dir = tempfile.mkdtemp()
145 self.server_keypair = gen_ssh_keypair(
146 os.path.join(self.dir, "server_key"))
147 self.client_keypair = gen_ssh_keypair(
148 os.path.join(self.dir, "client_key"))
149 self.authorized_keys = gen_auth_keys(self.client_keypair[1],
150 os.path.join(self.dir, "authorized_keys"), environ)
151 self.port = get_free_port()
152 self.sshd_conf = gen_sshd_config(
153 os.path.join(self.dir, "sshd_config"),
154 self.port, self.server_keypair[0], self.authorized_keys)
156 self.sshd = subprocess.Popen([sshd, '-q', '-D', '-f', self.sshd_conf])
157 self.ssh_agent_vars = start_ssh_agent()
158 add_key_to_agent(self.client_keypair[0])
162 os.kill(self.sshd.pid, signal.SIGTERM)
164 if self.ssh_agent_vars:
165 stop_ssh_agent(self.ssh_agent_vars)
166 shutil.rmtree(self.dir)