def _loadConfigOptions(self):
        """
    Fetches the configuration options available from tor or arm.
    """

        self.confContents = []
        self.confImportantContents = []

        if self.configType == State.TOR:
            conn, configOptionLines = torTools.getConn(), []
            customOptions = torConfig.getCustomOptions()
            configOptionQuery = conn.getInfo("config/names")

            if configOptionQuery:
                configOptionLines = configOptionQuery.strip().split("\n")

            for line in configOptionLines:
                # lines are of the form "<option> <type>[ <documentation>]", like:
                # UseEntryGuards Boolean
                # documentation is aparently only in older versions (for instance,
                # 0.2.1.25)
                lineComp = line.strip().split(" ")
                confOption, confType = lineComp[0], lineComp[1]

                # skips private and virtual entries if not configured to show them
                if not self._config[
                        "features.config.state.showPrivateOptions"] and confOption.startswith(
                            "__"):
                    continue
                elif not self._config[
                        "features.config.state.showVirtualOptions"] and confType == "Virtual":
                    continue

                self.confContents.append(
                    ConfigEntry(confOption, confType,
                                not confOption in customOptions))
        elif self.configType == State.ARM:
            # loaded via the conf utility
            armConf = conf.getConfig("arm")
            for key in armConf.getKeys():
                pass  # TODO: implement

        # mirror listing with only the important configuration options
        self.confImportantContents = []
        for entry in self.confContents:
            if torConfig.isImportant(entry.get(Field.OPTION)):
                self.confImportantContents.append(entry)

        # if there aren't any important options then show everything
        if not self.confImportantContents:
            self.confImportantContents = self.confContents

        self.setSortOrder()  # initial sorting of the contents
Beispiel #2
0
    def __init__(self, stdscr, configType, config=None):
        panel.Panel.__init__(self, stdscr, "configState", 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
                })

            self.sortOrdering = config.getIntCSV("features.config.order",
                                                 self.sortOrdering, 3, 0, 6)

        self.configType = configType
        self.confContents = []
        self.scroller = uiTools.Scroller(True)
        self.valsLock = threading.RLock()

        if self.configType == TOR_STATE:
            conn = torTools.getConn()
            customOptions = torConfig.getCustomOptions()
            configOptionLines = conn.getInfo("config/names",
                                             "").strip().split("\n")

            for line in configOptionLines:
                # lines are of the form "<option> <type>", like:
                # UseEntryGuards Boolean
                confOption, confType = line.strip().split(" ", 1)

                # skips private and virtual entries if not set to show them
                if not self._config[
                        "features.config.state.showPrivateOptions"] and confOption.startswith(
                            "__"):
                    continue
                elif not self._config[
                        "features.config.state.showVirtualOptions"] and confType == "Virtual":
                    continue

                manEntry = torConfig.getConfigDescription(confOption)
                self.confContents.append(
                    ConfigEntry(confOption, confType,
                                not confOption in customOptions, manEntry))

            self.setSortOrder()  # initial sorting of the contents
        elif self.configType == ARM_STATE:
            # loaded via the conf utility
            armConf = conf.getConfig("arm")
            for key in armConf.getKeys():
                pass  # TODO: implement
