test_rebind.py 3.8 KB

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