Split the authority-cert and signature/hash code from routerparse
[tor.git] / src / test / test_rebind.py
blob7ba3a5796d34cc53370150ec4c6062dea8ce98c0
1 from __future__ import print_function
3 import sys
4 import subprocess
5 import socket
6 import os
7 import time
8 import random
10 def try_connecting_to_socksport():
11 socks_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
12 if socks_socket.connect_ex(('127.0.0.1', socks_port)):
13 tor_process.terminate()
14 print('FAIL')
15 sys.exit('Cannot connect to SOCKSPort')
16 socks_socket.close()
18 def wait_for_log(s):
19 while True:
20 l = tor_process.stdout.readline()
21 if s in l.decode('utf8'):
22 return
24 def pick_random_port():
25 port = 0
26 random.seed()
28 for i in range(8):
29 port = random.randint(10000, 60000)
30 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
31 if s.connect_ex(('127.0.0.1', port)) == 0:
32 s.close()
33 else:
34 break
36 return port
38 if sys.hexversion < 0x02070000:
39 sys.exit("ERROR: unsupported Python version (should be >= 2.7)")
41 if sys.hexversion > 0x03000000 and sys.hexversion < 0x03010000:
42 sys.exit("ERROR: unsupported Python3 version (should be >= 3.1)")
44 control_port = pick_random_port()
45 socks_port = pick_random_port()
47 assert control_port != 0
48 assert socks_port != 0
50 if not os.path.exists(sys.argv[1]):
51 sys.exit('ERROR: cannot find tor at %s' % sys.argv[1])
53 tor_path = sys.argv[1]
55 tor_process = subprocess.Popen([tor_path,
56 '-ControlPort', '127.0.0.1:{}'.format(control_port),
57 '-SOCKSPort', '127.0.0.1:{}'.format(socks_port),
58 '-FetchServerDescriptors', '0'],
59 stdout=subprocess.PIPE,
60 stderr=subprocess.PIPE)
62 if tor_process == None:
63 sys.exit('ERROR: running tor failed')
65 if len(sys.argv) < 2:
66 sys.exit('Usage: %s <path-to-tor>' % sys.argv[0])
68 wait_for_log('Opened Control listener on')
70 try_connecting_to_socksport()
72 control_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
73 if control_socket.connect_ex(('127.0.0.1', control_port)):
74 tor_process.terminate()
75 print('FAIL')
76 sys.exit('Cannot connect to ControlPort')
78 control_socket.sendall('AUTHENTICATE \r\n'.encode('utf8'))
79 control_socket.sendall('SETCONF SOCKSPort=0.0.0.0:{}\r\n'.format(socks_port).encode('utf8'))
80 wait_for_log('Opened Socks listener')
82 try_connecting_to_socksport()
84 control_socket.sendall('SETCONF SOCKSPort=127.0.0.1:{}\r\n'.format(socks_port).encode('utf8'))
85 wait_for_log('Opened Socks listener')
87 try_connecting_to_socksport()
89 control_socket.sendall('SIGNAL HALT\r\n'.encode('utf8'))
91 time.sleep(0.1)
92 print('OK')
93 tor_process.terminate()