Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
for line in data.split('\n'):
self._network_status_parser.process(line)
txtorlog.msg(len(self.routers_by_name), "named routers found.")
## remove any names we added that turned out to have dups
for (k, v) in self.routers.items():
if v is None:
txtorlog.msg(len(self.routers_by_name[k]), "dups:", k)
del self.routers[k]
elif not v in self.unique_routers:
self.unique_routers.append(v)
txtorlog.msg(len(self.guards), "GUARDs")
option. This is generally just a TCP port (e.g. ``9050``), but
can also be a unix path like so ``unix:/path/to/socket`` (Tor
has restrictions on the ownership/permissions of the directory
containing ``socket``). If the given SOCKS option is not
already available in the underlying Tor instance, it is
re-configured to add the SOCKS option.
"""
# :param tls: True (the default) will use Twisted's default options
# with the hostname in the URI -- that is, TLS verification
# similar to a Browser. Otherwise, you can pass whatever Twisted
# returns for `optionsForClientTLS
# `_
socks_config = str(socks_config) # sadly, all lists are lists-of-strings to Tor :/
if socks_config not in torconfig.SocksPort:
txtorlog.msg("Adding SOCKS port '{}' to Tor".format(socks_config))
torconfig.SocksPort.append(socks_config)
try:
yield torconfig.save()
except Exception as e:
raise RuntimeError(
"Failed to reconfigure Tor with SOCKS port '{}': {}".format(
socks_config, str(e)
)
)
if socks_config.startswith('unix:'):
socks_ep = UNIXClientEndpoint(reactor, socks_config[5:])
else:
if ':' in socks_config:
host, port = socks_config.split(':', 1)
else:
def _addr_map(self, addr):
"Internal callback to update DNS cache. Listens to ADDRMAP."
txtorlog.msg(" --> addr_map", addr)
self.addrmap.update(addr)
The stream attacher is allowed to return a Deferred which will
callback with the desired circuit.
You may return the special object DO_NOT_ATTACH which will
cause the circuit attacher to simply ignore the stream
(neither attaching it, nor telling Tor to attach it).
"""
if self.attacher:
if stream.target_host is not None and '.exit' in stream.target_host:
## we want to totally ignore .exit URIs as these are
## used to specify a particular exit node, and trying
## to do STREAMATTACH on them will fail with an error
## from Tor anyway.
txtorlog.msg("ignore attacher:", stream)
return
circ = IStreamAttacher(self.attacher).attach_stream(stream, self.circuits)
if circ is self.DO_NOT_ATTACH:
return
if circ is None:
self.protocol.queue_command("ATTACHSTREAM %d 0" % stream.id)
else:
if isinstance(circ, defer.Deferred):
class IssueStreamAttach:
def __init__(self, state, streamid):
self.stream_id = streamid
self.state = state
def _tor_connected(self, proto):
txtorlog.msg("tor_connected %s" % proto)
self.tor_protocol = proto
self.tor_protocol.is_owned = self.transport.pid
yield self.tor_protocol.post_bootstrap
txtorlog.msg("Protocol is bootstrapped")
yield self.tor_protocol.add_event_listener('STATUS_CLIENT', self._status_client)
yield self.tor_protocol.queue_command('TAKEOWNERSHIP')
yield self.tor_protocol.queue_command('RESETCONF __OwningControllerProcess')
if self.config is not None and self.config.protocol is None:
yield self.config.attach_protocol(proto)
returnValue(self) # XXX or "proto"?
def circuit_failed(self, circuit, reason):
"ICircuitListener API"
txtorlog.msg("circuit_failed", circuit, reason)
self.circuit_destroy(circuit)
if len(self.cookie_data) != 32:
raise RuntimeError("Expected authentication cookie to be 32 bytes, got %d" % len(self.cookie_data))
txtorlog.msg("Using SAFECOOKIE authentication",cookie,len(self.cookie_data),"bytes")
self.client_nonce = os.urandom(32)
d = self.queue_command('AUTHCHALLENGE SAFECOOKIE %s' % base64.b16encode(self.client_nonce))
d.addCallback(self._safecookie_authchallenge).addCallback(self._bootstrap).addErrback(self._auth_failed)
return
elif 'COOKIE' in methods:
cookie = re.search('COOKIEFILE="(.*)"', protoinfo).group(1)
with open(cookie, 'r') as cookiefile:
data = cookiefile.read()
if len(data) != 32:
raise RuntimeError("Expected authentication cookie to be 32 bytes, got %d" % len(data))
txtorlog.msg("Using COOKIE authentication", cookie, len(data), "bytes")
self.authenticate(data).addCallback(self._bootstrap).addErrback(self._auth_failed)
return
if self.password:
self.authenticate(self.password).addCallback(self._bootstrap).addErrback(self._auth_failed)
return
raise RuntimeError("The Tor I connected to doesn't support SAFECOOKIE nor COOKIE authentication and I have no password.")
def outReceived(self, data):
"""
:api:`twisted.internet.protocol.ProcessProtocol ` API
"""
if self.stdout:
self.stdout.write(data.decode('ascii'))
# minor hack: we can't try this in connectionMade because
# that's when the process first starts up so Tor hasn't
# opened any ports properly yet. So, we presume that after
# its first output we're good-to-go. If this fails, we'll
# reset and try again at the next output (see this class'
# tor_connection_failed)
txtorlog.msg(data)
if not self.attempted_connect and self.connection_creator \
and b'Opening Control listener' in data:
self.attempted_connect = True
# hmmm, we don't "do" anything with this Deferred?
# (should it be connected to the when_connected
# Deferreds?)
d = self.connection_creator()
d.addCallback(self._tor_connected)
d.addErrback(self._tor_connection_failed)
# XXX 'should' be able to improve the error-handling by directly tying