rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
self.network = ipaddr.IPAddress(addr)
self.network = None self.address = ipaddr.IPAddress(addr)
def __init__(self, line): self.port_low, self.port_high = -1, -1 self.ip = None
if ipaddr.IPAddress(ip) in self.network:
if self.network and ipaddr.IPAddress(ip) in self.network: return True elif self.address and ipaddr.IPAddress(ip) == self.address:
def match(self, ip, port): if port >= self.port_low and port <= self.port_high: if ipaddr.IPAddress(ip) in self.network: return True
if os.getuid() == 0: if config.log_file: os.chown(config.log_file, config.uid, config.gid) log.debug("Changed owner of log file %s to uid=%d, gid=%d", config.log_file, config.uid, config.gid) os.setgid(config.gid) os.setuid(config.uid) log.info("Dropped root privileges to uid=%d, gid=%d", config.uid, config.gid)
def init_tests(self): """ Initialize testing infrastructure - sockets, resource limits, etc. """ # Init Twisted factory. self.server_factory = network.TestServerFactory(controller = self) #self.client_factory = TestClientFactory(controller = self)
try: torbel_start(host, port) sys.exit(0) except Exception, e: print "Unhandled error condition (%s): %s" % (type(e), e) sys.exit(2)
torbel_start(host, port) sys.exit(0)
def usage(): print "Usage: %s torhost ctlport" % sys.argv[0] sys.exit(1)
log.debug("%s: no testable ports.")
log.debug("%s: no testable ports.", exit.nickname)
def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = [] recv_sockets = [] self.test_exit = router exit = router.rout...
def export_json(self, fn): if config.export_gzip: fd = gzip.open(config.export_file_prefix + ".json.gz", "w") else: fd = open(config.export_file_prefix + ".json", "w")
def export_json(self): fn = config.export_file_prefix + (".json.gz" if config.export_gzip else ".json") try: if config.export_gzip: fd = gzip.open(config.export_file_prefix + ".json.gz", "w") else: fd = open(config.export_file_prefix + ".json", "w")
def export_json(self, fn): if config.export_gzip: fd = gzip.open(config.export_file_prefix + ".json.gz", "w") else: fd = open(config.export_file_prefix + ".json", "w") with self.consensus_cache_lock: records = [router.dump(fd) for router in self.router_cache.values()]
with self.consensus_cache_lock: records = [router.dump(fd) for router in self.router_cache.values()] json.dump(records, fd) fd.close()
with self.consensus_cache_lock: records = [router.dump(fd) for router in self.router_cache.values()] json.dump(records, fd) fd.close() except IOError, e: (errno, strerror) = e log.error("I/O error writing to file %s: %s", fn, strerror)
def export_json(self, fn): if config.export_gzip: fd = gzip.open(config.export_file_prefix + ".json.gz", "w") else: fd = open(config.export_file_prefix + ".json", "w") with self.consensus_cache_lock: records = [router.dump(fd) for router in self.router_cache.values()]
csv_file = gzip.open(config.export_file_prefix + ".csv.gz", "w")
csv_file = gzip.open(fn, "w")
def export_csv(self): """ Export current router cache in CSV format. See data-spec for more information on export formats. """ try: if config.export_gzip: csv_file = gzip.open(config.export_file_prefix + ".csv.gz", "w") else: csv_file = open(config.export_file_prefix + ".csv", "w") out = csv.writer(csv_file, dialect ...
csv_file = open(config.export_file_prefix + ".csv", "w")
csv_file = open(fn, "w")
def export_csv(self): """ Export current router cache in CSV format. See data-spec for more information on export formats. """ try: if config.export_gzip: csv_file = gzip.open(config.export_file_prefix + ".csv.gz", "w") else: csv_file = open(config.export_file_prefix + ".csv", "w") out = csv.writer(csv_file, dialect ...
log.error("I/O error writing to file %s: %s", csv_file.name, strerror)
log.error("I/O error writing to file %s: %s", fn, strerror)
def export_csv(self): """ Export current router cache in CSV format. See data-spec for more information on export formats. """ try: if config.export_gzip: csv_file = gzip.open(config.export_file_prefix + ".csv.gz", "w") else: csv_file = open(config.export_file_prefix + ".csv", "w") out = csv.writer(csv_file, dialect ...
if not "notests" in sys.argv:
if do_tests:
def torbel_start(): log.info("TorBEL v%s starting.", __version__) # Configuration check. try: config_check() except ConfigurationError, e: log.error("Configuration error: %s", e.message) return 1 except AttributeError, e: log.error("Configuration error: missing value: %s", e.args[0]) try: control = Controller() if no...
if not control.tests_running():
if do_tests and not control.tests_running():
def torbel_start(): log.info("TorBEL v%s starting.", __version__) # Configuration check. try: config_check() except ConfigurationError, e: log.error("Configuration error: %s", e.message) return 1 except AttributeError, e: log.error("Configuration error: missing value: %s", e.args[0]) try: control = Controller() if no...
test.circ_failed = circ_failed
if test: test.circ_failed = circ_failed
def test_cleanup(self, router, circ_failed = False): """ Clean up router after test - close circuit (if built), return circuit entry guard to cache, and return router to guard_cache if it is also a guard. """ # Finish the current test and unset the router guard. test = router.end_current_test() test.circ_failed = circ_...
event.strm_id, event.target_port
event.strm_id, event.target_port) return
def getSourcePort(): portsep = event.source_addr.rfind(':') return int(event.source_addr[portsep+1:])
self.export_task = task.LoopingCall(self.export)
def __init__(self, controller, max_pending_factor = 0.5, export_interval = 5): self.controller = controller self.terminated = False ## Circuit dictionaries. # Established circuits under test. self.circuits = {} # Circuits in the process of being built. self.pending_circuits = {} self.pending_circuit_lock = threading.Lo...
self.export_task.start(self.export_interval * 60, now = False)
reactor.callLater(self.export_interval * 60, self.export)
def start(self): """ Start the scheduler. """ # Start the export looping task, but don't run it immediately - # wait until the first export_interval (converted to seconds) to pass. self.export_task.start(self.export_interval * 60, now = False)
if self.export_task.running: self.export_task.stop()
def stop(self): """ Stop the scheduler. """ # Stop our export task. if self.export_task.running: self.export_task.stop() with self.pending_circuit_cond: self.pending_circuit_cond.notify() self.terminated = True
log.debug("StreamManager: SOCKS4 connect successful!")
def stream_management_thread(self): log.debug("StreamManager: Starting stream management thread.")
log.debug("TestThread: (%s, %d): sending test data.", router.nickname, port)
def testing_thread(self): log.debug("TestThread: Starting test thread.") data_recv = {} while True: with self.send_recv_cond: # Wait on send_recv_cond to stall while we're not waiting on # test sockets. while len(self.recv_sockets) + len(self.send_sockets) == 0: log.debug("TestThread: waiting for new test sockets.") s...
log.debug("Event (%s, %d): Initiated SOCKS4 handshake (src %d).", router.nickname, port, source_port)
def circ_status_event(self, event): id = event.circ_id if event.status == "BUILT": with self.pending_circuit_cond: if self.pending_circuits.has_key(id): router = self.pending_circuits[id] del self.pending_circuits[id] # Notify CircuitBuilder thread that we have # completed building a circuit and we could # need to pre-...
log.debug("Closed circuit %d (%s).", id, self.circuits[id].idhex)
log.debug("Closed circuit %d (%s).", id, self.circuits[id].nickname)
def circ_status_event(self, event): id = event.circ_id if event.status == "BUILT": with self.pending_circuit_cond: if self.pending_circuits.has_key(id): router = self.pending_circuits[id] del self.pending_circuits[id] # Notify CircuitBuilder thread that we have # completed building a circuit and we could # need to pre-...
def __init__(self):
def __init__(self, csv_file = None):
def __init__(self): self.cache_ip = {} self.cache_id = {}
if csv_file: self.import_csv(csv_file)
def __init__(self): self.cache_ip = {} self.cache_id = {}
self.cache_id[router.router_id] = router
self.cache_id[router.idhex] = router
def import_csv(self, filename): """ Import a TorBEL export file in CSV format, as specified in the TorBEL data-spec document. """ if filename.endswith(".gz"): infile = gzip.open(filename, "rb") else: infile = open(filename, "rb")
log.debug("csv: Imported %d records from '%s'.", records, filename)
def import_csv(self, filename): """ Import a TorBEL export file in CSV format, as specified in the TorBEL data-spec document. """ if filename.endswith(".gz"): infile = gzip.open(filename, "rb") else: infile = open(filename, "rb")
if not config.test_host: config.test_host = conn.get_info("address")["address"]
def start(self, passphrase = config.control_password): """ Attempt to connect to the Tor control port with the given passphrase. """ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host, self.port)) conn = TorCtl.Connection(self.sock) conn.set_event_handler(self) conn.authenticate...
def stream_management_thread(self): log.debug("StreamManager: Starting stream management thread.") while True: with self.send_pending_cond: while len(self.send_sockets_pending) == 0: self.send_pending_cond.wait() pending_sockets = copy(self.send_sockets_pending) try: ready, ignore, me = select.select(pending_socket...
def completed_test(self, router): """ Close test circuit associated with router. Restore associated guard to guard_cache. """ self.close_test_circuit(router) self.tests_completed += 1 if self.tests_completed % 10 == 0: self.export_csv() router.last_test_length = (time.time() - router.last_tested) log.debug("Complet...
def stream_management_thread(self): log.debug("StreamManager: Starting stream management thread.")
listen_set = set() for sock in self.test_bind_sockets: ip, port = sock.getsockname() sock.listen(20) listen_set.add(sock) while True: try: ready, ignore, error = select.select(listen_set, [], listen_set) except select.error, e: if e[0] != errno.EINTR: log.error("Listen: select() error: %s", e[1]) continue els...
def listen_thread(self): """ Thread that waits for new connections from the Tor network. """ log.debug("Listen: Starting listen thread.") listen_set = set() for sock in self.test_bind_sockets: ip, port = sock.getsockname() # LISTEN OK. Is 20 too large of a backlog? Testing will tell. sock.listen(20) listen_set.add(s...
log.debug("BUILT")
def circ_status_event(self, event): id = event.circ_id if event.status == "BUILT": with self.pending_circuit_cond: if self.pending_circuits.has_key(id): router = self.pending_circuits[id] del self.pending_circuits[id] # Notify CircuitBuilder thread that we have # completed building a circuit and we could # need to pre-...
log.debug("%d routers are now stale.", len(dropped_routers))
if dropped_routers: log.debug("%d routers are now stale (of %d, %.1f%%).", len(dropped_routers), len(old_ids), 10.0 * len(dropped_routers) / float(len(old_ids)))
def __update_consensus(self, nslist): # hbock: borrowed from TorCtl.py:ConsensusTracker # Routers can fall out of our consensus five different ways: # 1. Their descriptors disappear # 2. Their NS documents disappear # 3. They lose the Running flag # 4. They list a bandwidth of 0 # 5. They have 'opt hibernating' set wit...
log.debug("%s is now stale.", router.nickname)
def __update_consensus(self, nslist): # hbock: borrowed from TorCtl.py:ConsensusTracker # Routers can fall out of our consensus five different ways: # 1. Their descriptors disappear # 2. Their NS documents disappear # 3. They lose the Running flag # 4. They list a bandwidth of 0 # 5. They have 'opt hibernating' set wit...
router.current_test.passed(port) if router.current_test.is_complete(): self.end_test(router)
if router.current_test: router.current_test.passed(port) if router.current_test.is_complete(): self.end_test(router)
def passed(self, router, port): """ Mark port as working for router's current test, and end the test if it is complete. """ router.current_test.passed(port) if router.current_test.is_complete(): self.end_test(router)
TorCtl.loglevel = "INFO"
TorUtil.loglevel = "INFO"
# Set TorCtl log level (see TorCtl/TorUtil.py:def plog)
reactor.callLater(5 * 60, lambda: retry_soon(router))
reactor.callLater(5 * 60, lambda: self.retry_soon(router))
def retry_later(self, router): """ Retry router in five minutes. """ reactor.callLater(5 * 60, lambda: retry_soon(router))
control = sighup_handler.controller
control = sigusr1_handler.controller
def sigusr1_handler(signum, frame): control = sighup_handler.controller log.info("SIGUSR1 received: Updating consensus.") control._update_consensus(control.conn.get_network_status())
sighup_handler.controller = control
sigusr1_handler.controller = control
def torbel_start(): log.info("TorBEL v%s starting.", __version__) # Configuration check. try: config_check() except ConfigurationError, e: log.error("Configuration error: %s", e.message) return 1 except AttributeError, e: log.error("Configuration error: missing value: %s", e.args[0]) try: control = Controller() contr...
log.log(VERBOSE1, "Connection from %s:%d", self.peer.host, self.host.port)
log.log(VERBOSE2, "Connection from %s:%d", self.peer.host, self.host.port)
def connectionMade(self): self.host = self.transport.getHost() self.peer = self.transport.getPeer() self.data = ""
log.debug("%s: down/stale, circuit failed.")
log.debug("%s: down/stale, circuit failed.", router.nickname)
def closeCallback(sport): self.stream_remove(source_port = sport)
log.debug("%s: BadExit! circuit failed.")
log.debug("%s: BadExit! circuit failed.", router.nickname)
def closeCallback(sport): self.stream_remove(source_port = sport)
log.log(VERBOSE2, "Event (%s, %d): New target stream (sport %d).",
log.log(VERBOSE2, "(%s, %d): New target stream (sport %d).",
def getSourcePort(): portsep = event.source_addr.rfind(':') return int(event.source_addr[portsep+1:])
log.log(VERBOSE1, "Event (%s, %d): Attaching stream %d to circuit %d.",
log.log(VERBOSE2, "(%s, %d): Attaching stream %d to circuit %d.",
def getSourcePort(): portsep = event.source_addr.rfind(':') return int(event.source_addr[portsep+1:])
for id in old_ids:
log.debug("%d routers are now stale.", len(dropped_routers)) for id in dropped_routers:
def __update_consensus(self, nslist): # hbock: borrowed from TorCtl.py:ConsensusTracker # Routers can fall out of our consensus five different ways: # 1. Their descriptors disappear # 2. Their NS documents disappear # 3. They lose the Running flag # 4. They list a bandwidth of 0 # 5. They have 'opt hibernating' set wit...
log.debug("%s (%s) is now stale.", router.idhex, router.nickname)
log.debug("%s is now stale.", router.nickname)
def __update_consensus(self, nslist): # hbock: borrowed from TorCtl.py:ConsensusTracker # Routers can fall out of our consensus five different ways: # 1. Their descriptors disappear # 2. Their NS documents disappear # 3. They lose the Running flag # 4. They list a bandwidth of 0 # 5. They have 'opt hibernating' set wit...
def __init__(self, host, port = 9051):
def __init__(self, host = "localhost", port = 9051, orport = 9050):
def __init__(self, host, port = 9051): TorCtl.EventHandler.__init__(self) self.host = host self.port = port self.router_cache = {}
log.info("Our IP address should be %s.", conn.get_info("address")["address"])
log.info("Our IP address should be %s.", self.test_ip)
def start(self, passphrase): """ Attempt to connect to the Tor control port with the given passphrase. """ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host, self.port)) conn = TorCtl.Connection(self.sock) conn.set_event_handler(self) conn.authenticate(passphrase) conn.set_even...
def build_test_circuit(self, guard, exit): hops = map(lambda r: "$" + r.idhex, [guard, exit]) return self.conn.extend_circuit(0, hops) def test(self, router): guard = self.guard_list[0] self.test_circuit = self.build_test_circuit(guard, router) log.debug("Created test circuit %d", self.test_circuit) return self.test_s...
def start(self, passphrase): """ Attempt to connect to the Tor control port with the given passphrase. """ self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((self.host, self.port)) conn = TorCtl.Connection(self.sock) conn.set_event_handler(self) conn.authenticate(passphrase) conn.set_even...
def clear_exit_cache(self): """ Clear the current router cache. """ self.router_cache.clear()
def record_exists(self, rid): """ Check if a router with a particular identity key hash is being tracked. """ return self.router_cache.has_key(rid)
def or_conn_status_event(self, event): print event
def or_conn_status_event(self, event): print event
pass
log.debug("Stream %d status %s circuit %s target %s", event.strm_id, event.status, event.circ_id, event.target_host) if event.status == "NEW" and self.test_circuit: log.debug("Attaching new stream to target host %s on circuit %d", event.target_host, self.test_circuit) self.test_stream = event.strm_id
def stream_status_event(self, event): #print "Stream event ", event.purpose pass
reactor.callLater(nextUpdate, self.update) log.debug("Scheduling first update in %.1f seconds.", nextUpdate)
if nextUpdate > 0: log.debug("Scheduling first update in %.1f seconds.", nextUpdate) reactor.callLater(nextUpdate, self.update) else: log.notice("Export file is not up-to-date. Trying again in 10 minutes.") reactor.callLater(10 * 60, self.update)
def __init__(self, zone, filename, status, *args, **kwargs): server.DNSServerFactory.__init__(self, *args, **kwargs) self.el = ExitList(filename, status)
log.info("ExitList updated. Next update in %.1f seconds.", nextUpdate) reactor.callLater(nextUpdate, self.update)
if nextUpdate > 0: log.info("ExitList updated. Next update in %.1f seconds.", nextUpdate) reactor.callLater(nextUpdate, self.update) else: log.notice("Export file is not up-to-date. Trying again in 10 minutes.") reactor.callLater(10 * 60, self.update)
def update(self): next = self.el.update() nextUpdate = time.mktime(next.timetuple()) - time.time() log.info("ExitList updated. Next update in %.1f seconds.", nextUpdate)
circuit_limit = max_files / len(controller.test_ports) - max_pending_circuits
circuit_limit = max_files / len(controller.test_ports)
def __init__(self, controller, max_pending_factor = 0.5): self.controller = controller self.terminated = False ## Circuit dictionaries. # Established circuits under test. self.circuits = {} # Circuits in the process of being built. self.pending_circuits = {} self.pending_circuit_lock = threading.RLock() self.pending_ci...
self.pending_streams = {}
def __init__(self): TorCtl.EventHandler.__init__(self) self.host = config.tor_host self.port = config.control_port # Router cache contains all routers we know about, and is a # superset of the latest consensus (we continue to track # routers that have fallen out of the consensus for a short # time). # Guard cache co...
self.pending_streams = {} self.test_queue = Queue.Queue(maxsize = 5)
self.pending_circuit_lock = threading.RLock() self.pending_circuit_cond = threading.Condition(self.pending_circuit_lock)
def __init__(self): TorCtl.EventHandler.__init__(self) self.host = config.tor_host self.port = config.control_port # Router cache contains all routers we know about, and is a # superset of the latest consensus (we continue to track # routers that have fallen out of the consensus for a short # time). # Guard cache co...
self.test_exit = None
def __init__(self): TorCtl.EventHandler.__init__(self) self.host = config.tor_host self.port = config.control_port # Router cache contains all routers we know about, and is a # superset of the latest consensus (we continue to track # routers that have fallen out of the consensus for a short # time). # Guard cache co...
self.test_mgmt_thread = T(target = Controller.test_management_thread, args = (self,))
def init_tests(self): """ Initialize testing infrastructure - sockets, etc. """ # Bind to test ports. log.debug("Binding to test ports.") for port in self.test_ports: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) sock.bind((config.test_bind_ip, port)) self.test_bind_sockets.add(sock)...
self.test_mgmt_thread.start()
def run_tests(self): """ Start the test thread. """ if self.test_thread: if self.test_thread.is_alive(): log.error("BUG: Test thread already running!") return self.circuit_thread.start() self.listen_thread.start() self.stream_thread.start() self.test_thread.start() self.test_mgmt_thread.start()
def circuit_build_thread(self): log.debug("CircuitBuilder: Starting circuit builder thread.") time.sleep(10000)
def circuit_build_thread(self): log.debug("CircuitBuilder: Starting circuit builder thread.") time.sleep(10000)
router = self.pending_streams[source_port]
with self.send_pending_lock: router = self.pending_streams[source_port]
def testing_thread(self): log.debug("TestThread: Starting test thread.") data_recv = {} while True: with self.send_recv_cond: # Wait on send_recv_cond to stall while we're not waiting on # test sockets. while len(self.recv_sockets) + len(self.send_sockets) == 0: log.debug("TestThread: waiting for new test sockets.") s...
def test_management_thread(self): test_average_len = None tests = 0 log.debug("TestManagement: Started.") time.sleep(6000)
def circuit_build_thread(self): log.debug("CircuitBuilder: Starting circuit builder thread.")
def test_management_thread(self): test_average_len = None tests = 0
router.guard = self.guard_cache.popitem()[1] for router in routers: cid = self.build_test_circuit(router)
router.guard = self.guard_cache.popitem()[1] for router in routers: cid = self.build_test_circuit(router) router.last_tested = time.time() with self.pending_circuit_lock:
def test_management_thread(self): test_average_len = None tests = 0
try: while(len(self.pending_circuits) > 0): exit = self.test_queue.get(True, 5) log.debug("Pulled off %s for test.", exit.idhex) self.exit_test(exit) if test_average_len is None: test_average_len = exit.last_test_length else: test_average_len = (test_average_len + exit.last_test_length) / 2.0 log.debug("%s: test compl...
def test_management_thread(self): test_average_len = None tests = 0
self.test_exit = None def prepare_circuits(self): with self.consensus_cache_lock: routers = filter(lambda r: r.testable_ports(config.test_host, config.test_port_list), self.router_cache.values()) routers = sorted(routers, key = attrgetter("last_tested"))[0:4] with self.consensus_cache_lock: for router in routers: ...
def close_test_circuit(self, router): """ Clean up router router after test. """ if not router.circuit: return # Return guard to the guard pool. with self.consensus_cache_lock: self.guard_cache[router.guard.idhex] = router.guard # Return router to guard_cache if it was originally a guard. if "Guard" in router.flags: se...
for sock in self.test_sockets.itervalues():
for sock in self.test_bind_sockets:
def close(self): """ Close the connection to the Tor control port. """ self.conn.close() # Close all currently bound test sockets. log.debug("Closing test sockets.") for sock in self.test_sockets.itervalues(): sock.close() self.test_sockets.clear()
self.test_sockets.clear()
def close(self): """ Close the connection to the Tor control port. """ self.conn.close() # Close all currently bound test sockets. log.debug("Closing test sockets.") for sock in self.test_sockets.itervalues(): sock.close() self.test_sockets.clear()
if self.pending_circuits.has_key(id): router = self.pending_circuits[id] del self.pending_circuits[id]
with self.pending_circuit_cond: if self.pending_circuits.has_key(id): router = self.pending_circuits[id] del self.pending_circuits[id] self.pending_circuit_cond.notify() log.debug("BUILT") else: return
def circ_status_event(self, event): id = event.circ_id if event.status == "BUILT": if self.pending_circuits.has_key(id): router = self.pending_circuits[id] del self.pending_circuits[id] log.debug("Successfully built circuit %d for %s.", id, router.idhex) # Prepare circuit for testing. self.circuits[id] = router # Put r...
self.test_queue.put(router)
def circ_status_event(self, event): id = event.circ_id if event.status == "BUILT": if self.pending_circuits.has_key(id): router = self.pending_circuits[id] del self.pending_circuits[id] log.debug("Successfully built circuit %d for %s.", id, router.idhex) # Prepare circuit for testing. self.circuits[id] = router # Put r...
if self.circuits.has_key(id): log.error("Established test circuit %d failed: %s", id, event.reason) self.circuits[id].circuit = None del self.circuits[id] elif self.pending_circuits.has_key(id): log.error("Pending test circuit %d failed: %s", id, event.reason) self.pending_circuits[id].circuit = None del self.pending_...
with self.pending_circuit_cond: if self.circuits.has_key(id): log.error("Established test circuit %d failed: %s", id, event.reason) self.circuits[id].circuit = None del self.circuits[id] elif self.pending_circuits.has_key(id): log.error("Pending test circuit %d failed: %s", id, event.reason) self.pending_circuits[i...
def circ_status_event(self, event): id = event.circ_id if event.status == "BUILT": if self.pending_circuits.has_key(id): router = self.pending_circuits[id] del self.pending_circuits[id] log.debug("Successfully built circuit %d for %s.", id, router.idhex) # Prepare circuit for testing. self.circuits[id] = router # Put r...
if self.circuits.has_key(id): log.debug("Closed circuit %d (%s).", id, self.circuits[id].idhex) del self.circuits[id] elif self.pending_circuits.has_key(id): del self.pending_circuits[id]
with self.pending_circuit_cond: if self.circuits.has_key(id): log.debug("Closed circuit %d (%s).", id, self.circuits[id].idhex) del self.circuits[id] elif self.pending_circuits.has_key(id): log.debug("Pending circuit closed (%d)?", id) del self.pending_circuits[id] self.pending_circuit_cond.notify()
def circ_status_event(self, event): id = event.circ_id if event.status == "BUILT": if self.pending_circuits.has_key(id): router = self.pending_circuits[id] del self.pending_circuits[id] log.debug("Successfully built circuit %d for %s.", id, router.idhex) # Prepare circuit for testing. self.circuits[id] = router # Put r...
if source_port in self.pending_streams: router = self.pending_streams[source_port]
with self.send_pending_lock: if source_port in self.pending_streams: router = self.pending_streams[source_port]
def stream_status_event(self, event): if event.status == "NEW": if event.target_host == config.test_host: portsep = event.source_addr.rfind(':') source_port = int(event.source_addr[portsep+1:]) # Check if this stream is one of ours (TODO: there's no # reason AFAIK that it shouldn't be one we initiated # if event.target...
try: log.debug("Event (%s, %d): Attaching stream %d to circuit %d.", router.nickname, event.target_port, event.strm_id, router.circuit) self.conn.attach_stream(event.strm_id, router.circuit) except TorCtl.ErrorReply, e: log.error("Event (%s, %d): Error attaching stream!", router.nickname, event.target_port)
else: return try: log.debug("Event (%s, %d): Attaching stream %d to circuit %d.", router.nickname, event.target_port, event.strm_id, router.circuit) self.conn.attach_stream(event.strm_id, router.circuit) except TorCtl.ErrorReply, e: log.error("Event (%s, %d): Error attaching stream!", router.nickname, event.target...
def stream_status_event(self, event): if event.status == "NEW": if event.target_host == config.test_host: portsep = event.source_addr.rfind(':') source_port = int(event.source_addr[portsep+1:]) # Check if this stream is one of ours (TODO: there's no # reason AFAIK that it shouldn't be one we initiated # if event.target...
self.test_sockets = {}
self.test_bind_sockets = set() self.recv_sockets = set() self.send_sockets = set() self.send_recv_lock = threading.RLock() self.send_recv_cond = threading.Condition(self.send_recv_lock) self.send_sockets_pending = set() self.send_pending_lock = threading.RLock() self.send_pending_cond = threading.Condition(self.send...
def __init__(self): TorCtl.EventHandler.__init__(self) self.host = config.tor_host self.port = config.control_port # Router cache contains all routers we know about, and is a # superset of the latest consensus (we continue to track # routers that have fallen out of the consensus for a short # time). # Guard cache co...
self.streams = {}
self.pending_streams = {}
def __init__(self): TorCtl.EventHandler.__init__(self) self.host = config.tor_host self.port = config.control_port # Router cache contains all routers we know about, and is a # superset of the latest consensus (we continue to track # routers that have fallen out of the consensus for a short # time). # Guard cache co...
log.debug("Initializing test sockets.")
log.debug("Binding to test ports.")
def init_tests(self): """ Initialize testing infrastructure - sockets, etc. """ log.debug("Initializing test sockets.") for port in self.test_ports: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) sock.bind((config.test_bind_ip, port)) self.test_sockets[port] = sock except socket.error...
self.test_sockets[port] = sock
self.test_bind_sockets.add(sock)
def init_tests(self): """ Initialize testing infrastructure - sockets, etc. """ log.debug("Initializing test sockets.") for port in self.test_ports: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) sock.bind((config.test_bind_ip, port)) self.test_sockets[port] = sock except socket.error...
log.error("Run TorBEL as root or a user able to bind to privileged ports.")
log.error("Run TorBEL as a user able to bind to privileged ports.")
def init_tests(self): """ Initialize testing infrastructure - sockets, etc. """ log.debug("Initializing test sockets.") for port in self.test_ports: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) sock.bind((config.test_bind_ip, port)) self.test_sockets[port] = sock except socket.error...
log.error("test_bind_ip in torbel_config.py must be assigned to a working network interface.")
log.error("test_bind_ip in torbel_config.py must be assigned to an active network interface.")
def init_tests(self): """ Initialize testing infrastructure - sockets, etc. """ log.debug("Initializing test sockets.") for port in self.test_ports: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) sock.bind((config.test_bind_ip, port)) self.test_sockets[port] = sock except socket.error...
self.test_thread = threading.Thread(target = Controller.test_thread_func, args = (self,))
log.debug("Initializing test threads.") T = threading.Thread self.test_thread = T(target = Controller.testing_thread, args = (self,)) self.circuit_thread = T(target = Controller.circuit_build_thread, args = (self,)) self.listen_thread = T(target = Controller.listen_thread, args = (self,)) self.stream_thread ...
def init_tests(self): """ Initialize testing infrastructure - sockets, etc. """ log.debug("Initializing test sockets.") for port in self.test_ports: try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) sock.bind((config.test_bind_ip, port)) self.test_sockets[port] = sock except socket.error...
self.test_thread.run()
self.circuit_thread.start() self.listen_thread.start() self.stream_thread.start() self.test_thread.start() self.test_mgmt_thread.start() log.debug("All threads started.")
def run_tests(self): """ Start the test thread. """ if self.test_thread: if self.test_thread.is_alive(): log.error("BUG: Test thread already running!") return self.test_thread.run()
def test_thread_func(self): log.debug("Starting test thread...")
def stream_management_thread(self): log.debug("StreamManager: Starting stream management thread.") while True: with self.send_pending_cond: while len(self.send_sockets_pending) == 0: self.send_pending_cond.wait() pending_sockets = copy(self.send_sockets_pending) try: ready, ignore, me = select.select(pending_socket...
def test_thread_func(self): log.debug("Starting test thread...") test_average_len = None tests = 0
test_started = time.time() bind_list = filter(lambda x: x is not None, self.test_sockets.values()) for s in bind_list: ip, port = s.getsockname() if router.will_exit_to(config.test_host, port): log.debug("(%s, %d): Listening.", router.nickname, port) s.listen(1) listen_sockets.append(s) test_ports.add(port) test_...
def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = set() recv_sockets = [] listen_sockets = [] self.test_exit = ro...
for port in test_ports: s = socks4socket(config.tor_host, config.tor_port) s.connect((config.test_host, port)) send_sockets_pending.append(s) pending_sockets = listen_sockets + send_sockets_pending while len(pending_sockets) > 0: try: ready, ignore, me = select.select(pending_sockets, [], [], 20) except select...
def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = set() recv_sockets = [] listen_sockets = [] self.test_exit = ro...
while(len(recv_sockets + send_sockets) > 0): try: read_list, write_list, error = \ select.select(recv_sockets, send_sockets, [], 20) except select.error, e: if e[0] != errno.EINTR: log.error("%s: select() error (testing stage): %s", router.nickname, e[0]) continue else: raise if len(read_list + write_list) == 0: l...
def exit_test(self, router): """ Perform port and IP tests on router. Will block until all port tests are finished. Can raise the following errors: socket.error - errno == errno.ECONNREFUSED: Tor refused our SOCKS connected. """ test_data = {} test_ports = set() recv_sockets = [] listen_sockets = [] self.test_exit = ro...
routers = filter(lambda r: r.testable_ports(config.test_ip, config.test_ports), routers) routers = sorted(self.router_cache.values(), key = attrgetter("last_tested"))[0:4]
routers = filter(lambda r: r.testable_ports(config.test_host, config.test_port_list), self.router_cache.values()) routers = sorted(routers, key = attrgetter("last_tested"))[0:4]
def prepare_circuits(self): with self.consensus_cache_lock: routers = filter(lambda r: r.testable_ports(config.test_ip, config.test_ports), routers) routers = sorted(self.router_cache.values(), key = attrgetter("last_tested"))[0:4] # Build test circuits. with self.consensus_cache_lock: for router in routers: # If we a...
if event.target_host == config.test_host and self.test_exit: try: circuit = self.test_exit.circuit log.debug("(%s, %d): Attaching new stream %d to circuit %d.", self.circuits[circuit].nickname, event.target_port, event.strm_id, circuit) self.conn.attach_stream(event.strm_id, circuit) except TorCtl.ErrorReply, e: log.er...
if event.target_host == config.test_host: portsep = event.source_addr.rfind(':') source_port = int(event.source_addr[portsep+1:]) if source_port in self.pending_streams: router = self.pending_streams[source_port] try: log.debug("Event (%s, %d): Attaching stream %d to circuit %d.", router.nickname, event.target_po...
def stream_status_event(self, event): ## TODO: ## We must keep track of streams we have created via ## SOCKS. After creating a stream, we will receive ## a stream status event. We must check the target ## addresses against our bookkeeping on outgoing SOCKS ## sockets. ## If we are able to find a match, we should atta...
return c
def unit_test(tests = True): import atexit config_check() c = Controller() c.start() if tests: c.init_tests() c.run_tests() atexit.register(lambda: c.close()) if tests: return c exits = c.prepare_circuits() return c, exits else: return c
log.notice("%d match, %d mismatch (%.2%% agreement).",
log.notice("%d match, %d mismatch (%.2f%% agreement).",
def query(router, dest, dest_port): s = map(lambda o: str(ord(o)), struct.pack(">I", router.ip)) d = map(lambda o: str(ord(o)), struct.pack(">I", dest)) s.reverse() d.reverse()
self.n = 0
def init(self): self.router_count = 0 self.router_list = deque() self.n = 0 self.new_router_lock = threading.Lock() self.new_router_cond = threading.Condition(self.new_router_lock)
if self.n % 30 == 0: log.debug("Going to test %d routers. %.1f%% started (%d circs)!", len(test_set), 100 * (self.router_count - len(self.router_list)) \ / float(self.router_count), len(self.circuits)) self.n += 1
def fetch_next_tests(self): testable = 0
self.guard_cache = set()
self.guard_cache = []
def __init__(self): TorCtl.EventHandler.__init__(self) self.host = config.tor_host self.port = config.control_port # Router cache contains all routers we know about, and is a # superset of the latest consensus (we continue to track # routers that have fallen out of the consensus for a short # time). # Guard cache co...
self.guard_cache.add(router.idhex)
self.guard_cache.append(router.idhex)
def add_to_cache(self, router): """ Add a router to our cache, given its NetworkStatus instance. """ with self.consensus_cache_lock: # Update router record in-place to preserve references. # TODO: The way TorCtl does this is not thread-safe :/ if router.idhex in self.router_cache: # Router was stale. Since it is again...
log.debug("%d routers are testable", len(routers))
log.debug("%d:%d streams open", len(self.streams_by_id), len(self.streams_by_source))
def cleanup_circuits(): ctime = time.time() with self.pending_circuit_lock: for idhex, router in self.circuits.iteritems(): if not router.current_test: continue if (ctime - router.current_test.start_time) > 3 * 60: test = router.current_test ndone = len(test.working_ports) + len(test.failed_ports) log.debug("Closing ol...
return
try: stream = self.stream_remove(id = event.strm_id) self.stream_remove(source_port = stream.source_port) except KeyError: pass
def getSourcePort(): portsep = event.source_addr.rfind(':') return int(event.source_addr[portsep+1:])
s = self.streams_by_source[port]
s = self.streams_by_source[sport]
def connectCallback(sport): stream = Stream() stream.router = router stream.source_port = sport stream.circ_id = router.current_test.circ_id with self.streams_lock: if sport in self.streams_by_source: s = self.streams_by_source[port] log.error("Badness: new stream with sport %d already here. old state = %s", sport, s.s...
self.pending_circuit_lock = threading.RLock()
self.pending_circuit_lock = threading.Lock()
def __init__(self, controller, max_pending_factor = 0.5, export_interval = 5): self.controller = controller self.terminated = False ## Circuit dictionaries. # Established circuits under test. self.circuits = {} # Circuits in the process of being built. self.pending_circuits = {} self.pending_circuit_lock = threading.RL...
self.circ_failed(event) return log.verbose2("Closed circuit %d (%s).", circ_id, self.circuits[circ_id].nickname) del self.circuits[circ_id]
handle_as_failed = True else: log.verbose2("Closed circuit %d (%s).", circ_id, self.circuits[circ_id].nickname) del self.circuits[circ_id]
def circ_closed(self, event): circ_id = event.circ_id with self.pending_circuit_cond: if circ_id in self.circuits: router = self.circuits[circ_id] # FINISHED = "The circuit has expired for being dirty or old." # (tor-spec.txt 5.4, "Tearing down circuits"). Treat this as # an error condition if we have not yet completed...
if handle_as_failed: self.circ_failed(event)
def circ_closed(self, event): circ_id = event.circ_id with self.pending_circuit_cond: if circ_id in self.circuits: router = self.circuits[circ_id] # FINISHED = "The circuit has expired for being dirty or old." # (tor-spec.txt 5.4, "Tearing down circuits"). Treat this as # an error condition if we have not yet completed...
return None
raise ValueError("Guard not set for exit %s (%s).", exit.nickname, exit.idhex)
def build_test_circuit(self, exit): """ Build a test circuit using exit and its associated guard node. Fail if exit.guard is not set. """ if not exit.guard: return None
self.guard_cache.pop(router.idhex)
if router.idhex in self.guard_cache: self.guard_cache.pop(router.idhex)
def prepare_circuits(self): with self.consensus_cache_lock: routers = sorted(self.router_cache.values(), key = attrgetter("last_tested"))[0:4] # Build test circuits. with self.consensus_cache_lock: for router in routers: # If we are testing a guard, we don't want to use it as a guard for this # circuit. Pop it tempor...
if e.errno == errno.EBADF:
if err == errno.EBADF:
def remove_pending_socket(socket): with self.send_pending_lock: self.send_sockets_pending.remove(sock)