Beispiel #3
0
 def _loadConfigOptions(self):
   """
   Fetches the configuration options available from tor or arm.
   """
   
   self.confContents = []
   self.confImportantContents = []
   
   if self.configType == State.TOR:
     conn, configOptionLines = torTools.getConn(), []
     customOptions = torConfig.getCustomOptions()
     configOptionQuery = conn.getInfo("config/names")
     
     if configOptionQuery:
       configOptionLines = configOptionQuery.strip().split("\n")
     
     for line in configOptionLines:
       # lines are of the form "<option> <type>[ <documentation>]", like:
       # UseEntryGuards Boolean
       # documentation is aparently only in older versions (for instance,
       # 0.2.1.25)
       lineComp = line.strip().split(" ")
       confOption, confType = lineComp[0], lineComp[1]
       
       # skips private and virtual entries if not configured to show them
       if not self._config["features.config.state.showPrivateOptions"] and confOption.startswith("__"):
         continue
       elif not self._config["features.config.state.showVirtualOptions"] and confType == "Virtual":
         continue
       
       self.confContents.append(ConfigEntry(confOption, confType, not confOption in customOptions))
   elif self.configType == State.ARM:
     # loaded via the conf utility
     armConf = conf.getConfig("arm")
     for key in armConf.getKeys():
       pass # TODO: implement
   
   # mirror listing with only the important configuration options
   self.confImportantContents = []
   for entry in self.confContents:
     if torConfig.isImportant(entry.get(Field.OPTION)):
       self.confImportantContents.append(entry)
   
   # if there aren't any important options then show everything
   if not self.confImportantContents:
     self.confImportantContents = self.confContents
   
   self.setSortOrder() # initial sorting of the contents
Beispiel #4
0
 def __init__(self, stdscr, configType, config=None):
   panel.Panel.__init__(self, stdscr, "configState", 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})
     
     self.sortOrdering = config.getIntCSV("features.config.order", self.sortOrdering, 3, 0, 6)
   
   self.configType = configType
   self.confContents = []
   self.scroller = uiTools.Scroller(True)
   self.valsLock = threading.RLock()
   
   if self.configType == TOR_STATE:
     conn = torTools.getConn()
     customOptions = torConfig.getCustomOptions()
     configOptionLines = conn.getInfo("config/names", "").strip().split("\n")
     
     for line in configOptionLines:
       # lines are of the form "<option> <type>", like:
       # UseEntryGuards Boolean
       confOption, confType = line.strip().split(" ", 1)
       
       # skips private and virtual entries if not set to show them
       if not self._config["features.config.state.showPrivateOptions"] and confOption.startswith("__"):
         continue
       elif not self._config["features.config.state.showVirtualOptions"] and confType == "Virtual":
         continue
       
       manEntry = torConfig.getConfigDescription(confOption)
       self.confContents.append(ConfigEntry(confOption, confType, not confOption in customOptions, manEntry))
     
     self.setSortOrder() # initial sorting of the contents
   elif self.configType == ARM_STATE:
     # loaded via the conf utility
     armConf = conf.getConfig("arm")
     for key in armConf.getKeys():
       pass # TODO: implement
