# -*-mode: python; py-indent-offset: 2; indent-tabs-mode: nil; coding: utf-8-unix -*-

# http://vt5hknv6sblkgf22.onion/tutorials/examples/list_circuits.html

import sys
import os
import getpass
from stem import CircStatus
from stem.control import Controller

# port(port = 9051)
if os.path.exists('/var/run/tor/control'):
    controller = Controller.from_socket_file(path='/var/run/tor/control')
else:
    controller = Controller.from_port(port=9051)
try:
    sys.stdout.flush()
    p = getpass.unix_getpass(prompt='Controller Password: ', stream=sys.stderr)
    controller.authenticate(p)

    for circ in sorted(controller.get_circuits()):
      if circ.status != CircStatus.BUILT:
        continue

      print("")
      print("Circuit %s (%s)" % (circ.id, circ.purpose))

      for i, entry in enumerate(circ.path):
        div = '+' if (i == len(circ.path) - 1) else '|'
        fingerprint, nickname = entry

        desc = controller.get_network_status(fingerprint, None)
        address = desc.address if desc else 'unknown'

        print(" %s- %s (%s, %s)" % (div, fingerprint, nickname, address))

except Exception as e:
    print(e)
finally:
    del controller

