Example #1
0
  def test_get_short_time_label(self):
    """
    Checks the get_short_time_label() function.
    """

    # test the pydoc examples
    self.assertEquals('01:51', str_tools.get_short_time_label(111))
    self.assertEquals('6-07:08:20', str_tools.get_short_time_label(544100))

    self.assertEquals('00:00', str_tools.get_short_time_label(0))

    self.assertRaises(TypeError, str_tools.get_short_time_label, None)
    self.assertRaises(TypeError, str_tools.get_short_time_label, 'hello world')
    self.assertRaises(ValueError, str_tools.get_short_time_label, -5)
Example #2
0
  def test_get_short_time_label(self):
    """
    Checks the get_short_time_label() function.
    """

    # test the pydoc examples
    self.assertEquals('01:51', str_tools.get_short_time_label(111))
    self.assertEquals('6-07:08:20', str_tools.get_short_time_label(544100))

    self.assertEquals('00:00', str_tools.get_short_time_label(0))

    self.assertRaises(TypeError, str_tools.get_short_time_label, None)
    self.assertRaises(TypeError, str_tools.get_short_time_label, 'hello world')
    self.assertRaises(ValueError, str_tools.get_short_time_label, -5)
Example #3
0
    def draw(self, width, height):
        self.valsLock.acquire()
        isWide = width + 1 >= MIN_DUAL_COL_WIDTH

        # space available for content
        if isWide:
            leftWidth = max(width / 2, 77)
            rightWidth = width - leftWidth
        else:
            leftWidth = rightWidth = width

        # Line 1 / Line 1 Left (system and tor version information)
        sysNameLabel = "arm - %s" % self.vals["sys/hostname"]
        contentSpace = min(leftWidth, 40)

        if len(sysNameLabel) + 10 <= contentSpace:
            sysTypeLabel = "%s %s" % (self.vals["sys/os"],
                                      self.vals["sys/version"])
            sysTypeLabel = uiTools.cropStr(
                sysTypeLabel, contentSpace - len(sysNameLabel) - 3, 4)
            self.addstr(0, 0, "%s (%s)" % (sysNameLabel, sysTypeLabel))
        else:
            self.addstr(0, 0, uiTools.cropStr(sysNameLabel, contentSpace))

        contentSpace = leftWidth - 43
        if 7 + len(self.vals["tor/version"]) + len(
                self.vals["tor/versionStatus"]) <= contentSpace:
            if self.vals["tor/version"] != "Unknown":
                versionColor = VERSION_STATUS_COLORS[self.vals["tor/versionStatus"]] if \
                    self.vals["tor/versionStatus"] in VERSION_STATUS_COLORS else "white"
                labelPrefix = "Tor %s (" % self.vals["tor/version"]
                self.addstr(0, 43, labelPrefix)
                self.addstr(0, 43 + len(labelPrefix),
                            self.vals["tor/versionStatus"],
                            uiTools.getColor(versionColor))
                self.addstr(
                    0, 43 + len(labelPrefix) +
                    len(self.vals["tor/versionStatus"]), ")")
        elif 11 <= contentSpace:
            self.addstr(
                0, 43,
                uiTools.cropStr("Tor %s" % self.vals["tor/version"],
                                contentSpace, 4))

        # Line 2 / Line 2 Left (tor ip/port information)
        x, includeControlPort = 0, True
        if self.vals["tor/orPort"]:
            myAddress = "Unknown"
            if self.vals["tor/orListenAddr"]:
                myAddress = self.vals["tor/orListenAddr"]
            elif self.vals["tor/address"]:
                myAddress = self.vals["tor/address"]

            # acting as a relay (we can assume certain parameters are set
            dirPortLabel = ", Dir Port: %s" % self.vals[
                "tor/dirPort"] if self.vals["tor/dirPort"] != "0" else ""
            for label in (self.vals["tor/nickname"], " - " + myAddress,
                          ":" + self.vals["tor/orPort"], dirPortLabel):
                if x + len(label) <= leftWidth:
                    self.addstr(1, x, label)
                    x += len(label)
                else:
                    break
        else:
            # non-relay (client only)
            if self._isTorConnected:
                self.addstr(1, x, "Relaying Disabled",
                            uiTools.getColor("cyan"))
                x += 17
            else:
                statusTime = torTools.getConn().getHeartbeat()

                if statusTime:
                    statusTimeLabel = time.strftime("%H:%M %m/%d/%Y, ",
                                                    time.localtime(statusTime))
                else:
                    statusTimeLabel = ""  # never connected to tor

                self.addstr(1, x, "Tor Disconnected",
                            curses.A_BOLD | uiTools.getColor("red"))
                self.addstr(1, x + 16,
                            " (%spress r to reconnect)" % statusTimeLabel)
                x += 39 + len(statusTimeLabel)
                includeControlPort = False

        if includeControlPort:
            if self.vals["tor/controlPort"] == "0":
                # connected via a control socket
                self.addstr(
                    1, x, ", Control Socket: %s" % self.vals["tor/socketPath"])
            else:
                if self.vals["tor/isAuthPassword"]: authType = "password"
                elif self.vals["tor/isAuthCookie"]: authType = "cookie"
                else: authType = "open"

                if x + 19 + len(self.vals["tor/controlPort"]) + len(
                        authType) <= leftWidth:
                    authColor = "red" if authType == "open" else "green"
                    self.addstr(1, x, ", Control Port (")
                    self.addstr(1, x + 16, authType,
                                uiTools.getColor(authColor))
                    self.addstr(1, x + 16 + len(authType),
                                "): %s" % self.vals["tor/controlPort"])
                elif x + 16 + len(self.vals["tor/controlPort"]) <= leftWidth:
                    self.addstr(
                        1, 0,
                        ", Control Port: %s" % self.vals["tor/controlPort"])

        # Line 3 / Line 1 Right (system usage info)
        y, x = (0, leftWidth) if isWide else (2, 0)
        if self.vals["stat/rss"] != "0":
            memoryLabel = str_tools.get_size_label(int(self.vals["stat/rss"]))
        else:
            memoryLabel = "0"

        uptimeLabel = ""
        if self.vals["tor/startTime"]:
            if self.isPaused() or not self._isTorConnected:
                # freeze the uptime when paused or the tor process is stopped
                uptimeLabel = str_tools.get_short_time_label(
                    self.getPauseTime() - self.vals["tor/startTime"])
            else:
                uptimeLabel = str_tools.get_short_time_label(
                    time.time() - self.vals["tor/startTime"])

        sysFields = ((0, "cpu: %s%% tor, %s%% arm" %
                      (self.vals["stat/%torCpu"], self.vals["stat/%armCpu"])),
                     (27, "mem: %s (%s%%)" %
                      (memoryLabel, self.vals["stat/%mem"])),
                     (47, "pid: %s" %
                      (self.vals["tor/pid"] if self._isTorConnected else "")),
                     (59, "uptime: %s" % uptimeLabel))

        for (start, label) in sysFields:
            if start + len(label) <= rightWidth:
                self.addstr(y, x + start, label)
            else:
                break

        if self.vals["tor/orPort"]:
            # Line 4 / Line 2 Right (fingerprint, and possibly file descriptor usage)
            y, x = (1, leftWidth) if isWide else (3, 0)

            fingerprintLabel = uiTools.cropStr(
                "fingerprint: %s" % self.vals["tor/fingerprint"], width)
            self.addstr(y, x, fingerprintLabel)

            # if there's room and we're able to retrieve both the file descriptor
            # usage and limit then it might be presented
            if width - x - 59 >= 20 and self.vals["tor/fdUsed"] and self.vals[
                    "tor/fdLimit"]:
                # display file descriptor usage if we're either configured to do so or
                # running out

                fdPercent = 100 * self.vals["tor/fdUsed"] / self.vals[
                    "tor/fdLimit"]

                if fdPercent >= 60 or CONFIG["features.showFdUsage"]:
                    fdPercentLabel, fdPercentFormat = "%i%%" % fdPercent, curses.A_NORMAL
                    if fdPercent >= 95:
                        fdPercentFormat = curses.A_BOLD | uiTools.getColor(
                            "red")
                    elif fdPercent >= 90:
                        fdPercentFormat = uiTools.getColor("red")
                    elif fdPercent >= 60:
                        fdPercentFormat = uiTools.getColor("yellow")

                    estimateChar = "?" if self.vals[
                        "tor/isFdLimitEstimate"] else ""
                    baseLabel = "file desc: %i / %i%s (" % (
                        self.vals["tor/fdUsed"], self.vals["tor/fdLimit"],
                        estimateChar)

                    self.addstr(y, x + 59, baseLabel)
                    self.addstr(y, x + 59 + len(baseLabel), fdPercentLabel,
                                fdPercentFormat)
                    self.addstr(y,
                                x + 59 + len(baseLabel) + len(fdPercentLabel),
                                ")")

            # Line 5 / Line 3 Left (flags)
            if self._isTorConnected:
                y, x = (2 if isWide else 4, 0)
                self.addstr(y, x, "flags: ")
                x += 7

                if len(self.vals["tor/flags"]) > 0:
                    for i in range(len(self.vals["tor/flags"])):
                        flag = self.vals["tor/flags"][i]
                        flagColor = FLAG_COLORS[
                            flag] if flag in FLAG_COLORS.keys() else "white"

                        self.addstr(
                            y, x, flag,
                            curses.A_BOLD | uiTools.getColor(flagColor))
                        x += len(flag)

                        if i < len(self.vals["tor/flags"]) - 1:
                            self.addstr(y, x, ", ")
                            x += 2
                else:
                    self.addstr(y, x, "none",
                                curses.A_BOLD | uiTools.getColor("cyan"))
            else:
                y = 2 if isWide else 4
                statusTime = torTools.getConn().getHeartbeat()
                statusTimeLabel = time.strftime("%H:%M %m/%d/%Y",
                                                time.localtime(statusTime))
                self.addstr(y, 0, "Tor Disconnected",
                            curses.A_BOLD | uiTools.getColor("red"))
                self.addstr(y, 16,
                            " (%s) - press r to reconnect" % statusTimeLabel)

            # Undisplayed / Line 3 Right (exit policy)
            if isWide:
                exitPolicy = self.vals["tor/exitPolicy"]

                # adds note when default exit policy is appended
                if exitPolicy == "": exitPolicy = "<default>"
                elif not exitPolicy.endswith((" *:*", " *")):
                    exitPolicy += ", <default>"

                self.addstr(2, leftWidth, "exit policy: ")
                x = leftWidth + 13

                # color codes accepts to be green, rejects to be red, and default marker to be cyan
                isSimple = len(exitPolicy) > rightWidth - 13
                policies = exitPolicy.split(", ")
                for i in range(len(policies)):
                    policy = policies[i].strip()
                    policyLabel = policy.replace("accept", "").replace(
                        "reject", "").strip() if isSimple else policy

                    policyColor = "white"
                    if policy.startswith("accept"): policyColor = "green"
                    elif policy.startswith("reject"): policyColor = "red"
                    elif policy.startswith("<default>"): policyColor = "cyan"

                    self.addstr(2, x, policyLabel,
                                curses.A_BOLD | uiTools.getColor(policyColor))
                    x += len(policyLabel)

                    if i < len(policies) - 1:
                        self.addstr(2, x, ", ")
                        x += 2
        else:
            # (Client only) Undisplayed / Line 2 Right (new identity option)
            if isWide:
                conn = torTools.getConn()
                newnymWait = conn.getNewnymWait()

                msg = "press 'n' for a new identity"
                if newnymWait > 0:
                    pluralLabel = "s" if newnymWait > 1 else ""
                    msg = "building circuits, available again in %i second%s" % (
                        newnymWait, pluralLabel)

                self.addstr(1, leftWidth, msg)

        self.valsLock.release()