Beispiel #5
0
 def showWriteDialog(self):
   """
   Provies an interface to confirm if the configuration is saved and, if so,
   where.
   """
   
   # display a popup for saving the current configuration
   configLines = torConfig.getCustomOptions(True)
   popup, width, height = popups.init(len(configLines) + 2)
   if not popup: return
   
   try:
     # displayed options (truncating the labels if there's limited room)
     if width >= 30: selectionOptions = ("Save", "Save As...", "Cancel")
     else: selectionOptions = ("Save", "Save As", "X")
     
     # checks if we can show options beside the last line of visible content
     isOptionLineSeparate = False
     lastIndex = min(height - 2, len(configLines) - 1)
     
     # if we don't have room to display the selection options and room to
     # grow then display the selection options on its own line
     if width < (30 + len(configLines[lastIndex])):
       popup.setHeight(height + 1)
       popup.redraw(True) # recreates the window instance
       newHeight, _ = popup.getPreferredSize()
       
       if newHeight > height:
         height = newHeight
         isOptionLineSeparate = True
     
     key, selection = 0, 2
     while not uiTools.isSelectionKey(key):
       # if the popup has been resized then recreate it (needed for the
       # proper border height)
       newHeight, newWidth = popup.getPreferredSize()
       if (height, width) != (newHeight, newWidth):
         height, width = newHeight, newWidth
         popup.redraw(True)
       
       # if there isn't room to display the popup then cancel it
       if height <= 2:
         selection = 2
         break
       
       popup.win.erase()
       popup.win.box()
       popup.addstr(0, 0, "Configuration being saved:", curses.A_STANDOUT)
       
       visibleConfigLines = height - 3 if isOptionLineSeparate else height - 2
       for i in range(visibleConfigLines):
         line = uiTools.cropStr(configLines[i], width - 2)
         
         if " " in line:
           option, arg = line.split(" ", 1)
           popup.addstr(i + 1, 1, option, curses.A_BOLD | uiTools.getColor("green"))
           popup.addstr(i + 1, len(option) + 2, arg, curses.A_BOLD | uiTools.getColor("cyan"))
         else:
           popup.addstr(i + 1, 1, line, curses.A_BOLD | uiTools.getColor("green"))
       
       # draws selection options (drawn right to left)
       drawX = width - 1
       for i in range(len(selectionOptions) - 1, -1, -1):
         optionLabel = selectionOptions[i]
         drawX -= (len(optionLabel) + 2)
         
         # if we've run out of room then drop the option (this will only
         # occure on tiny displays)
         if drawX < 1: break
         
         selectionFormat = curses.A_STANDOUT if i == selection else curses.A_NORMAL
         popup.addstr(height - 2, drawX, "[")
         popup.addstr(height - 2, drawX + 1, optionLabel, selectionFormat | curses.A_BOLD)
         popup.addstr(height - 2, drawX + len(optionLabel) + 1, "]")
         
         drawX -= 1 # space gap between the options
       
       popup.win.refresh()
       
       key = cli.controller.getController().getScreen().getch()
       if key == curses.KEY_LEFT: selection = max(0, selection - 1)
       elif key == curses.KEY_RIGHT: selection = min(len(selectionOptions) - 1, selection + 1)
     
     if selection in (0, 1):
       loadedTorrc, promptCanceled = torConfig.getTorrc(), False
       try: configLocation = loadedTorrc.getConfigLocation()
       except IOError: configLocation = ""
       
       if selection == 1:
         # prompts user for a configuration location
         configLocation = popups.inputPrompt("Save to (esc to cancel): ", configLocation)
         if not configLocation: promptCanceled = True
       
       if not promptCanceled:
         try:
           torConfig.saveConf(configLocation, configLines)
           msg = "Saved configuration to %s" % configLocation
         except IOError, exc:
           msg = "Unable to save configuration (%s)" % sysTools.getFileErrorMsg(exc)
         
         popups.showMsg(msg, 2)
   finally: popups.finalize()
Beispiel #6
0
 def handleKey(self, key):
   self.valsLock.acquire()
   isKeystrokeConsumed = True
   if uiTools.isScrollKey(key):
     pageHeight = self.getPreferredSize()[0] - 1
     detailPanelHeight = self._config["features.config.selectionDetails.height"]
     if detailPanelHeight > 0 and detailPanelHeight + 2 <= pageHeight:
       pageHeight -= (detailPanelHeight + 1)
     
     isChanged = self.scroller.handleKey(key, self._getConfigOptions(), pageHeight)
     if isChanged: self.redraw(True)
   elif uiTools.isSelectionKey(key) and self._getConfigOptions():
     # Prompts the user to edit the selected configuration value. The
     # interface is locked to prevent updates between setting the value
     # and showing any errors.
     
     panel.CURSES_LOCK.acquire()
     try:
       selection = self.getSelection()
       configOption = selection.get(Field.OPTION)
       if selection.isUnset(): initialValue = ""
       else: initialValue = selection.get(Field.VALUE)
       
       promptMsg = "%s Value (esc to cancel): " % configOption
       isPrepopulated = self._config["features.config.prepopulateEditValues"]
       newValue = popups.inputPrompt(promptMsg, initialValue if isPrepopulated else "")
       
       if newValue != None and newValue != initialValue:
         try:
           if selection.get(Field.TYPE) == "Boolean":
             # if the value's a boolean then allow for 'true' and 'false' inputs
             if newValue.lower() == "true": newValue = "1"
             elif newValue.lower() == "false": newValue = "0"
           elif selection.get(Field.TYPE) == "LineList":
             # setOption accepts list inputs when there's multiple values
             newValue = newValue.split(",")
           
           torTools.getConn().setOption(configOption, newValue)
           
           # forces the label to be remade with the new value
           selection.labelCache = None
           
           # resets the isDefault flag
           customOptions = torConfig.getCustomOptions()
           selection.fields[Field.IS_DEFAULT] = not configOption in customOptions
           
           self.redraw(True)
         except Exception, exc:
           popups.showMsg("%s (press any key)" % exc)
     finally:
       panel.CURSES_LOCK.release()
   elif key == ord('a') or key == ord('A'):
     self.showAll = not self.showAll
     self.redraw(True)
   elif key == ord('s') or key == ord('S'):
     self.showSortDialog()
   elif key == ord('v') or key == ord('V'):
     self.showWriteDialog()
   else: isKeystrokeConsumed = False
   
   self.valsLock.release()
   return isKeystrokeConsumed
