test_rebind.py 4.4 KB

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