当前位置: 首页>>代码示例>>Python>>正文


Python torTools.getConn函数代码示例

本文整理汇总了Python中util.torTools.getConn函数的典型用法代码示例。如果您正苦于以下问题:Python getConn函数的具体用法?Python getConn怎么用?Python getConn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了getConn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

 def __init__(self):
   """
   Initializes parameters needed to present a graph.
   """
   
   # panel to be redrawn when updated (set when added to GraphPanel)
   self._graphPanel = None
   self.isSelected = False
   self.isPauseBuffer = False
   
   # tracked stats
   self.tick = 0                                 # number of processed events
   self.lastPrimary, self.lastSecondary = 0, 0   # most recent registered stats
   self.primaryTotal, self.secondaryTotal = 0, 0 # sum of all stats seen
   
   # timescale dependent stats
   self.maxCol = CONFIG["features.graph.maxWidth"]
   self.maxPrimary, self.maxSecondary = {}, {}
   self.primaryCounts, self.secondaryCounts = {}, {}
   
   for i in range(len(UPDATE_INTERVALS)):
     # recent rates for graph
     self.maxPrimary[i] = 0
     self.maxSecondary[i] = 0
     
     # historic stats for graph, first is accumulator
     # iterative insert needed to avoid making shallow copies (nasty, nasty gotcha)
     self.primaryCounts[i] = (self.maxCol + 1) * [0]
     self.secondaryCounts[i] = (self.maxCol + 1) * [0]
   
   # tracks BW events
   torTools.getConn().addEventListener(self.bandwidth_event, stem.control.EventType.BW)
开发者ID:refnode,项目名称:arm,代码行数:32,代码来源:graphPanel.py

示例2: quit

    def quit(self):
        """
    Terminates arm after the input is processed. Optionally if we're connected
    to a arm generated tor instance then this may check if that should be shut
    down too.
    """

        self._isDone = True

        # check if the torrc has a "ARM_SHUTDOWN" comment flag, if so then shut
        # down the instance

        isShutdownFlagPresent = False
        torrcContents = torConfig.getTorrc().getContents()

        if torrcContents:
            for line in torrcContents:
                if "# ARM_SHUTDOWN" in line:
                    isShutdownFlagPresent = True
                    break

        if isShutdownFlagPresent:
            try:
                torTools.getConn().shutdown()
            except IOError, exc:
                cli.popups.showMsg(str(exc), 3, curses.A_BOLD)
开发者ID:gsathya,项目名称:arm,代码行数:26,代码来源:controller.py

示例3: shutdownDaemons

def shutdownDaemons():
    """
  Stops and joins on worker threads.
  """

    # prevents further worker threads from being spawned
    torTools.NO_SPAWN = True

    # stops panel daemons
    control = getController()
    for panelImpl in control.getDaemonPanels():
        panelImpl.stop()
    for panelImpl in control.getDaemonPanels():
        panelImpl.join()

    # joins on stem threads
    torTools.getConn().close()

    # joins on utility daemon threads - this might take a moment since the
    # internal threadpools being joined might be sleeping
    hostnames.stop()
    resourceTrackers = sysTools.RESOURCE_TRACKERS.values()
    resolver = connections.getResolver("tor") if connections.isResolverAlive("tor") else None
    for tracker in resourceTrackers:
        tracker.stop()
    if resolver:
        resolver.stop()  # sets halt flag (returning immediately)
    for tracker in resourceTrackers:
        tracker.join()
    if resolver:
        resolver.join()  # joins on halted resolver
开发者ID:gsathya,项目名称:arm,代码行数:31,代码来源:controller.py

示例4: __init__

 def __init__(self):
   self.backlog = []   # prior requests the user has made
   self.contents = []  # (msg, format list) tuples for what's been displayed
   self.writePath = DEFAULT_WRITE_PATH # last location we've saved to
   self.eventBuffer = [] # unread event messages
   self.loggedEvents = [] # event types that we're listening for
   
   torTools.getConn().addEventListener(TorEventObserver(self.registerEvent))
开发者ID:JustMe23,项目名称:arm,代码行数:8,代码来源:torInterpretor.py

示例5: isExitsAllowed

 def isExitsAllowed(self):
   """
   True if exit connections are permissable, false otherwise.
   """
   
   if not torTools.getConn().getOption("ORPort", None):
     return False # no ORPort
   
   policy = torTools.getConn().getExitPolicy()
   return policy and policy.is_exiting_allowed()
开发者ID:gsathya,项目名称:arm,代码行数:10,代码来源:connPanel.py

示例6: sendNewnym

 def sendNewnym(self):
   """
   Requests a new identity and provides a visual queue.
   """
   
   torTools.getConn().sendNewnym()
   
   # If we're wide then the newnym label in this panel will give an
   # indication that the signal was sent. Otherwise use a msg.
   isWide = self.getParent().getmaxyx()[1] >= MIN_DUAL_COL_WIDTH
   if not isWide: cli.popups.showMsg("Requesting a new identity", 1)