Beispiel #7
0
 def showWriteDialog(self):
   """
   Provies an interface to confirm if the configuration is saved and, if so,
   where.
   """
   
   # display a popup for saving the current configuration
   configLines = torConfig.getCustomOptions(True)
   popup, width, height = popups.init(len(configLines) + 2)
   if not popup: return
   
   try:
     # displayed options (truncating the labels if there's limited room)
     if width >= 30: selectionOptions = ("Save", "Save As...", "Cancel")
     else: selectionOptions = ("Save", "Save As", "X")
     
     # checks if we can show options beside the last line of visible content
     isOptionLineSeparate = False
     lastIndex = min(height - 2, len(configLines) - 1)
     
     # if we don't have room to display the selection options and room to
     # grow then display the selection options on its own line
     if width < (30 + len(configLines[lastIndex])):
       popup.setHeight(height + 1)
       popup.redraw(True) # recreates the window instance
       newHeight, _ = popup.getPreferredSize()
       
       if newHeight > height:
         height = newHeight
         isOptionLineSeparate = True
     
     key, selection = 0, 2
     while not uiTools.isSelectionKey(key):
       # if the popup has been resized then recreate it (needed for the
       # proper border height)
       newHeight, newWidth = popup.getPreferredSize()
       if (height, width) != (newHeight, newWidth):
         height, width = newHeight, newWidth
         popup.redraw(True)
       
       # if there isn't room to display the popup then cancel it
       if height <= 2:
         selection = 2
         break
       
       popup.win.erase()
       popup.win.box()
       popup.addstr(0, 0, "Configuration being saved:", curses.A_STANDOUT)
       
       visibleConfigLines = height - 3 if isOptionLineSeparate else height - 2
       for i in range(visibleConfigLines):
         line = uiTools.cropStr(configLines[i], width - 2)
         
         if " " in line:
           option, arg = line.split(" ", 1)
           popup.addstr(i + 1, 1, option, curses.A_BOLD | uiTools.getColor("green"))
           popup.addstr(i + 1, len(option) + 2, arg, curses.A_BOLD | uiTools.getColor("cyan"))
         else:
           popup.addstr(i + 1, 1, line, curses.A_BOLD | uiTools.getColor("green"))
       
       # draws selection options (drawn right to left)
       drawX = width - 1
       for i in range(len(selectionOptions) - 1, -1, -1):
         optionLabel = selectionOptions[i]
         drawX -= (len(optionLabel) + 2)
         
         # if we've run out of room then drop the option (this will only
         # occure on tiny displays)
         if drawX < 1: break
         
         selectionFormat = curses.A_STANDOUT if i == selection else curses.A_NORMAL
         popup.addstr(height - 2, drawX, "[")
         popup.addstr(height - 2, drawX + 1, optionLabel, selectionFormat | curses.A_BOLD)
         popup.addstr(height - 2, drawX + len(optionLabel) + 1, "]")
         
         drawX -= 1 # space gap between the options
       
       popup.win.refresh()
       
       key = cli.controller.getController().getScreen().getch()
       if key == curses.KEY_LEFT: selection = max(0, selection - 1)
       elif key == curses.KEY_RIGHT: selection = min(len(selectionOptions) - 1, selection + 1)
     
     if selection in (0, 1):
       loadedTorrc, promptCanceled = torConfig.getTorrc(), False
       try: configLocation = loadedTorrc.getConfigLocation()
       except IOError: configLocation = ""
       
       if selection == 1:
         # prompts user for a configuration location
         configLocation = popups.inputPrompt("Save to (esc to cancel): ", configLocation)
         if not configLocation: promptCanceled = True
       
       if not promptCanceled:
         try:
           torConfig.saveConf(configLocation, configLines)
           msg = "Saved configuration to %s" % configLocation
         except IOError, exc:
           msg = "Unable to save configuration (%s)" % sysTools.getFileErrorMsg(exc)
         
         popups.showMsg(msg, 2)
   finally: popups.finalize()
