Remove unused function: dns_randfn_() in dns.c.
[tor.git] / src / test / test_rebind.py
blob30a587858f08be92ab11a64b1fa18220a11456b5
1 from __future__ import print_function
3 import errno
4 import logging
5 import os
6 import random
7 import socket
8 import subprocess
9 import sys
10 import time
12 LOG_TIMEOUT = 60.0
13 LOG_WAIT = 0.1
15 def fail(msg):
16 logging.error('FAIL')
17 sys.exit(msg)
19 def skip(msg):
20 logging.warning('SKIP: {}'.format(msg))
21 sys.exit(77)
23 def try_connecting_to_socksport():
24 socks_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
25 if socks_socket.connect_ex(('127.0.0.1', socks_port)):
26 tor_process.terminate()
27 fail('Cannot connect to SOCKSPort')
28 socks_socket.close()
30 def wait_for_log(s):
31 cutoff = time.time() + LOG_TIMEOUT
32 while time.time() < cutoff:
33 l = tor_process.stdout.readline()
34 l = l.decode('utf8', 'backslashreplace')
35 if s in l:
36 logging.info('Tor logged: "{}"'.format(l.strip()))
37 return
38 # readline() returns a blank string when there is no output
39 # avoid busy-waiting
40 if len(l) == 0:
41 logging.debug('Tor has not logged anything, waiting for "{}"'.format(s))
42 time.sleep(LOG_WAIT)
43 else:
44 logging.info('Tor logged: "{}", waiting for "{}"'.format(l.strip(), s))
45 fail('Could not find "{}" in logs after {} seconds'.format(s, LOG_TIMEOUT))
47 def pick_random_port():
48 port = 0
49 random.seed()
51 for i in range(8):
52 port = random.randint(10000, 60000)
53 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
54 if s.connect_ex(('127.0.0.1', port)) == 0:
55 s.close()
56 else:
57 break
59 if port == 0:
60 fail('Could not find a random free port between 10000 and 60000')
62 return port
64 logging.basicConfig(level=logging.DEBUG,
65 format='%(asctime)s.%(msecs)03d %(message)s',
66 datefmt='%Y-%m-%d %H:%M:%S')
68 if sys.hexversion < 0x02070000:
69 fail("ERROR: unsupported Python version (should be >= 2.7)")
71 if sys.hexversion > 0x03000000 and sys.hexversion < 0x03010000:
72 fail("ERROR: unsupported Python3 version (should be >= 3.1)")
74 if 'TOR_SKIP_TEST_REBIND' in os.environ:
75 skip('$TOR_SKIP_TEST_REBIND is set')
77 control_port = pick_random_port()
78 socks_port = pick_random_port()
80 assert control_port != 0
81 assert socks_port != 0
83 if len(sys.argv) < 3:
84 fail('Usage: %s <path-to-tor> <data-dir>' % sys.argv[0])
86 if not os.path.exists(sys.argv[1]):
87 fail('ERROR: cannot find tor at %s' % sys.argv[1])
88 if not os.path.exists(sys.argv[2]):
89 fail('ERROR: cannot find datadir at %s' % sys.argv[2])
91 tor_path = sys.argv[1]
92 data_dir = sys.argv[2]
94 empty_torrc_path = os.path.join(data_dir, 'empty_torrc')
95 open(empty_torrc_path, 'w').close()
96 empty_defaults_torrc_path = os.path.join(data_dir, 'empty_defaults_torrc')
97 open(empty_defaults_torrc_path, 'w').close()
99 tor_process = subprocess.Popen([tor_path,
100 '-DataDirectory', data_dir,
101 '-ControlPort', '127.0.0.1:{}'.format(control_port),
102 '-SOCKSPort', '127.0.0.1:{}'.format(socks_port),
103 '-Log', 'debug stdout',
104 '-LogTimeGranularity', '1',
105 '-FetchServerDescriptors', '0',
106 '-f', empty_torrc_path,
107 '--defaults-torrc', empty_defaults_torrc_path,
109 stdout=subprocess.PIPE,
110 stderr=subprocess.PIPE)
112 if tor_process == None:
113 fail('ERROR: running tor failed')
115 wait_for_log('Opened Control listener on')
117 try_connecting_to_socksport()
119 control_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
120 if control_socket.connect_ex(('127.0.0.1', control_port)):
121 tor_process.terminate()
122 fail('Cannot connect to ControlPort')
124 control_socket.sendall('AUTHENTICATE \r\n'.encode('ascii'))
125 control_socket.sendall('SETCONF SOCKSPort=0.0.0.0:{}\r\n'.format(socks_port).encode('ascii'))
126 wait_for_log('Opened Socks listener')
128 try_connecting_to_socksport()
130 control_socket.sendall('SETCONF SOCKSPort=127.0.0.1:{}\r\n'.format(socks_port).encode('ascii'))
131 wait_for_log('Opened Socks listener')
133 try_connecting_to_socksport()
135 control_socket.sendall('SIGNAL HALT\r\n'.encode('ascii'))
137 wait_for_log('exiting cleanly')
138 logging.info('OK')
140 try:
141 tor_process.terminate()
142 except OSError as e:
143 if e.errno == errno.ESRCH: # errno 3: No such process
144 # assume tor has already exited due to SIGNAL HALT
145 logging.warn("Tor has already exited")
146 else:
147 raise