开发者ID:twilde,项目名称:arm,代码行数:11,代码来源:headerPanel.py

示例7: resetOptions

 def resetOptions(self):
   self.familyResolutions = {}
   self.familyFingerprints = {}
   
   try:
     self.address = "" # fetched when needed if unset
     self.nickname = self.conn.get_option("Nickname")[0][1]
     if self.nickname == None: self.nickname = "Unnamed"
     
     self.orPort = self.conn.get_option("ORPort")[0][1]
     self.dirPort = self.conn.get_option("DirPort")[0][1]
     self.controlPort = self.conn.get_option("ControlPort")[0][1]
     
     # uses ports to identify type of connections (ORListenAddress port overwrites ORPort if set)
     listenAddr = self.conn.get_option("ORListenAddress")[0][1]
     if listenAddr and ":" in listenAddr:
       self.listenPort = listenAddr[listenAddr.find(":") + 1:]
     else: self.listenPort = self.orPort
     
     self.socksPort = torTools.getConn().getOption("SocksPort", "0")
     
     # entry is None if not set, otherwise of the format "$<fingerprint>,$<fingerprint>"
     familyEntry = self.conn.get_option("MyFamily")[0][1]
     if familyEntry: self.family = familyEntry.split(",")
     else: self.family = []
     
     self.isBridge = self.conn.get_option("BridgeRelay")[0][1] == "1"
     
     policyEntries = torTools.getConn().getOption("ExitPolicy", multiple=True)
     if not policyEntries: policyEntries = [] # if ExitPolicy is undefined, policyEntries is None
     self.exitPolicy = ",".join(policyEntries)
     self.exitPolicy = self.exitPolicy.replace("\\t", " ").replace("\"", "")
     
     if self.exitPolicy: self.exitPolicy += "," + self.conn.get_info("exit-policy/default")["exit-policy/default"]
     else: self.exitPolicy = self.conn.get_info("exit-policy/default")["exit-policy/default"]
     
     self.exitRejectPrivate = self.conn.get_option("ExitPolicyRejectPrivate")[0][1] == "1"
     
     self._resolveFamilyEntries()
   except (socket.error, TorCtl.ErrorReply, TorCtl.TorCtlClosed):
     self.nickname = ""
     self.listenPort = None
     self.orPort = "0"
     self.dirPort = "0"
     self.controlPort = "0"
     self.socksPort = "0"
     self.family = []
     self.isBridge = False
     self.exitPolicy = ""
     self.exitRejectPrivate = True
开发者ID:katmagic,项目名称:arm,代码行数:50,代码来源:connPanel.py

示例8: makeActionsMenu

def makeActionsMenu():
  """
  Submenu consisting of...
    Close Menu
    New Identity
    Pause / Unpause
    Reset Tor
    Exit
  """
  
  control = cli.controller.getController()
  conn = torTools.getConn()
  headerPanel = control.getPanel("header")
  actionsMenu = cli.menu.item.Submenu("Actions")
  actionsMenu.add(cli.menu.item.MenuItem("Close Menu", None))
  actionsMenu.add(cli.menu.item.MenuItem("New Identity", headerPanel.sendNewnym))
  
  if conn.isAlive():
    actionsMenu.add(cli.menu.item.MenuItem("Stop Tor", conn.shutdown))
  
  actionsMenu.add(cli.menu.item.MenuItem("Reset Tor", conn.reload))
  
  if control.isPaused(): label, arg = "Unpause", False
  else: label, arg = "Pause", True
  actionsMenu.add(cli.menu.item.MenuItem(label, functools.partial(control.setPaused, arg)))
  
  actionsMenu.add(cli.menu.item.MenuItem("Exit", control.quit))
  return actionsMenu
开发者ID:gsathya,项目名称:arm,代码行数:28,代码来源:actions.py

示例9: update

 def update(self, status, path):
   """
   Our status and path can change over time if the circuit is still in the
   process of being built. Updates these attributes of our relay.
   
   Arguments:
     status - new status of the circuit
     path   - list of fingerprints for the series of relays involved in the
              circuit
   """
   
   self.status = status
   self.lines = [self.lines[0]]
   conn = torTools.getConn()
   
   if status == "BUILT" and not self.lines[0].isBuilt:
     exitIp, exitORPort = conn.getRelayAddress(path[-1], ("192.168.0.1", "0"))
     self.lines[0].setExit(exitIp, exitORPort, path[-1])
   
   for i in range(len(path)):
     relayFingerprint = path[i]
     relayIp, relayOrPort = conn.getRelayAddress(relayFingerprint, ("192.168.0.1", "0"))
     
     if i == len(path) - 1:
       if status == "BUILT": placementType = "Exit"
       else: placementType = "Extending"
     elif i == 0: placementType = "Guard"
     else: placementType = "Middle"
     
     placementLabel = "%i / %s" % (i + 1, placementType)
     
     self.lines.append(CircLine(relayIp, relayOrPort, relayFingerprint, placementLabel))
   
   self.lines[-1].isLast = True