Beispiel #8
0
 def handleKey(self, key):
   self.valsLock.acquire()
   isKeystrokeConsumed = True
   if uiTools.isScrollKey(key):
     pageHeight = self.getPreferredSize()[0] - 1
     detailPanelHeight = CONFIG["features.config.selectionDetails.height"]
     if detailPanelHeight > 0 and detailPanelHeight + 2 <= pageHeight:
       pageHeight -= (detailPanelHeight + 1)
     
     isChanged = self.scroller.handleKey(key, self._getConfigOptions(), pageHeight)
     if isChanged: self.redraw(True)
   elif uiTools.isSelectionKey(key) and self._getConfigOptions():
     # Prompts the user to edit the selected configuration value. The
     # interface is locked to prevent updates between setting the value
     # and showing any errors.
     
     panel.CURSES_LOCK.acquire()
     try:
       selection = self.getSelection()
       configOption = selection.get(Field.OPTION)
       if selection.isUnset(): initialValue = ""
       else: initialValue = selection.get(Field.VALUE)
       
       promptMsg = "%s Value (esc to cancel): " % configOption
       isPrepopulated = CONFIG["features.config.prepopulateEditValues"]
       newValue = popups.inputPrompt(promptMsg, initialValue if isPrepopulated else "")
       
       if newValue != None and newValue != initialValue:
         try:
           if selection.get(Field.TYPE) == "Boolean":
             # if the value's a boolean then allow for 'true' and 'false' inputs
             if newValue.lower() == "true": newValue = "1"
             elif newValue.lower() == "false": newValue = "0"
           elif selection.get(Field.TYPE) == "LineList":
             # setOption accepts list inputs when there's multiple values
             newValue = newValue.split(",")
           
           torTools.getConn().setOption(configOption, newValue)
           
           # forces the label to be remade with the new value
           selection.labelCache = None
           
           # resets the isDefault flag
           customOptions = torConfig.getCustomOptions()
           selection.fields[Field.IS_DEFAULT] = not configOption in customOptions
           
           self.redraw(True)
         except Exception, exc:
           popups.showMsg("%s (press any key)" % exc)
     finally:
       panel.CURSES_LOCK.release()
   elif key == ord('a') or key == ord('A'):
     self.showAll = not self.showAll
     self.redraw(True)
   elif key == ord('s') or key == ord('S'):
     self.showSortDialog()
   elif key == ord('v') or key == ord('V'):
     self.showWriteDialog()
   else: isKeystrokeConsumed = False
   
   self.valsLock.release()
   return isKeystrokeConsumed