code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
for x in self.listeners:
try:
getattr(x, func)(*args, **kw)
except Exception:
log.err() | def _notify(self, func, *args, **kw) | Internal helper. Calls the IStreamListener function 'func' with
the given args, guarding around errors. | 3.197659 | 3.410756 | 0.937522 |
if self._closing_deferred:
self._closing_deferred.callback(self)
self._closing_deferred = None | def maybe_call_closing_deferred(self) | Used internally to callback on the _closing_deferred if it
exists. | 3.228961 | 2.279349 | 1.416616 |
try:
# we "often" have a REASON
reason = kw['REASON']
try:
# ...and sometimes even have a REMOTE_REASON
reason = '{}, {}'.format(reason, kw['REMOTE_REASON'])
except KeyError:
pass # should still be the 'REASON' error if we had it
except KeyError:
reason = "unknown"
return reason | def _extract_reason(kw) | Internal helper. Extracts a reason (possibly both reasons!) from
the kwargs for a circuit failed or closed event. | 8.200803 | 8.034479 | 1.020701 |
timed_circuit = []
d = tor_state.build_circuit(routers=path, using_guards=using_guards)
def get_circuit(c):
timed_circuit.append(c)
return c
def trap_cancel(f):
f.trap(defer.CancelledError)
if timed_circuit:
d2 = timed_circuit[0].close()
else:
d2 = defer.succeed(None)
d2.addCallback(lambda _: Failure(CircuitBuildTimedOutError("circuit build timed out")))
return d2
d.addCallback(get_circuit)
d.addCallback(lambda circ: circ.when_built())
d.addErrback(trap_cancel)
reactor.callLater(timeout, d.cancel)
return d | def build_timeout_circuit(tor_state, reactor, path, timeout, using_guards=False) | Build a new circuit within a timeout.
CircuitBuildTimedOutError will be raised unless we receive a
circuit build result (success or failure) within the `timeout`
duration.
:returns: a Deferred which fires when the circuit build succeeds (or
fails to build). | 3.518703 | 3.150031 | 1.117038 |
# XXX note to self: we never do an errback; fix this behavior
if self.state == 'BUILT':
return defer.succeed(self)
return self._when_built.when_fired() | def when_built(self) | Returns a Deferred that is callback()'d (with this Circuit
instance) when this circuit hits BUILT.
If it's already BUILT when this is called, you get an
already-successful Deferred; otherwise, the state must change
to BUILT.
If the circuit will never hit BUILT (e.g. it is abandoned by
Tor before it gets to BUILT) you will receive an errback | 13.771603 | 10.273261 | 1.340529 |
if self.state in ['CLOSED', 'FAILED']:
return defer.succeed(self)
return self._when_closed.when_fired() | def when_closed(self) | Returns a Deferred that callback()'s (with this Circuit instance)
when this circuit hits CLOSED or FAILED. | 6.702306 | 3.836445 | 1.74701 |
# local import because there isn't Agent stuff on some
# platforms we support, so this will only error if you try
# this on the wrong platform (pypy [??] and old-twisted)
from txtorcon import web
return web.tor_agent(
reactor,
socks_endpoint,
circuit=self,
pool=pool,
) | def web_agent(self, reactor, socks_endpoint, pool=None) | :param socks_endpoint: create one with
:meth:`txtorcon.TorConfig.create_socks_endpoint`. Can be a
Deferred.
:param pool: passed on to the Agent (as ``pool=``) | 19.372164 | 20.870651 | 0.928201 |
from .endpoints import TorClientEndpoint
ep = TorClientEndpoint(
host, port, socks_endpoint,
tls=use_tls,
reactor=reactor,
)
return TorCircuitEndpoint(reactor, self._torstate, self, ep) | def stream_via(self, reactor, host, port,
socks_endpoint,
use_tls=False) | This returns an `IStreamClientEndpoint`_ that will connect to
the given ``host``, ``port`` via Tor -- and via this
parciular circuit.
We match the streams up using their source-ports, so even if
there are many streams in-flight to the same destination they
will align correctly. For example, to cause a stream to go to
``torproject.org:443`` via a particular circuit::
@inlineCallbacks
def main(reactor):
circ = yield torstate.build_circuit() # lets Tor decide the path
yield circ.when_built()
tor_ep = circ.stream_via(reactor, 'torproject.org', 443)
# 'factory' is for your protocol
proto = yield tor_ep.connect(factory)
Note that if you're doing client-side Web requests, you
probably want to use `treq
<http://treq.readthedocs.org/en/latest/>`_ or ``Agent``
directly so call :meth:`txtorcon.Circuit.web_agent` instead.
:param socks_endpoint: should be a Deferred firing a valid
IStreamClientEndpoint pointing at a Tor SOCKS port (or an
IStreamClientEndpoint already).
.. _istreamclientendpoint: https://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IStreamClientEndpoint.html | 6.549855 | 6.653364 | 0.984443 |
# we're already closed; nothing to do
if self.state == 'CLOSED':
return defer.succeed(None)
# someone already called close() but we're not closed yet
if self._closing_deferred:
d = defer.Deferred()
def closed(arg):
d.callback(arg)
return arg
self._closing_deferred.addBoth(closed)
return d
# actually-close the circuit
self._closing_deferred = defer.Deferred()
def close_command_is_queued(*args):
return self._closing_deferred
d = self._torstate.close_circuit(self.id, **kw)
d.addCallback(close_command_is_queued)
return d | def close(self, **kw) | This asks Tor to close the underlying circuit object. See
:meth:`txtorcon.torstate.TorState.close_circuit`
for details.
You may pass keyword arguments to take care of any Flags Tor
accepts for the CLOSECIRCUIT command. Currently, this is only
"IfUnused". So for example: circ.close(IfUnused=True)
:return: Deferred which callbacks with this Circuit instance
ONLY after Tor has confirmed it is gone (not simply that the
CLOSECIRCUIT command has been queued). This could be a while
if you included IfUnused. | 4.209072 | 3.513053 | 1.198124 |
if not self.time_created:
return None
if now is None:
now = datetime.utcnow()
return (now - self.time_created).seconds | def age(self, now=None) | Returns an integer which is the difference in seconds from
'now' to when this circuit was created.
Returns None if there is no created-time. | 3.256083 | 2.917117 | 1.116199 |
if self._closing_deferred:
self._closing_deferred.callback(self)
self._closing_deferred = None
self._when_closed.fire(self) | def maybe_call_closing_deferred(self) | Used internally to callback on the _closing_deferred if it
exists. | 3.973077 | 3.321164 | 1.19629 |
oldpath = self.path
self.path = []
for p in path:
if p[0] != '$':
break
# this will create a Router if we give it a router
# LongName that doesn't yet exist
router = self.router_container.router_from_id(p)
self.path.append(router)
# if the path grew, notify listeners
if len(self.path) > len(oldpath):
for x in self.listeners:
x.circuit_extend(self, router)
oldpath = self.path | def update_path(self, path) | There are EXTENDED messages which don't include any routers at
all, and any of the EXTENDED messages may have some arbitrary
flags in them. So far, they're all upper-case and none start
with $ luckily. The routers in the path should all be
LongName-style router names (this depends on them starting
with $).
For further complication, it's possible to extend a circuit to
a router which isn't in the consensus. nickm via #tor thought
this might happen in the case of hidden services choosing a
rendevouz point not in the current consensus. | 7.669404 | 4.915254 | 1.560327 |
if six.PY2 and isinstance(hostname, str):
hostname = unicode(hostname) # noqa
elif six.PY3 and isinstance(hostname, bytes):
hostname = hostname.decode('ascii')
factory = _TorSocksFactory(
hostname, 0, 'RESOLVE', None,
)
proto = yield tor_endpoint.connect(factory)
result = yield proto.when_done()
returnValue(result) | def resolve(tor_endpoint, hostname) | This is easier to use via :meth:`txtorcon.Tor.dns_resolve`
:param tor_endpoint: the Tor SOCKS endpoint to use.
:param hostname: the hostname to look up. | 5.025729 | 5.6005 | 0.897371 |
if six.PY2 and isinstance(ip, str):
ip = unicode(ip) # noqa
elif six.PY3 and isinstance(ip, bytes):
ip = ip.decode('ascii')
factory = _TorSocksFactory(
ip, 0, 'RESOLVE_PTR', None,
)
proto = yield tor_endpoint.connect(factory)
result = yield proto.when_done()
returnValue(result) | def resolve_ptr(tor_endpoint, ip) | This is easier to use via :meth:`txtorcon.Tor.dns_resolve_ptr`
:param tor_endpoint: the Tor SOCKS endpoint to use.
:param ip: the IP address to look up. | 5.041317 | 5.45434 | 0.924276 |
# a "for x in self._outgoing_data" would potentially be more
# efficient, but then there's no good way to bubble exceptions
# from callback() out without lying about how much data we
# processed .. or eat the exceptions in here.
while len(self._outgoing_data):
data = self._outgoing_data.pop(0)
callback(data) | def send_data(self, callback) | drain all pending data by calling `callback()` on it | 11.486719 | 10.944044 | 1.049586 |
"waiting for a version reply"
if len(self._data) >= 2:
reply = self._data[:2]
self._data = self._data[2:]
(version, method) = struct.unpack('BB', reply)
if version == 5 and method in [0x00, 0x02]:
self.version_reply(method)
else:
if version != 5:
self.version_error(SocksError(
"Expected version 5, got {}".format(version)))
else:
self.version_error(SocksError(
"Wanted method 0 or 2, got {}".format(method))) | def _parse_version_reply(self) | waiting for a version reply | 3.350074 | 3.049382 | 1.098608 |
"waiting for a reply to our request"
# we need at least 6 bytes of data: 4 for the "header", such
# as it is, and 2 more if it's DOMAINNAME (for the size) or 4
# or 16 more if it's an IPv4/6 address reply. plus there's 2
# bytes on the end for the bound port.
if len(self._data) < 8:
return
msg = self._data[:4]
# not changing self._data yet, in case we've not got
# enough bytes so far.
(version, reply, _, typ) = struct.unpack('BBBB', msg)
if version != 5:
self.reply_error(SocksError(
"Expected version 5, got {}".format(version)))
return
if reply != self.SUCCEEDED:
self.reply_error(_create_socks_error(reply))
return
reply_dispatcher = {
self.REPLY_IPV4: self._parse_ipv4_reply,
self.REPLY_HOST: self._parse_domain_name_reply,
self.REPLY_IPV6: self._parse_ipv6_reply,
}
try:
method = reply_dispatcher[typ]
except KeyError:
self.reply_error(SocksError(
"Unexpected response type {}".format(typ)))
return
method() | def _parse_request_reply(self) | waiting for a reply to our request | 5.728458 | 5.344152 | 1.071911 |
"make our proxy connection"
sender = self._create_connection(addr, port)
# XXX look out! we're depending on this "sender" implementing
# certain Twisted APIs, and the state-machine shouldn't depend
# on that.
# XXX also, if sender implements producer/consumer stuff, we
# should register ourselves (and implement it to) -- but this
# should really be taking place outside the state-machine in
# "the I/O-doing" stuff
self._sender = sender
self._when_done.fire(sender) | def _make_connection(self, addr, port) | make our proxy connection | 20.201513 | 19.091251 | 1.058156 |
"done"
if self._on_disconnect:
self._on_disconnect(str(error))
if self._sender:
self._sender.connectionLost(Failure(error))
self._when_done.fire(Failure(error)) | def _disconnect(self, error) | done | 7.094702 | 6.350142 | 1.117251 |
"relay any data we have"
if self._data:
d = self._data
self._data = b''
# XXX this is "doing I/O" in the state-machine and it
# really shouldn't be ... probably want a passed-in
# "relay_data" callback or similar?
self._sender.dataReceived(d) | def _relay_data(self) | relay any data we have | 12.330665 | 10.691278 | 1.153339 |
"sends CONNECT request"
# XXX needs to support v6 ... or something else does
host = self._addr.host
port = self._addr.port
if isinstance(self._addr, (IPv4Address, IPv6Address)):
is_v6 = isinstance(self._addr, IPv6Address)
self._data_to_send(
struct.pack(
'!BBBB4sH',
5, # version
0x01, # command
0x00, # reserved
0x04 if is_v6 else 0x01,
inet_pton(AF_INET6 if is_v6 else AF_INET, host),
port,
)
)
else:
host = host.encode('ascii')
self._data_to_send(
struct.pack(
'!BBBBB{}sH'.format(len(host)),
5, # version
0x01, # command
0x00, # reserved
0x03,
len(host),
host,
port,
)
) | def _send_connect_request(self) | sends CONNECT request | 3.161857 | 3.069398 | 1.030123 |
"sends RESOLVE_PTR request (Tor custom)"
host = self._addr.host.encode()
self._data_to_send(
struct.pack(
'!BBBBB{}sH'.format(len(host)),
5, # version
0xF0, # command
0x00, # reserved
0x03, # DOMAINNAME
len(host),
host,
0, # self._addr.port?
)
) | def _send_resolve_request(self) | sends RESOLVE_PTR request (Tor custom) | 8.192061 | 5.30993 | 1.542781 |
"sends RESOLVE_PTR request (Tor custom)"
addr_type = 0x04 if isinstance(self._addr, ipaddress.IPv4Address) else 0x01
encoded_host = inet_aton(self._addr.host)
self._data_to_send(
struct.pack(
'!BBBB4sH',
5, # version
0xF1, # command
0x00, # reserved
addr_type,
encoded_host,
0, # port; unused? SOCKS is fun
)
) | def _send_resolve_ptr_request(self) | sends RESOLVE_PTR request (Tor custom) | 7.585581 | 5.746932 | 1.319936 |
# "... in the form YYYY-MM-DD HH:MM:SS, in UTC"
if self._modified is None:
self._modified = datetime.strptime(
self._modified_unparsed,
'%Y-%m-%d %H:%M:%S'
)
return self._modified | def modified(self) | This is the time of 'the publication time of its most recent
descriptor' (in UTC).
See also dir-spec.txt. | 4.35109 | 3.909172 | 1.113046 |
if self._location:
return succeed(self._location)
if self.ip != 'unknown':
self._location = NetLocation(self.ip)
else:
self._location = NetLocation(None)
if not self._location.countrycode and self.ip != 'unknown':
# see if Tor is magic and knows more...
d = self.controller.get_info_raw('ip-to-country/' + self.ip)
d.addCallback(self._set_country)
d.addCallback(lambda _: self._location)
return d
return succeed(self._location) | def get_location(self) | Returns a Deferred that fires with a NetLocation object for this
router. | 4.564201 | 3.898572 | 1.170737 |
if self._location:
return self._location
if self.ip != 'unknown':
self._location = NetLocation(self.ip)
else:
self._location = NetLocation(None)
if not self._location.countrycode and self.ip != 'unknown':
# see if Tor is magic and knows more...
d = self.controller.get_info_raw('ip-to-country/' + self.ip)
d.addCallback(self._set_country)
# ignore errors (e.g. "GeoIP Information not loaded")
d.addErrback(lambda _: None)
return self._location | def location(self) | A NetLocation instance with some GeoIP or pygeoip information
about location, asn, city (if available). | 5.736181 | 5.070577 | 1.131268 |
if isinstance(flags, (six.text_type, bytes)):
flags = flags.split()
self._flags = [x.lower() for x in flags]
self.name_is_unique = 'named' in self._flags | def flags(self, flags) | It might be nice to make flags not a list of strings. This is
made harder by the control-spec: `...controllers MUST tolerate
unrecognized flags and lines...`
There is some current work in Twisted for open-ended constants
(enums) support however, it seems. | 4.751469 | 5.04078 | 0.942606 |
# clearnet: 'https://onionoo.torproject.org/details?lookup={}'
uri = 'http://tgel7v4rpcllsrk2.onion/details?lookup={}'.format(self.id_hex[1:]).encode('ascii')
resp = yield agent.request(b'GET', uri)
if resp.code != 200:
raise RuntimeError(
'Failed to lookup relay details for {}'.format(self.id_hex)
)
body = yield readBody(resp)
data = json.loads(body.decode('ascii'))
if len(data['relays']) != 1:
raise RuntimeError(
'Got multiple relays for {}'.format(self.id_hex)
)
relay_data = data['relays'][0]
if relay_data['fingerprint'].lower() != self.id_hex[1:].lower():
raise RuntimeError(
'Expected "{}" but got data for "{}"'.format(self.id_hex, relay_data['fingerprint'])
)
returnValue(relay_data) | def get_onionoo_details(self, agent) | Requests the 'details' document from onionoo.torproject.org via
the given `twisted.web.iweb.IAgent` -- you can get a suitable
instance to pass here by calling either :meth:`txtorcon.Tor.web_agent` or
:meth:`txtorcon.Circuit.web_agent`. | 4.233733 | 3.874077 | 1.092837 |
if self.accepted_ports:
return 'accept ' + ','.join(map(str, self.accepted_ports))
elif self.rejected_ports:
return 'reject ' + ','.join(map(str, self.rejected_ports))
else:
return '' | def policy(self) | Port policies for this Router.
:return: a string describing the policy | 2.820395 | 2.532148 | 1.113835 |
word = args[0]
if word == 'reject':
self.accepted_ports = None
self.rejected_ports = []
target = self.rejected_ports
elif word == 'accept':
self.accepted_ports = []
self.rejected_ports = None
target = self.accepted_ports
else:
raise RuntimeError("Don't understand policy word \"%s\"" % word)
for port in args[1].split(','):
if '-' in port:
(a, b) = port.split('-')
target.append(PortRange(int(a), int(b)))
else:
target.append(int(port)) | def policy(self, args) | setter for the policy descriptor | 2.927248 | 2.863915 | 1.022114 |
if self.rejected_ports is None and self.accepted_ports is None:
raise RuntimeError("policy hasn't been set yet")
if self.rejected_ports:
for x in self.rejected_ports:
if port == x:
return False
return True
for x in self.accepted_ports:
if port == x:
return True
return False | def accepts_port(self, port) | Query whether this Router will accept the given port. | 2.872485 | 2.841544 | 1.010889 |
self.location.countrycode = c.split()[0].split('=')[1].strip().upper() | def _set_country(self, c) | callback if we used Tor's GETINFO ip-to-country | 14.158934 | 10.902778 | 1.298654 |
global _global_tor
global _global_tor_lock
yield _global_tor_lock.acquire()
if _tor_launcher is None:
# XXX :( mutual dependencies...really get_global_tor_instance
# should be in controller.py if it's going to return a Tor
# instance.
from .controller import launch
_tor_launcher = launch
try:
if _global_tor is None:
_global_tor = yield _tor_launcher(reactor, progress_updates=progress_updates)
else:
config = yield _global_tor.get_config()
already_port = config.ControlPort
if control_port is not None and control_port != already_port:
raise RuntimeError(
"ControlPort is already '{}', but you wanted '{}'",
already_port,
control_port,
)
defer.returnValue(_global_tor)
finally:
_global_tor_lock.release() | def get_global_tor_instance(reactor,
control_port=None,
progress_updates=None,
_tor_launcher=None) | Normal users shouldn't need to call this; use
TCPHiddenServiceEndpoint::system_tor instead.
:return Tor: a 'global to this Python process' instance of
Tor. There isn't one of these until the first time this method
is called. All calls to this method return the same instance. | 4.041409 | 4.45003 | 0.908176 |
tor = yield get_global_tor_instance(
reactor,
control_port=control_port,
progress_updates=progress_updates,
_tor_launcher=_tor_launcher,
)
cfg = yield tor.get_config()
defer.returnValue(cfg) | def get_global_tor(reactor, control_port=None,
progress_updates=None,
_tor_launcher=None) | See description of :class:`txtorcon.TCPHiddenServiceEndpoint`'s
class-method ``global_tor``
:param control_port:
a TCP port upon which to run the launched Tor's
control-protocol (selected by the OS by default).
:param progress_updates:
A callable that takes 3 args: ``percent, tag, message`` which
is called when Tor announcing some progress setting itself up.
:returns:
a ``Deferred`` that fires a :class:`txtorcon.TorConfig` which is
bootstrapped.
The _tor_launcher keyword arg is internal-only. | 2.43115 | 3.366432 | 0.722174 |
with open(fname, "rb") as f:
data = f.read()
if b"\x00\x00\x00" in data: # v3 private key file
blob = data[data.find(b"\x00\x00\x00") + 3:]
return u"ED25519-V3:{}".format(b2a_base64(blob.strip()).decode('ascii').strip())
if b"-----BEGIN RSA PRIVATE KEY-----" in data: # v2 RSA key
blob = "".join(data.decode('ascii').split('\n')[1:-2])
return u"RSA1024:{}".format(blob)
blob = data.decode('ascii').strip()
if ':' in blob:
kind, key = blob.split(':', 1)
if kind in ['ED25519-V3', 'RSA1024']:
return blob
raise ValueError(
"'{}' does not appear to contain v2 or v3 private key data".format(
fname,
)
) | def _load_private_key_file(fname) | Loads an onion-service private-key from the given file. This can
be either a 'key blog' as returned from a previous ADD_ONION call,
or a v3 or v2 file as created by Tor when using the
HiddenServiceDir directive.
In any case, a key-blob suitable for ADD_ONION use is returned. | 3.000699 | 2.834388 | 1.058676 |
socks_ports = yield control_protocol.get_conf('SOCKSPort')
if socks_ports:
socks_ports = list(socks_ports.values())[0]
if not isinstance(socks_ports, list):
socks_ports = [socks_ports]
# see TorConfig for more fun-times regarding *PortLines, including
# the __*Port things...
if socks_ports == ['DEFAULT']:
default = yield control_protocol.get_conf_single('__SocksPort')
socks_ports = [default]
else:
# return from get_conf was an empty dict; we want a list
socks_ports = []
# everything in the SocksPort list can include "options" after the
# initial value. We don't care about those, but do need to strip
# them.
socks_ports = [port.split()[0] for port in socks_ports]
# could check platform? but why would you have unix ports on a
# platform that doesn't?
unix_ports = set([p for p in socks_ports if p.startswith('unix:')])
tcp_ports = set(socks_ports) - unix_ports
socks_endpoint = None
for p in list(unix_ports) + list(tcp_ports): # prefer unix-ports
if socks_config and p != socks_config:
continue
try:
socks_endpoint = _endpoint_from_socksport_line(reactor, p)
except Exception as e:
log.err(
Failure(),
"failed to process SOCKS port '{}': {}".format(p, e)
)
# if we still don't have an endpoint, nothing worked (or there
# were no SOCKSPort lines at all) so we add config to tor
if socks_endpoint is None:
if socks_config is None:
# is a unix-socket in /tmp on a supported platform better than
# this?
port = yield available_tcp_port(reactor)
socks_config = str(port)
socks_ports.append(socks_config)
# NOTE! We must set all the ports in one command or we'll
# destroy pre-existing config
args = []
for p in socks_ports:
args.append('SOCKSPort')
args.append(p)
yield control_protocol.set_conf(*args)
socks_endpoint = _endpoint_from_socksport_line(reactor, socks_config)
assert socks_endpoint is not None
defer.returnValue(socks_endpoint) | def _create_socks_endpoint(reactor, control_protocol, socks_config=None) | Internal helper.
This uses an already-configured SOCKS endpoint from the attached
Tor, or creates a new TCP one (and configures Tor with it). If
socks_config is non-None, it is a SOCKSPort line and will either
be used if it already exists or will be created. | 4.908714 | 4.676726 | 1.049605 |
hosts = [
onion.get_client(nm).hostname
for nm in onion.client_names()
]
if not hosts:
raise ValueError(
"Can't access .onion_uri because there are no clients"
)
host = hosts[0]
for h in hosts[1:]:
if h != host:
raise ValueError(
"Cannot access .onion_uri for stealth-authenticated services "
"because each client has a unique URI"
)
return host | def _maybe_unique_host(onion) | :param onion: IAuthenticatedOnionClients provider
:returns: a .onion hostname if all clients have the same name or
raises ValueError otherwise | 5.575245 | 4.794775 | 1.162775 |
from .controller import launch
# XXX FIXME are we dealing with options in the config "properly"
# as far as translating semantics from the old launch_tor to
# launch()? DataDirectory, User, ControlPort, ...?
tor = yield launch(
reactor,
stdout=stdout,
stderr=stderr,
progress_updates=progress_updates,
tor_binary=tor_binary,
connection_creator=connection_creator,
timeout=timeout,
kill_on_stderr=kill_on_stderr,
_tor_config=config,
)
defer.returnValue(tor.process) | def launch_tor(config, reactor,
tor_binary=None,
progress_updates=None,
connection_creator=None,
timeout=None,
kill_on_stderr=True,
stdout=None, stderr=None) | Deprecated; use launch() instead.
See also controller.py | 5.980173 | 5.999344 | 0.996804 |
# @functools.wraps(orig)
def foo(*args):
obj = args[0]
obj.on_modify()
return orig(*args)
return foo | def _wrapture(orig) | Returns a new method that wraps orig (the original method) with
something that first calls on_modify from the
instance. _ListWrapper uses this to wrap all methods that modify
the list. | 5.078013 | 3.482593 | 1.458113 |
if socks_config.startswith('unix:'):
# XXX wait, can SOCKSPort lines with "unix:/path" still
# include options afterwards? What about if the path has a
# space in it?
return UNIXClientEndpoint(reactor, socks_config[5:])
# options like KeepAliveIsolateSOCKSAuth can be appended
# to a SocksPort line...
if ' ' in socks_config:
socks_config = socks_config.split()[0]
if ':' in socks_config:
host, port = socks_config.split(':', 1)
port = int(port)
else:
host = '127.0.0.1'
port = int(socks_config)
return TCP4ClientEndpoint(reactor, host, port) | def _endpoint_from_socksport_line(reactor, socks_config) | Internal helper.
Returns an IStreamClientEndpoint for the given config, which is of
the same format expected by the SOCKSPort option in Tor. | 4.619977 | 4.589359 | 1.006671 |
rtn = [('HiddenServiceDir', str(self.dir))]
if self.conf._supports['HiddenServiceDirGroupReadable'] \
and self.group_readable:
rtn.append(('HiddenServiceDirGroupReadable', str(1)))
for port in self.ports:
rtn.append(('HiddenServicePort', str(port)))
if self.version:
rtn.append(('HiddenServiceVersion', str(self.version)))
for authline in self.authorize_client:
rtn.append(('HiddenServiceAuthorizeClient', str(authline)))
return rtn | def config_attributes(self) | Helper method used by TorConfig when generating a torrc file. | 5.098716 | 4.16715 | 1.22355 |
'''
Returns a Deferred which fires with 'self' after at least one
descriptor has been uploaded. Errback if no descriptor upload
succeeds.
'''
upload_d = _await_descriptor_upload(protocol, self, progress=None, await_all_uploads=False)
# _add_ephemeral_service takes a TorConfig but we don't have
# that here .. and also we're just keeping this for
# backwards-compatability anyway so instead of trying to
# re-use that helper I'm leaving this original code here. So
# this is what it supports and that's that:
ports = ' '.join(map(lambda x: 'Port=' + x.strip(), self._ports))
cmd = 'ADD_ONION %s %s' % (self._key_blob, ports)
ans = yield protocol.queue_command(cmd)
ans = find_keywords(ans.split('\n'))
self.hostname = ans['ServiceID'] + '.onion'
if self._key_blob.startswith('NEW:'):
self.private_key = ans['PrivateKey']
else:
self.private_key = self._key_blob
log.msg('Created hidden-service at', self.hostname)
log.msg("Created '{}', waiting for descriptor uploads.".format(self.hostname))
yield upload_d | def add_to_tor(self, protocol) | Returns a Deferred which fires with 'self' after at least one
descriptor has been uploaded. Errback if no descriptor upload
succeeds. | 10.237422 | 7.701892 | 1.329209 |
'''
Returns a Deferred which fires with None
'''
r = yield protocol.queue_command('DEL_ONION %s' % self.hostname[:-6])
if r.strip() != 'OK':
raise RuntimeError('Failed to remove hidden service: "%s".' % r) | def remove_from_tor(self, protocol) | Returns a Deferred which fires with None | 11.214499 | 9.11638 | 1.230148 |
cfg = TorConfig(control=proto)
yield cfg.post_bootstrap
defer.returnValue(cfg) | def from_protocol(proto) | This creates and returns a ready-to-go TorConfig instance from the
given protocol, which should be an instance of
TorControlProtocol. | 23.587229 | 16.705133 | 1.411975 |
if len(self.SocksPort) == 0:
raise RuntimeError(
"No SOCKS ports configured"
)
socks_config = None
if port is None:
socks_config = self.SocksPort[0]
else:
port = str(port) # in case e.g. an int passed in
if ' ' in port:
raise ValueError(
"Can't specify options; use create_socks_endpoint instead"
)
for idx, port_config in enumerate(self.SocksPort):
# "SOCKSPort" is a gnarly beast that can have a bunch
# of options appended, so we have to split off the
# first thing which *should* be the port (or can be a
# string like 'unix:')
if port_config.split()[0] == port:
socks_config = port_config
break
if socks_config is None:
raise RuntimeError(
"No SOCKSPort configured for port {}".format(port)
)
return _endpoint_from_socksport_line(reactor, socks_config) | def socks_endpoint(self, reactor, port=None) | Returns a TorSocksEndpoint configured to use an already-configured
SOCKSPort from the Tor we're connected to. By default, this
will be the very first SOCKSPort.
:param port: a str, the first part of the SOCKSPort line (that
is, a port like "9151" or a Unix socket config like
"unix:/path". You may also specify a port as an int.
If you need to use a particular port that may or may not
already be configured, see the async method
:meth:`txtorcon.TorConfig.create_socks_endpoint` | 4.958831 | 4.211382 | 1.177483 |
yield self.post_bootstrap
if socks_config is None:
if len(self.SocksPort) == 0:
raise RuntimeError(
"socks_port is None and Tor has no SocksPorts configured"
)
socks_config = self.SocksPort[0]
else:
if not any([socks_config in port for port in self.SocksPort]):
# need to configure Tor
self.SocksPort.append(socks_config)
try:
yield self.save()
except TorProtocolError as e:
extra = ''
if socks_config.startswith('unix:'):
# XXX so why don't we check this for the
# caller, earlier on?
extra = '\nNote Tor has specific ownership/permissions ' +\
'requirements for unix sockets and parent dir.'
raise RuntimeError(
"While configuring SOCKSPort to '{}', error from"
" Tor: {}{}".format(
socks_config, e, extra
)
)
defer.returnValue(
_endpoint_from_socksport_line(reactor, socks_config)
) | def create_socks_endpoint(self, reactor, socks_config) | Creates a new TorSocksEndpoint instance given a valid
configuration line for ``SocksPort``; if this configuration
isn't already in the underlying tor, we add it. Note that this
method may call :meth:`txtorcon.TorConfig.save()` on this instance.
Note that calling this with `socks_config=None` is equivalent
to calling `.socks_endpoint` (which is not async).
XXX socks_config should be .. i dunno, but there's fucking
options and craziness, e.g. default Tor Browser Bundle is:
['9150 IPv6Traffic PreferIPv6 KeepAliveIsolateSOCKSAuth',
'9155']
XXX maybe we should say "socks_port" as the 3rd arg, insist
it's an int, and then allow/support all the other options
(e.g. via kwargs)
XXX we could avoid the "maybe call .save()" thing; worth it?
(actually, no we can't or the Tor won't have it config'd) | 6.574325 | 5.255693 | 1.250896 |
if self._protocol is not None:
raise RuntimeError("Already have a protocol.")
# make sure we have nothing in self.unsaved
self.save()
self.__dict__['_protocol'] = proto
# FIXME some of this is duplicated from ctor
del self.__dict__['_accept_all_']
self.__dict__['post_bootstrap'] = defer.Deferred()
if proto.post_bootstrap:
proto.post_bootstrap.addCallback(self.bootstrap)
return self.__dict__['post_bootstrap'] | def attach_protocol(self, proto) | returns a Deferred that fires once we've set this object up to
track the protocol. Fails if we already have a protocol. | 6.83073 | 6.04937 | 1.129164 |
# XXX FIXME uhm...how to do all the different types of hidden-services?
if name.lower() == 'hiddenservices':
return FilesystemOnionService
return type(self.parsers[name]) | def get_type(self, name) | return the type of a config key.
:param: name the key
FIXME can we do something more-clever than this for client
code to determine what sort of thing a key is? | 32.031395 | 23.59149 | 1.357752 |
conf = parse_keywords(arg, multiline_values=False)
for (k, v) in conf.items():
# v will be txtorcon.DEFAULT_VALUE already from
# parse_keywords if it was unspecified
real_name = self._find_real_name(k)
if real_name in self.parsers:
v = self.parsers[real_name].parse(v)
self.config[real_name] = v | def _conf_changed(self, arg) | internal callback. from control-spec:
4.1.18. Configuration changed
The syntax is:
StartReplyLine *(MidReplyLine) EndReplyLine
StartReplyLine = "650-CONF_CHANGED" CRLF
MidReplyLine = "650-" KEYWORD ["=" VALUE] CRLF
EndReplyLine = "650 OK"
Tor configuration options have changed (such as via a SETCONF or
RELOAD signal). KEYWORD and VALUE specify the configuration option
that was changed. Undefined configuration options contain only the
KEYWORD. | 7.310803 | 7.389715 | 0.989321 |
'''
This only takes args so it can be used as a callback. Don't
pass an arg, it is ignored.
'''
try:
d = self.protocol.add_event_listener(
'CONF_CHANGED', self._conf_changed)
except RuntimeError:
# for Tor versions which don't understand CONF_CHANGED
# there's nothing we can really do.
log.msg(
"Can't listen for CONF_CHANGED event; won't stay up-to-date "
"with other clients.")
d = defer.succeed(None)
d.addCallback(lambda _: self.protocol.get_info_raw("config/names"))
d.addCallback(self._do_setup)
d.addCallback(self.do_post_bootstrap)
d.addErrback(self.do_post_errback) | def bootstrap(self, arg=None) | This only takes args so it can be used as a callback. Don't
pass an arg, it is ignored. | 6.161365 | 4.562693 | 1.350379 |
if not self.needs_save():
return defer.succeed(self)
args = []
directories = []
for (key, value) in self.unsaved.items():
if key == 'HiddenServices':
self.config['HiddenServices'] = value
# using a list here because at least one unit-test
# cares about order -- and conceivably order *could*
# matter here, to Tor...
services = list()
# authenticated services get flattened into the HiddenServices list...
for hs in value:
if IOnionClient.providedBy(hs):
parent = IOnionClient(hs).parent
if parent not in services:
services.append(parent)
elif isinstance(hs, (EphemeralOnionService, EphemeralHiddenService)):
raise ValueError(
"Only filesystem based Onion services may be added"
" via TorConfig.hiddenservices; ephemeral services"
" must be created with 'create_onion_service'."
)
else:
if hs not in services:
services.append(hs)
for hs in services:
for (k, v) in hs.config_attributes():
if k == 'HiddenServiceDir':
if v not in directories:
directories.append(v)
args.append(k)
args.append(v)
else:
raise RuntimeError("Trying to add hidden service with same HiddenServiceDir: %s" % v)
else:
args.append(k)
args.append(v)
continue
if isinstance(value, list):
for x in value:
# FIXME XXX
if x is not DEFAULT_VALUE:
args.append(key)
args.append(str(x))
else:
args.append(key)
args.append(value)
# FIXME in future we should wait for CONF_CHANGED and
# update then, right?
real_name = self._find_real_name(key)
if not isinstance(value, list) and real_name in self.parsers:
value = self.parsers[real_name].parse(value)
self.config[real_name] = value
# FIXME might want to re-think this, but currently there's no
# way to put things into a config and get them out again
# nicely...unless you just don't assign a protocol
if self.protocol:
d = self.protocol.set_conf(*args)
d.addCallback(self._save_completed)
return d
else:
self._save_completed()
return defer.succeed(self) | def save(self) | Save any outstanding items. This returns a Deferred which will
errback if Tor was unhappy with anything, or callback with
this TorConfig object on success. | 5.306643 | 4.91351 | 1.080011 |
'''
Returns an iterator of 2-tuples (config_name, value), one for each
configuration option in this config. This is more-or-less an
internal method, but see, e.g., launch_tor()'s implementation
if you think you need to use this for something.
See :meth:`txtorcon.TorConfig.create_torrc` which returns a
string which is also a valid ``torrc`` file
'''
everything = dict()
everything.update(self.config)
everything.update(self.unsaved)
for (k, v) in list(everything.items()):
if type(v) is _ListWrapper:
if k.lower() == 'hiddenservices':
for x in v:
for (kk, vv) in x.config_attributes():
yield (str(kk), str(vv))
else:
# FIXME actually, is this right? don't we want ALL
# the values in one string?!
for x in v:
yield (str(k), str(x))
else:
yield (str(k), str(v)) | def config_args(self) | Returns an iterator of 2-tuples (config_name, value), one for each
configuration option in this config. This is more-or-less an
internal method, but see, e.g., launch_tor()'s implementation
if you think you need to use this for something.
See :meth:`txtorcon.TorConfig.create_torrc` which returns a
string which is also a valid ``torrc`` file | 6.672226 | 2.827643 | 2.359643 |
@inlineCallbacks
def try_endpoint(control_ep):
assert IStreamClientEndpoint.providedBy(control_ep)
proto = yield control_ep.connect(
TorProtocolFactory(
password_function=password_function
)
)
config = yield TorConfig.from_protocol(proto)
tor = Tor(reactor, proto, _tor_config=config)
returnValue(tor)
if control_endpoint is None:
to_try = [
UNIXClientEndpoint(reactor, '/var/run/tor/control'),
TCP4ClientEndpoint(reactor, '127.0.0.1', 9051),
TCP4ClientEndpoint(reactor, '127.0.0.1', 9151),
]
elif IStreamClientEndpoint.providedBy(control_endpoint):
to_try = [control_endpoint]
elif isinstance(control_endpoint, Sequence):
to_try = control_endpoint
for ep in control_endpoint:
if not IStreamClientEndpoint.providedBy(ep):
raise ValueError(
"For control_endpoint=, '{}' must provide"
" IStreamClientEndpoint".format(ep)
)
else:
raise ValueError(
"For control_endpoint=, '{}' must provide"
" IStreamClientEndpoint".format(control_endpoint)
)
errors = []
for idx, ep in enumerate(to_try):
try:
tor = yield try_endpoint(ep)
txtorlog.msg("Connected via '{}'".format(ep))
returnValue(tor)
except Exception as e:
errors.append(e)
if len(errors) == 1:
raise errors[0]
raise RuntimeError(
'Failed to connect to: {}'.format(
', '.join(
'{}: {}'.format(ep, err) for ep, err in zip(to_try, errors)
)
)
) | def connect(reactor, control_endpoint=None, password_function=None) | Creates a :class:`txtorcon.Tor` instance by connecting to an
already-running tor's control port. For example, a common default
tor uses is UNIXClientEndpoint(reactor, '/var/run/tor/control') or
TCP4ClientEndpoint(reactor, 'localhost', 9051)
If only password authentication is available in the tor we connect
to, the ``password_function`` is called (if supplied) to retrieve
a valid password. This function can return a Deferred.
For example::
import txtorcon
from twisted.internet.task import react
from twisted.internet.defer import inlineCallbacks
@inlineCallbacks
def main(reactor):
tor = yield txtorcon.connect(
TCP4ClientEndpoint(reactor, "localhost", 9051)
)
state = yield tor.create_state()
for circuit in state.circuits:
print(circuit)
:param control_endpoint: None, an IStreamClientEndpoint to connect
to, or a Sequence of IStreamClientEndpoint instances to connect
to. If None, a list of defaults are tried.
:param password_function:
See :class:`txtorcon.TorControlProtocol`
:return:
a Deferred that fires with a :class:`txtorcon.Tor` instance | 2.36731 | 2.104151 | 1.125066 |
if self._connected_listeners is None:
return
for d in self._connected_listeners:
# Twisted will turn this into an errback if "arg" is a
# Failure
d.callback(arg)
self._connected_listeners = None | def _maybe_notify_connected(self, arg) | Internal helper.
.callback or .errback on all Deferreds we've returned from
`when_connected` | 5.845813 | 5.151156 | 1.134855 |
try:
self.transport.signalProcess('TERM')
d = Deferred()
self._on_exit.append(d)
except error.ProcessExitedAlready:
self.transport.loseConnection()
d = succeed(None)
except Exception:
d = fail()
return d | def quit(self) | This will terminate (with SIGTERM) the underlying Tor process.
:returns: a Deferred that callback()'s (with None) when the
process has actually exited. | 5.770467 | 4.459026 | 1.294109 |
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) | def outReceived(self, data) | :api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API | 9.878793 | 9.35675 | 1.055793 |
self._did_timeout = True
try:
self.transport.signalProcess('TERM')
except error.ProcessExitedAlready:
# XXX why don't we just always do this?
self.transport.loseConnection()
fail = Failure(RuntimeError("timeout while launching Tor"))
self._maybe_notify_connected(fail) | def _timeout_expired(self) | A timeout was supplied during setup, and the time has run out. | 10.000691 | 8.685832 | 1.15138 |
if self.stderr:
self.stderr.write(data)
if self.kill_on_stderr:
self.transport.loseConnection()
raise RuntimeError(
"Received stderr output from slave Tor process: " + data.decode('utf8')
) | def errReceived(self, data) | :api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API | 6.774239 | 5.951758 | 1.138191 |
all([delete_file_or_tree(f) for f in self.to_delete])
self.to_delete = [] | def cleanup(self) | Clean up my temporary files. | 8.323302 | 6.400006 | 1.300515 |
self.cleanup()
if status.value.exitCode is None:
if self._did_timeout:
err = RuntimeError("Timeout waiting for Tor launch.")
else:
err = RuntimeError(
"Tor was killed (%s)." % status.value.signal)
else:
err = RuntimeError(
"Tor exited with error-code %d" % status.value.exitCode)
# hmmm, this log() should probably go away...not always an
# error (e.g. .quit()
log.err(err)
self._maybe_notify_connected(Failure(err)) | def processEnded(self, status) | :api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>` API | 7.597342 | 6.882156 | 1.103919 |
if self.progress_updates:
self.progress_updates(percent, tag, summary) | def progress(self, percent, tag, summary) | Can be overridden or monkey-patched if you want to get
progress updates yourself. | 5.178554 | 4.447716 | 1.164318 |
control_ep = UNIXClientEndpoint(reactor, '/var/run/tor/control')
tor = yield txtorcon.connect(reactor, control_ep)
state = yield tor.create_state()
print("Closing all circuits:")
for circuit in list(state.circuits.values()):
path = '->'.join(map(lambda r: r.id_hex, circuit.path))
print("Circuit {} through {}".format(circuit.id, path))
for stream in circuit.streams:
print(" Stream {} to {}".format(stream.id, stream.target_host))
yield stream.close()
print(" closed")
yield circuit.close()
print("closed")
yield tor.quit() | def main(reactor) | Close all open streams and circuits in the Tor we connect to | 4.858546 | 4.469167 | 1.087126 |
gmtexpires = None
(name, ip, expires) = args[:3]
for arg in args:
if arg.lower().startswith('expires='):
gmtexpires = arg[8:]
if gmtexpires is None:
if len(args) == 3:
gmtexpires = expires
else:
if args[2] == 'NEVER':
gmtexpires = args[2]
else:
gmtexpires = args[3]
self.name = name # "www.example.com"
self.ip = maybe_ip_addr(ip) # IPV4Address instance, or string
if self.ip == '<error>':
self._expire()
return
fmt = "%Y-%m-%d %H:%M:%S"
# if we already have expiry times, etc then we want to
# properly delay our timeout
oldexpires = self.expires
if gmtexpires.upper() == 'NEVER':
# FIXME can I just select a date 100 years in the future instead?
self.expires = None
else:
self.expires = datetime.datetime.strptime(gmtexpires, fmt)
self.created = datetime.datetime.utcnow()
if self.expires is not None:
if oldexpires is None:
if self.expires <= self.created:
diff = datetime.timedelta(seconds=0)
else:
diff = self.expires - self.created
self.expiry = self.map.scheduler.callLater(diff.seconds,
self._expire)
else:
diff = self.expires - oldexpires
self.expiry.delay(diff.seconds) | def update(self, *args) | deals with an update from Tor; see parsing logic in torcontroller | 4.28491 | 4.257755 | 1.006378 |
del self.map.addr[self.name]
self.map.notify("addrmap_expired", *[self.name], **{}) | def _expire(self) | callback done via callLater | 18.116289 | 17.653339 | 1.026224 |
params = shlex.split(update)
if params[0] in self.addr:
self.addr[params[0]].update(*params)
else:
a = Addr(self)
# add both name and IP address
self.addr[params[0]] = a
self.addr[params[1]] = a
a.update(*params)
self.notify("addrmap_added", *[a], **{}) | def update(self, update) | Deal with an update from Tor; either creates a new Addr object
or find existing one and calls update() on it. | 6.466763 | 5.031728 | 1.285197 |
return Headers({
b"User-Agent": [b"Mozilla/5.0 (Windows NT 6.1; rv:45.0) Gecko/20100101 Firefox/45.0"],
b"Accept": [b"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"],
b"Accept-Language": [b"en-US,en;q=0.5"],
b"Accept-Encoding": [b"gzip, deflate"],
}) | def create_tbb_web_headers() | Returns a new `twisted.web.http_headers.Headers` instance
populated with tags to mimic Tor Browser. These include values for
`User-Agent`, `Accept`, `Accept-Language` and `Accept-Encoding`. | 1.531893 | 1.407304 | 1.08853 |
parts = re.match(
r'^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+).*$',
version_string,
)
for ver, gold in zip(parts.group(1, 2, 3, 4), (major, minor, micro, patch)):
if int(ver) < int(gold):
return False
elif int(ver) > int(gold):
return True
return True | def version_at_least(version_string, major, minor, micro, patch) | This returns True if the version_string represents a Tor version
of at least ``major``.``minor``.``micro``.``patch`` version,
ignoring any trailing specifiers. | 2.200814 | 2.307952 | 0.953578 |
# Try to find the tor executable using the shell
if system_tor:
try:
proc = subprocess.Popen(
('which tor'),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True
)
except OSError:
pass
else:
stdout, _ = proc.communicate()
if proc.poll() == 0 and stdout != '':
return stdout.strip()
# the shell may not provide type and tor is usually not on PATH when using
# the browser-bundle. Look in specific places
for pattern in globs:
for path in glob.glob(pattern):
torbin = os.path.join(path, 'tor')
if is_executable(torbin):
return torbin
return None | def find_tor_binary(globs=('/usr/sbin/', '/usr/bin/',
'/Applications/TorBrowser_*.app/Contents/MacOS/'),
system_tor=True) | Tries to find the tor executable using the shell first or in in the
paths whose glob-patterns is in the given 'globs'-tuple.
:param globs:
A tuple of shell-style globs of directories to use to find tor
(TODO consider making that globs to actual tor binary?)
:param system_tor:
This controls whether bash is used to seach for 'tor' or
not. If False, we skip that check and use only the 'globs'
tuple. | 4.179967 | 4.128815 | 1.012389 |
if six.PY2 and isinstance(addr, str):
addr = unicode(addr) # noqa
try:
return ipaddress.ip_address(addr)
except ValueError:
pass
return str(addr) | def maybe_ip_addr(addr) | Tries to return an IPAddress, otherwise returns a string.
TODO consider explicitly checking for .exit or .onion at the end? | 3.855436 | 3.293314 | 1.170686 |
filtered = [x for x in args if '=' in x and key_filter(x.split('=')[0])]
return dict(x.split('=', 1) for x in filtered) | def find_keywords(args, key_filter=lambda x: not x.startswith("$")) | This splits up strings like name=value, foo=bar into a dict. Does NOT deal
with quotes in value (e.g. key="value with space" will not work
By default, note that it takes OUT any key which starts with $ (i.e. a
single dollar sign) since for many use-cases the way Tor encodes nodes
with "$hash=name" looks like a keyword argument (but it isn't). If you
don't want this, override the "key_filter" argument to this method.
:param args: a list of strings, each with one key=value pair
:return:
a dict of key->value (both strings) of all name=value type
keywords found in args. | 3.698527 | 4.859934 | 0.761024 |
for f in args:
try:
os.unlink(f)
except OSError:
shutil.rmtree(f, ignore_errors=True) | def delete_file_or_tree(*args) | For every path in args, try to delete it as a file or a directory
tree. Ignores deletion errors. | 2.940061 | 2.490108 | 1.180696 |
if addr is None:
return None
if "(tor_internal)" == str(addr).lower():
if torstate is None:
return None
return int(torstate.tor_pid)
proc = subprocess.Popen(['lsof', '-i', '4tcp@%s:%s' % (addr, port)],
stdout=subprocess.PIPE)
(stdout, stderr) = proc.communicate()
lines = stdout.split(b'\n')
if len(lines) > 1:
return int(lines[1].split()[1]) | def process_from_address(addr, port, torstate=None) | Determines the PID from the address/port provided by using lsof
and returns it as an int (or None if it couldn't be
determined). In the special case the addr is '(Tor_internal)' then
the PID of the Tor process (as gotten from the torstate object) is
returned (or 0 if unavailable, e.g. a Tor which doesn't implement
'GETINFO process/pid'). In this case if no TorState instance is
given, None is returned. | 3.790494 | 3.041004 | 1.246461 |
return hmac.new(key, msg, hashlib.sha256).digest() | def hmac_sha256(key, msg) | Adapted from rransom's tor-utils git repository. Returns the
digest (binary) of an HMAC with SHA256 over msg with key. | 3.414582 | 3.385348 | 1.008636 |
endpoint = serverFromString(reactor, 'tcp:0:interface=127.0.0.1')
port = yield endpoint.listen(NoOpProtocolFactory())
address = port.getHost()
yield port.stopListening()
defer.returnValue(address.port) | def available_tcp_port(reactor) | Returns a Deferred firing an available TCP port on localhost.
It does so by listening on port 0; then stopListening and fires the
assigned port number. | 3.399811 | 3.212059 | 1.058452 |
r'''
This function implementes the recommended functionality described in the
tor control-spec to be compatible with older tor versions:
* Read \\n \\t \\r and \\0 ... \\377 as C escapes.
* Treat a backslash followed by any other character as that character.
Except the legacy support for the escape sequences above this function
implements parsing of QuotedString using qcontent from
QuotedString = DQUOTE *qcontent DQUOTE
:param string: The escaped quoted string.
:returns: The unescaped string.
:raises ValueError: If the string is in a invalid form
(e.g. a single backslash)
'''
match = re.match(r'''^"((?:[^"\\]|\\.)*)"$''', string)
if not match:
raise ValueError("Invalid quoted string", string)
string = match.group(1)
# remove backslash before all characters which should not be
# handeled as escape codes by string.decode('string-escape').
# This is needed so e.g. '\x00' is not unescaped as '\0'
string = re.sub(r'((?:^|[^\\])(?:\\\\)*)\\([^ntr0-7\\])', r'\1\2', string)
if six.PY3:
# XXX hmmm?
return bytes(string, 'ascii').decode('unicode-escape')
return string.decode('string-escape') | def unescape_quoted_string(string) | r'''
This function implementes the recommended functionality described in the
tor control-spec to be compatible with older tor versions:
* Read \\n \\t \\r and \\0 ... \\377 as C escapes.
* Treat a backslash followed by any other character as that character.
Except the legacy support for the escape sequences above this function
implements parsing of QuotedString using qcontent from
QuotedString = DQUOTE *qcontent DQUOTE
:param string: The escaped quoted string.
:returns: The unescaped string.
:raises ValueError: If the string is in a invalid form
(e.g. a single backslash) | 7.598992 | 2.509614 | 3.027953 |
if six.PY3 and asyncio.iscoroutine(obj):
return defer.ensureDeferred(obj)
return obj | def maybe_coroutine(obj) | If 'obj' is a coroutine and we're using Python3, wrap it in
ensureDeferred. Otherwise return the original object.
(This is to insert in all callback chains from user code, in case
that user code is Python3 and used 'async def') | 4.411614 | 4.862141 | 0.90734 |
# for numeric hostnames, skip RFC1918 addresses, since no Tor exit
# node will be able to reach those. Likewise ignore IPv6 addresses.
try:
a = ipaddress.ip_address(six.text_type(host))
except ValueError:
return False # non-numeric, let Tor try it
if a.is_loopback or a.is_multicast or a.is_private or a.is_reserved \
or a.is_unspecified:
return True # too weird, don't connect
return False | def _is_non_public_numeric_address(host) | returns True if 'host' is not public | 5.635384 | 5.320588 | 1.059166 |
if not isabs(hsdir):
abs_hsdir = abspath(hsdir)
warnings.warn(
"Onions service directory ({}) is relative and has"
" been resolved to '{}'".format(hsdir, abs_hsdir)
)
hsdir = abs_hsdir
return hsdir | def _canonical_hsdir(hsdir) | Internal helper.
:return: the absolute path for 'hsdir' (and issue a warning)
issuing a warning) if it was relative. Otherwise, returns the path
unmodified. | 4.6435 | 4.587369 | 1.012236 |
# For v3 services, Tor attempts to upload to 16 services; we'll
# assume that for now but also cap it (we want to show some
# progress for "attempting uploads" but we need to decide how
# much) .. so we leave 50% of the "progress" for attempts, and the
# other 50% for "are we done" (which is either "one thing
# uploaded" or "all the things uploaded")
attempted_uploads = set()
confirmed_uploads = set()
failed_uploads = set()
uploaded = defer.Deferred()
await_all = False if await_all_uploads is None else await_all_uploads
def translate_progress(tag, description):
if progress:
done = len(confirmed_uploads) + len(failed_uploads)
done_endpoint = float(len(attempted_uploads)) if await_all else 1.0
done_pct = 0 if not attempted_uploads else float(done) / done_endpoint
started_pct = float(min(16, len(attempted_uploads))) / 16.0
try:
progress(
(done_pct * 50.0) + (started_pct * 50.0),
tag,
description,
)
except Exception:
log.err()
def hostname_matches(hostname):
if IAuthenticatedOnionClients.providedBy(onion):
return hostname[:-6] == onion.get_permanent_id()
else:
# provides IOnionService
return onion.hostname == hostname
def hs_desc(evt):
args = evt.split()
subtype = args[0]
if subtype == 'UPLOAD':
if hostname_matches('{}.onion'.format(args[1])):
attempted_uploads.add(args[3])
translate_progress(
"wait_descriptor",
"Upload to {} started".format(args[3])
)
elif subtype == 'UPLOADED':
# we only need ONE successful upload to happen for the
# HS to be reachable.
# unused? addr = args[1]
# XXX FIXME I think tor is sending the onion-address
# properly with these now, so we can use those
# (i.e. instead of matching to "attempted_uploads")
if args[3] in attempted_uploads:
confirmed_uploads.add(args[3])
log.msg("Uploaded '{}' to '{}'".format(args[1], args[3]))
translate_progress(
"wait_descriptor",
"Successful upload to {}".format(args[3])
)
if not uploaded.called:
if await_all:
if (len(failed_uploads) + len(confirmed_uploads)) == len(attempted_uploads):
uploaded.callback(onion)
else:
uploaded.callback(onion)
elif subtype == 'FAILED':
if hostname_matches('{}.onion'.format(args[1])):
failed_uploads.add(args[3])
translate_progress(
"wait_descriptor",
"Failed upload to {}".format(args[3])
)
if failed_uploads == attempted_uploads:
msg = "Failed to upload '{}' to: {}".format(
args[1],
', '.join(failed_uploads),
)
uploaded.errback(RuntimeError(msg))
# the first 'yield' should be the add_event_listener so that a
# caller can do "d = _await_descriptor_upload()", then add the
# service.
yield tor_protocol.add_event_listener('HS_DESC', hs_desc)
yield uploaded
yield tor_protocol.remove_event_listener('HS_DESC', hs_desc)
# ensure we show "100%" at the end
if progress:
if await_all_uploads:
msg = "Completed descriptor uploads"
else:
msg = "At least one descriptor uploaded"
try:
progress(100.0, "wait_descriptor", msg)
except Exception:
log.err() | def _await_descriptor_upload(tor_protocol, onion, progress, await_all_uploads) | Internal helper.
:param tor_protocol: ITorControlProtocol instance
:param onion: IOnionService instance
:param progress: a progess callback, or None
:returns: a Deferred that fires once we've detected at least one
descriptor upload for the service (as detected by listening for
HS_DESC events) | 4.720786 | 4.636544 | 1.018169 |
pub = private_key.public_key()
p = pub.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.PKCS1
)
z = ''.join(p.decode('ascii').strip().split('\n')[1:-1])
b = base64.b64decode(z)
h1 = hashlib.new('sha1')
h1.update(b)
permanent_id = h1.digest()[:10]
return base64.b32encode(permanent_id).lower().decode('ascii') | def _compute_permanent_id(private_key) | Internal helper. Return an authenticated service's permanent ID
given an RSA private key object.
The permanent ID is the base32 encoding of the SHA1 hash of the
first 10 bytes (80 bits) of the public key. | 2.638765 | 2.443811 | 1.079775 |
if not isinstance(ports, (list, tuple)):
raise ValueError("'ports' must be a list of strings, ints or 2-tuples")
processed_ports = []
for port in ports:
if isinstance(port, (set, list, tuple)):
if len(port) != 2:
raise ValueError(
"'ports' must contain a single int or a 2-tuple of ints"
)
remote, local = port
try:
remote = int(remote)
except ValueError:
raise ValueError(
"'ports' has a tuple with a non-integer "
"component: {}".format(port)
)
try:
local = int(local)
except ValueError:
if local.startswith('unix:/'):
pass
else:
if ':' not in local:
raise ValueError(
"local port must be either an integer"
" or start with unix:/ or be an IP:port"
)
ip, port = local.split(':')
if not _is_non_public_numeric_address(ip):
log.msg(
"'{}' used as onion port doesn't appear to be a "
"local, numeric address".format(ip)
)
processed_ports.append(
"{} {}".format(remote, local)
)
else:
processed_ports.append(
"{} 127.0.0.1:{}".format(remote, local)
)
elif isinstance(port, (six.text_type, str)):
_validate_single_port_string(port)
processed_ports.append(port)
else:
try:
remote = int(port)
except (ValueError, TypeError):
raise ValueError(
"'ports' has a non-integer entry: {}".format(port)
)
local = yield available_tcp_port(reactor)
processed_ports.append(
"{} 127.0.0.1:{}".format(remote, local)
)
defer.returnValue(processed_ports) | def _validate_ports(reactor, ports) | Internal helper for Onion services. Validates an incoming list of
port mappings and returns a list of strings suitable for passing
to other onion-services functions.
Accepts 3 different ways of specifying ports:
- list of ints: each int is the public port, local port random
- list of 2-tuples of ints: (pubic, local) ports.
- list of strings like "80 127.0.0.1:1234"
This is async in case it needs to ask for a random, unallocated
local port. | 2.818781 | 2.715355 | 1.038089 |
if not isinstance(ports, (list, tuple)):
raise ValueError("'ports' must be a list of strings")
if any([not isinstance(x, (six.text_type, str)) for x in ports]):
raise ValueError("'ports' must be a list of strings")
for port in ports:
_validate_single_port_string(port) | def _validate_ports_low_level(ports) | Internal helper.
Validates the 'ports' argument to EphemeralOnionService or
EphemeralAuthenticatedOnionService returning None on success or
raising ValueError otherwise.
This only accepts the "list of strings" variants; some
higher-level APIs also allow lists of ints or lists of 2-tuples,
but those must be converted to strings before they get here. | 2.556824 | 2.53043 | 1.010431 |
if ' ' not in port or len(port.split(' ')) != 2:
raise ValueError(
"Port '{}' should have exactly one space in it".format(port)
)
(external, internal) = port.split(' ')
try:
external = int(external)
except ValueError:
raise ValueError(
"Port '{}' external port isn't an int".format(port)
)
if ':' not in internal:
raise ValueError(
"Port '{}' local address should be 'IP:port'".format(port)
)
if not internal.startswith('unix:'):
ip, localport = internal.split(':')
if ip != 'localhost' and not _is_non_public_numeric_address(ip):
raise ValueError(
"Port '{}' internal IP '{}' should be a local "
"address".format(port, ip)
) | def _validate_single_port_string(port) | Validate a single string specifying ports for Onion
services. These look like: "80 127.0.0.1:4321" | 3.353903 | 3.166285 | 1.059255 |
'''
This parses a hidden-service "client_keys" file, either stealth or
basic (they're the same, except "stealth" includes a
"client-key"). Returns a list of HiddenServiceClientAuth() instances.
Note that the key does NOT include the "----BEGIN ---" markers,
nor *any* embedded whitespace. It is *just* the key blob.
'''
def parse_error(data):
raise RuntimeError("Parse error at: " + data)
class ParserState(object):
def __init__(self):
self.keys = []
self.reset()
def reset(self):
self.name = None
self.cookie = None
self.key = []
def create_key(self):
if self.name is not None:
self.keys.append(HiddenServiceClientAuth(self.name, self.cookie, self.key))
self.reset()
def set_name(self, name):
self.create_key()
self.name = name.split()[1]
def set_cookie(self, cookie):
self.cookie = cookie.split()[1]
if self.cookie.endswith('=='):
self.cookie = self.cookie[:-2]
def add_key_line(self, line):
self.key.append(line)
from txtorcon.spaghetti import FSM, State, Transition
init = State('init')
got_name = State('got_name')
got_cookie = State('got_cookie')
reading_key = State('got_key')
parser_state = ParserState()
# initial state; we want "client-name" or it's an error
init.add_transitions([
Transition(got_name, lambda line: line.startswith('client-name '), parser_state.set_name),
Transition(init, lambda line: not line.startswith('client-name '), parse_error),
])
# next up is "descriptor-cookie" or it's an error
got_name.add_transitions([
Transition(got_cookie, lambda line: line.startswith('descriptor-cookie '), parser_state.set_cookie),
Transition(init, lambda line: not line.startswith('descriptor-cookie '), parse_error),
])
# the "interesting bit": there's either a client-name if we're a
# "basic" file, or an RSA key (with "client-key" before it)
got_cookie.add_transitions([
Transition(reading_key, lambda line: line.startswith('client-key'), None),
Transition(got_name, lambda line: line.startswith('client-name '), parser_state.set_name),
])
# if we're reading an RSA key, we accumulate it in current_key.key
# until we hit a line starting with "client-name"
reading_key.add_transitions([
Transition(reading_key, lambda line: not line.startswith('client-name'), parser_state.add_key_line),
Transition(got_name, lambda line: line.startswith('client-name '), parser_state.set_name),
])
# create our FSM and parse the data
fsm = FSM([init, got_name, got_cookie, reading_key])
for line in stream.readlines():
fsm.process(line.strip())
parser_state.create_key() # make sure we get the "last" one
return parser_state.keys | def _parse_client_keys(stream) | This parses a hidden-service "client_keys" file, either stealth or
basic (they're the same, except "stealth" includes a
"client-key"). Returns a list of HiddenServiceClientAuth() instances.
Note that the key does NOT include the "----BEGIN ---" markers,
nor *any* embedded whitespace. It is *just* the key blob. | 3.333452 | 2.430156 | 1.371703 |
if self.handler:
state = self.handler(data)
if state is None:
return self.next_state
return state
return self.next_state | def handle(self, data) | return next state. May override in a subclass to change
behavior or pass a handler method to ctor | 4.244932 | 3.300285 | 1.286232 |
if np.all(np.equal(start, end)):
return np.linalg.norm(point - start)
return np.divide(
np.abs(np.linalg.norm(np.cross(end - start, start - point))),
np.linalg.norm(end - start)) | def pldist(point, start, end) | Calculates the distance from ``point`` to the line given
by the points ``start`` and ``end``.
:param point: a point
:type point: numpy array
:param start: a point of the line
:type start: numpy array
:param end: another point of the line
:type end: numpy array | 2.73074 | 2.887876 | 0.945588 |
dmax = 0.0
index = -1
for i in xrange(1, M.shape[0]):
d = dist(M[i], M[0], M[-1])
if d > dmax:
index = i
dmax = d
if dmax > epsilon:
r1 = rdp_rec(M[:index + 1], epsilon, dist)
r2 = rdp_rec(M[index:], epsilon, dist)
return np.vstack((r1[:-1], r2))
else:
return np.vstack((M[0], M[-1])) | def rdp_rec(M, epsilon, dist=pldist) | Simplifies a given array of points.
Recursive version.
:param M: an array
:type M: numpy array
:param epsilon: epsilon in the rdp algorithm
:type epsilon: float
:param dist: distance function
:type dist: function with signature ``f(point, start, end)`` -- see :func:`rdp.pldist` | 2.124347 | 2.182583 | 0.973318 |
mask = _rdp_iter(M, 0, len(M) - 1, epsilon, dist)
if return_mask:
return mask
return M[mask] | def rdp_iter(M, epsilon, dist=pldist, return_mask=False) | Simplifies a given array of points.
Iterative version.
:param M: an array
:type M: numpy array
:param epsilon: epsilon in the rdp algorithm
:type epsilon: float
:param dist: distance function
:type dist: function with signature ``f(point, start, end)`` -- see :func:`rdp.pldist`
:param return_mask: return the mask of points to keep instead
:type return_mask: bool | 3.499678 | 6.211316 | 0.563436 |
if algo == "iter":
algo = partial(rdp_iter, return_mask=return_mask)
elif algo == "rec":
if return_mask:
raise NotImplementedError("return_mask=True not supported with algo=\"rec\"")
algo = rdp_rec
if "numpy" in str(type(M)):
return algo(M, epsilon, dist)
return algo(np.array(M), epsilon, dist).tolist() | def rdp(M, epsilon=0, dist=pldist, algo="iter", return_mask=False) | Simplifies a given array of points using the Ramer-Douglas-Peucker
algorithm.
Example:
>>> from rdp import rdp
>>> rdp([[1, 1], [2, 2], [3, 3], [4, 4]])
[[1, 1], [4, 4]]
This is a convenience wrapper around both :func:`rdp.rdp_iter`
and :func:`rdp.rdp_rec` that detects if the input is a numpy array
in order to adapt the output accordingly. This means that
when it is called using a Python list as argument, a Python
list is returned, and in case of an invocation using a numpy
array, a NumPy array is returned.
The parameter ``return_mask=True`` can be used in conjunction
with ``algo="iter"`` to return only the mask of points to keep. Example:
>>> from rdp import rdp
>>> import numpy as np
>>> arr = np.array([1, 1, 2, 2, 3, 3, 4, 4]).reshape(4, 2)
>>> arr
array([[1, 1],
[2, 2],
[3, 3],
[4, 4]])
>>> mask = rdp(arr, algo="iter", return_mask=True)
>>> mask
array([ True, False, False, True], dtype=bool)
>>> arr[mask]
array([[1, 1],
[4, 4]])
:param M: a series of points
:type M: numpy array with shape ``(n,d)`` where ``n`` is the number of points and ``d`` their dimension
:param epsilon: epsilon in the rdp algorithm
:type epsilon: float
:param dist: distance function
:type dist: function with signature ``f(point, start, end)`` -- see :func:`rdp.pldist`
:param algo: either ``iter`` for an iterative algorithm or ``rec`` for a recursive algorithm
:type algo: string
:param return_mask: return mask instead of simplified array
:type return_mask: bool | 3.137147 | 2.960275 | 1.059749 |
self.pause_scene()
self.start_scene(event.new_scene, event.kwargs) | def on_start_scene(self, event: StartScene, signal: Callable[[Any], None]) | Start a new scene. The current scene pauses. | 8.570734 | 4.720802 | 1.815525 |
self.stop_scene()
if self.current_scene is not None:
signal(events.SceneContinued())
else:
signal(events.Quit()) | def on_stop_scene(self, event: events.StopScene, signal: Callable[[Any], None]) | Stop a running scene. If there's a scene on the stack, it resumes. | 6.149772 | 4.50451 | 1.365248 |
self.stop_scene()
self.start_scene(event.new_scene, event.kwargs) | def on_replace_scene(self, event: events.ReplaceScene, signal) | Replace the running scene with a new one. | 6.109046 | 4.321386 | 1.413677 |
if not isinstance(event_type, type) and event_type is not ...:
raise TypeError(f"{type(self)}.register requires event_type to be a type.")
if not callable(callback):
raise TypeError(f"{type(self)}.register requires callback to be callable.")
self.event_extensions[event_type].append(callback) | def register(self, event_type: Union[Type, _ellipsis], callback: Callable[[], Any]) | Register a callback to be applied to an event at time of publishing.
Primarily to be used by subsystems.
The callback will receive the event. Your code should modify the event
in place. It does not need to return it.
:param event_type: The class of an event.
:param callback: A callable, must accept an event, and return no value.
:return: None | 2.84532 | 3.008426 | 0.945783 |
global _module_file_index
_module_file_index = {
mod.__file__: mod.__name__
for mod in sys.modules.values()
if hasattr(mod, '__file__') and hasattr(mod, '__name__')
} | def _build_index() | Rebuild _module_file_index from sys.modules | 2.999778 | 2.016398 | 1.487691 |
# This is internal/CPython only/etc
# It's also astonishingly faster than alternatives.
frame = sys._getframe(1)
file_name = frame.f_code.co_filename
module_name = _get_module(file_name)
return logging.getLogger(module_name) | def logger(self) | The logger for this class. | 9.652356 | 8.730625 | 1.105574 |
if not self._pause_level:
self._paused_time = self._clock() + self._offset
self._paused_frame = self.current_frame
self._pause_level += 1 | def pause(self) | Pause the animation. | 6.286294 | 5.782506 | 1.087123 |
self._pause_level -= 1
if not self._pause_level:
self._offset = self._paused_time - self._clock() | def unpause(self) | Unpause the animation. | 8.095014 | 7.577514 | 1.068294 |
if not self._pause_level:
return (
int((self._clock() + self._offset) * self.frames_per_second)
% len(self._frames)
)
else:
return self._paused_frame | def current_frame(self) | Compute the number of the current frame (0-indexed) | 5.774603 | 5.334354 | 1.082531 |
logging.basicConfig(level=log_level)
kwargs = {
"resolution": (800, 600),
"scene_kwargs": {
"set_up": setup,
}
}
with GameEngine(starting_scene, **kwargs) as eng:
eng.run() | def run(setup: Callable[[BaseScene], None]=None, *, log_level=logging.WARNING,
starting_scene=BaseScene) | Run a small game.
The resolution will 800 pixels wide by 600 pixels tall.
setup is a callable that accepts a scene and returns None.
log_level let's you set the expected log level. Consider logging.DEBUG if
something is behaving oddly.
starting_scene let's you change the scene used by the engine. | 3.75048 | 4.156091 | 0.902406 |
if isinstance(tags, (str, bytes)):
raise TypeError("You passed a string instead of an iterable, this probably isn't what you intended.\n\nTry making it a tuple.")
self.all.add(game_object)
for kind in type(game_object).mro():
self.kinds[kind].add(game_object)
for tag in tags:
self.tags[tag].add(game_object) | def add(self, game_object: Hashable, tags: Iterable[Hashable]=()) -> None | Add a game_object to the container.
game_object: Any Hashable object. The item to be added.
tags: An iterable of Hashable objects. Values that can be used to
retrieve a group containing the game_object.
Examples:
container.add(MyObject())
container.add(MyObject(), tags=("red", "blue") | 4.63735 | 5.345897 | 0.86746 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.