开发者ID:JustMe23,项目名称:arm,代码行数:34,代码来源:circEntry.py

示例10: setEventListening

 def setEventListening(self, events):
   """
   Configures the events Tor listens for, filtering non-tor events from what we
   request from the controller. This returns a sorted list of the events we
   successfully set.
   
   Arguments:
     events - event types to attempt to set
   """
   
   events = set(events) # drops duplicates
   torEvents = events.intersection(set(TOR_EVENT_TYPES.values()))
   
   # adds events unrecognized by arm if we're listening to the 'UNKNOWN' type
   if "UNKNOWN" in events:
     torEvents.update(set(getMissingEventTypes()))
   
   torConn = torTools.getConn()
   torConn.removeEventListener(self.registerTorEvent)
   
   for eventType in list(torEvents):
     try:
       torConn.addEventListener(self.registerTorEvent, eventType)
     except stem.ProtocolError:
       torEvents.remove(eventType)
   
   # provides back the input set minus events we failed to set
   return sorted(torEvents)
开发者ID:refnode,项目名称:arm,代码行数:28,代码来源:logPanel.py

示例11: saveOptionDescriptions

def saveOptionDescriptions(path):
  """
  Preserves the current configuration descriptors to the given path. This
  raises an IOError if unable to do so.
  
  Arguments:
    path - location to persist configuration descriptors
  """
  
  # make dir if the path doesn't already exist
  baseDir = os.path.dirname(path)
  if not os.path.exists(baseDir): os.makedirs(baseDir)
  outputFile = open(path, "w")
  
  CONFIG_DESCRIPTIONS_LOCK.acquire()
  sortedOptions = CONFIG_DESCRIPTIONS.keys()
  sortedOptions.sort()
  
  torVersion = torTools.getConn().getInfo("version", "")
  outputFile.write("Tor Version %s\n" % torVersion)
  for i in range(len(sortedOptions)):
    option = sortedOptions[i]
    manEntry = getConfigDescription(option)
    outputFile.write("%s\nindex: %i\n%s\n%s\n%s\n" % (OPTION_CATEGORY_STR[manEntry.category], manEntry.index, option, manEntry.argUsage, manEntry.description))
    if i != len(sortedOptions) - 1: outputFile.write(PERSIST_ENTRY_DIVIDER)
  
  outputFile.close()
  CONFIG_DESCRIPTIONS_LOCK.release()
开发者ID:katmagic,项目名称:arm,代码行数:28,代码来源:torConfig.py

示例12: getConfigLocation

def getConfigLocation():
  """
  Provides the location of the torrc, raising an IOError with the reason if the
  path can't be determined.
  """
  
  conn = torTools.getConn()
  configLocation = conn.getInfo("config-file")
  if not configLocation: raise IOError("unable to query the torrc location")
  
  # checks if this is a relative path, needing the tor pwd to be appended
  if configLocation[0] != "/":
    torPid = conn.getMyPid()
    failureMsg = "querying tor's pwd failed because %s"
    if not torPid: raise IOError(failureMsg % "we couldn't get the pid")
    
    try:
      # pwdx results are of the form:
      # 3799: /home/atagar
      # 5839: No such process
      results = sysTools.call("pwdx %s" % torPid)
      if not results:
        raise IOError(failureMsg % "pwdx didn't return any results")
      elif results[0].endswith("No such process"):
        raise IOError(failureMsg % ("pwdx reported no process for pid " + torPid))
      elif len(results) != 1 or results.count(" ") != 1:
        raise IOError(failureMsg % "we got unexpected output from pwdx")
      else:
        pwdPath = results[0][results[0].find(" ") + 1:]
        configLocation = "%s/%s" % (pwdPath, configLocation)
    except IOError, exc:
      raise IOError(failureMsg % ("the pwdx call failed: " + str(exc)))
开发者ID:katmagic,项目名称:arm,代码行数:32,代码来源:torConfig.py

示例13: __init__

 def __init__(self, lIpAddr, lPort, fIpAddr, fPort, includePort=True, includeExpandedIpAddr=True):
   entries.ConnectionPanelLine.__init__(self)
   
   self.local = Endpoint(lIpAddr, lPort)
   self.foreign = Endpoint(fIpAddr, fPort)
   self.startTime = time.time()
   self.isInitialConnection = False
   
   # overwrite the local fingerprint with ours
   conn = torTools.getConn()
   self.local.fingerprintOverwrite = conn.getInfo("fingerprint", None)
   
   # True if the connection has matched the properties of a client/directory
   # connection every time we've checked. The criteria we check is...
   #   client    - first hop in an established circuit
   #   directory - matches an established single-hop circuit (probably a
   #               directory mirror)
   
   self._possibleClient = True
   self._possibleDirectory = True
   
   # attributes for SOCKS, HIDDEN, and CONTROL connections
   self.appName = None
   self.appPid = None
   self.isAppResolving = False
   
   myOrPort = conn.getOption("ORPort", None)
   myDirPort = conn.getOption("DirPort", None)
   mySocksPort = conn.getOption("SocksPort", "9050")
   myCtlPort = conn.getOption("ControlPort", None)
   myHiddenServicePorts = conn.getHiddenServicePorts()
   
   # the ORListenAddress can overwrite the ORPort
   listenAddr = conn.getOption("ORListenAddress", None)
   if listenAddr and ":" in listenAddr:
     myOrPort = listenAddr[listenAddr.find(":") + 1:]
   
   if lPort in (myOrPort, myDirPort):
     self.baseType = Category.INBOUND
     self.local.isNotORPort = False
   elif lPort == mySocksPort:
     self.baseType = Category.SOCKS
   elif fPort in myHiddenServicePorts:
     self.baseType = Category.HIDDEN
   elif lPort == myCtlPort:
     self.baseType = Category.CONTROL
   else:
     self.baseType = Category.OUTBOUND
     self.foreign.isNotORPort = False
   
   self.cachedType = None
   
   # includes the port or expanded ip address field when displaying listing
   # information if true
   self.includePort = includePort
   self.includeExpandedIpAddr = includeExpandedIpAddr
   
   # cached immutable values used for sorting
   self.sortIpAddr = connections.ipToInt(self.foreign.getIpAddr())
   self.sortPort = int(self.foreign.getPort())
开发者ID:refnode,项目名称:arm,代码行数:60,代码来源:connEntry.py

示例14: isPrivate

 def isPrivate(self):
   """
   Returns true if the endpoint is private, possibly belonging to a client
   connection or exit traffic.
   """
   
   if not CONFIG["features.connection.showIps"]: return True
   
   # This is used to scrub private information from the interface. Relaying
   # etiquette (and wiretapping laws) say these are bad things to look at so
   # DON'T CHANGE THIS UNLESS YOU HAVE A DAMN GOOD REASON!
   
   myType = self.getType()
   
   if myType == Category.INBOUND:
     # if we're a guard or bridge and the connection doesn't belong to a
     # known relay then it might be client traffic
     
     conn = torTools.getConn()
     if "Guard" in conn.getMyFlags([]) or conn.getOption("BridgeRelay", None) == "1":
       allMatches = conn.getRelayFingerprint(self.foreign.getIpAddr(), getAllMatches = True)
       return allMatches == []
   elif myType == Category.EXIT:
     # DNS connections exiting us aren't private (since they're hitting our
     # resolvers). Everything else, however, is.
     
     # TODO: Ideally this would also double check that it's a UDP connection
     # (since DNS is the only UDP connections Tor will relay), however this
     # will take a bit more work to propagate the information up from the
     # connection resolver.
     return self.foreign.getPort() != "53"
   
   # for everything else this isn't a concern
   return False
开发者ID:refnode,项目名称:arm,代码行数:34,代码来源:connEntry.py

示例15: __init__

 def __init__(self, stdscr, configType, config=None):
   panel.Panel.__init__(self, stdscr, "configuration", 0)
   
   self.sortOrdering = DEFAULT_SORT_ORDER
   self._config = dict(DEFAULT_CONFIG)
   if config:
     config.update(self._config, {
       "features.config.selectionDetails.height": 0,
       "features.config.state.colWidth.option": 5,
       "features.config.state.colWidth.value": 5})
     
     sortFields = Field.values()
     customOrdering = config.getIntCSV("features.config.order", None, 3, 0, len(sortFields))
     
     if customOrdering:
       self.sortOrdering = [sortFields[i] for i in customOrdering]
   
   self.configType = configType
   self.confContents = []
   self.confImportantContents = []
   self.scroller = uiTools.Scroller(True)
   self.valsLock = threading.RLock()
   
   # shows all configuration options if true, otherwise only the ones with
   # the 'important' flag are shown
   self.showAll = False
   
   # initializes config contents if we're connected
   conn = torTools.getConn()
   conn.addStatusListener(self.resetListener)
   if conn.isAlive(): self.resetListener(conn, torTools.State.INIT)
开发者ID:JustMe23,项目名称:arm,代码行数:31,代码来源:configPanel.py


注:本文中的util.torTools.getConn函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。