Example #1
0
 def _write_one(self):
     """ Writes the loaded config file to disk. """
     for section in self.sections():
         print("_write_one", to_unicode(section))
         if not to_unicode(section):
             self.remove_section(to_unicode(section))
     configfile = open(self.config_file, 'w')
     RawConfigParser.write(self, configfile)
     configfile.close()
Example #2
0
    def get_option(self, section, option, default="__None__"):
        """ Wrapper around ConfigParser.get. 
        
        Automatically adds any missing sections, adds the ability
        to write a default value, and if one is provided prints if
        the default or a previously saved value is returned.
        
        """
        if not self.has_section(section):
            if default != "__None__":
                self.add_section(section)
            else:
                return None

        if self.has_option(section, option):
            ret = RawConfigParser.get(self, section, option)
            if (isinstance(ret, str) and ret.startswith(self.mrk_ws)
                    and ret.endswith(self.mrk_ws)):
                ret = ret[3:-3]
            ret = to_unicode(ret)
            if default:
                if self.debug:
                    # mask out sensitive information
                    if option in [
                            'apsk', 'password', 'identity', 'private_key',
                            'private_key_passwd', 'key', 'passphrase'
                    ]:
                        print(''.join(
                            ['found ', option, ' in configuration *****']))
                    else:
                        print(''.join(
                            ['found ', option, ' in configuration ',
                             str(ret)]))
        else:
            if default != "__None__":
                print('did not find {0} in configuration, setting default {1}'.
                      format(option, str(default)))
                self.set(section, option, str(default), write=True)
                ret = default
            else:
                ret = None

        # Try to intelligently handle the type of the return value.
        try:
            if not ret.startswith('0') or len(ret) == 1:
                ret = int(ret)
        except (ValueError, TypeError, AttributeError):
            ret = Noneify(ret)
        # This is a workaround for a python-dbus issue on 64-bit systems.
        if isinstance(ret, (int, )):
            try:
                Int32(ret)
            except OverflowError:
                ret = str(ret)
        return to_unicode(ret)
Example #3
0
 def get_option(self, section, option, default="__None__"):
     """ Wrapper around ConfigParser.get. 
     
     Automatically adds any missing sections, adds the ability
     to write a default value, and if one is provided prints if
     the default or a previously saved value is returned.
     
     """
     if not self.has_section(section):
         if default != "__None__":
             self.add_section(section)
         else:
             return None
 
     if self.has_option(section, option):
         ret = RawConfigParser.get(self, section, option)
         if (isinstance(ret, basestring) and ret.startswith(self.mrk_ws) 
             and ret.endswith(self.mrk_ws)):
             ret = ret[3:-3]
         ret = to_unicode(ret)
         if default:
             if self.debug:
                 # mask out sensitive information
                 if option in ['apsk', 'password', 'identity', \
                               'private_key', 'private_key_passwd', \
                               'key', 'passphrase']:
                     print ''.join(['found ', option, \
                         ' in configuration *****'])
                 else:
                     print ''.join(['found ', option, ' in configuration ',
                                    str(ret)])
     else:
         if default != "__None__":
             print 'did not find %s in configuration, setting default %s' \
                 % (option, str(default))
             self.set(section, option, str(default), write=True)
             ret = default
         else:
             ret = None
     
     # Try to intelligently handle the type of the return value.
     try:
         if not ret.startswith('0') or len(ret) == 1:
             ret = int(ret)
     except (ValueError, TypeError, AttributeError):
         ret = Noneify(ret)
     # This is a workaround for a python-dbus issue on 64-bit systems.
     if isinstance(ret, (int, long)):
         try:
             Int32(ret)
         except OverflowError:
             ret = str(ret)
     return to_unicode(ret)
Example #4
0
 def _ParseAccessPoint(self, cell, ralink_info):
     """ Parse a single cell from the output of iwlist.
     Keyword arguments:
     cell -- string containing the cell information
     ralink_info -- string contating network information needed
                    for ralink cards.
     Returns:
     A dictionary containing the cell networks properties.
     """
     ap = {}
     ap['essid'] = misc.RunRegex(essid_pattern, cell)
     try:
         ap['essid'] = misc.to_unicode(ap['essid'])
     except (UnicodeDecodeError, UnicodeEncodeError):
         print 'Unicode problem with current network essid, ignoring!!'
         return None
     if ap['essid'] in ['<hidden>', ""]:
         ap['essid'] = '<hidden>'
         ap['hidden'] = True
     else:
         ap['hidden'] = False
     ap['channel'] = misc.RunRegex(channel_pattern, cell)
     if ap['channel'] == None:
         freq = misc.RunRegex(freq_pattern, cell)
         ap['channel'] = self._FreqToChannel(freq)
     ap['bssid'] = misc.RunRegex(ap_mac_pattern, cell)
     ap['mode'] = misc.RunRegex(mode_pattern, cell)
     if self.wpa_driver == RALINK_DRIVER:
         ap = self._ParseRalinkAccessPoint(ap, ralink_info, cell)
     elif misc.RunRegex(wep_pattern, cell) == 'on':
         ap['encryption'] = True
         ap['encryption_method'] = 'WEP'
         if misc.RunRegex(wpa1_pattern, cell) == 'WPA Version 1':
             ap['encryption_method'] = 'WPA'
         if misc.RunRegex(altwpa_pattern, cell) == 'wpa_ie':
             ap['encryption_method'] = 'WPA'
         if misc.RunRegex(wpa2_pattern, cell) == 'WPA2':
             ap['encryption_method'] = 'WPA2'
     else:
         ap['encryption'] = False
     if (strength_pattern.match(cell)):
         [(strength, max_strength)] = strength_pattern.findall(cell)
         if max_strength:
             if int(max_strength) != 0:
                 ap["quality"] = 100 * int(strength) // int(max_strength)
             else:
                 ap['quality'] = int(strength)
         else:
             ap["quality"] = int(strength)
     elif misc.RunRegex(altstrength_pattern,cell):
         ap['quality'] = misc.RunRegex(altstrength_pattern, cell)
     else:
         ap['quality'] = -1
     if misc.RunRegex(signaldbm_pattern, cell):
         ap['strength'] = misc.RunRegex(signaldbm_pattern, cell)
     elif self.wpa_driver != RALINK_DRIVER:  
         ap['strength'] = -1
     return ap
Example #5
0
def check_for_wireless(iwconfig, wireless_ip, set_status):
    """ Determine if wireless is active, and if yes, set the status. """
    if not wireless_ip:
        return False

    network = wireless.GetCurrentNetwork(iwconfig)
    if not network:
        return False

    network = misc.to_unicode(network)
    if daemon.GetSignalDisplayType() == 0:
        strength = wireless.GetCurrentSignalStrength(iwconfig)
    else:
        strength = wireless.GetCurrentDBMStrength(iwconfig)

    if strength is None:
        return False
    strength = misc.to_unicode(daemon.FormatSignalForPrinting(strength))
    ip = misc.to_unicode(wireless_ip)
    set_status(_("Connected to $A at $B (IP: $C)").replace("$A", network).replace("$B", strength).replace("$C", ip))
    return True
Example #6
0
    def _parse_ap(self, cell):
        """Parse a single cell from the python-iwscan list."""
        ap = {}
        try:
            ap['essid'] = misc.to_unicode(cell['essid'])
        except UnicodeError:
            print('Unicode problem with the current network essid, ignoring!!')
            return None

        if ap['essid'] in ["", '<hidden>']:
            ap['essid'] = '<hidden>'
            ap['hidden'] = True
        else:
            ap['hidden'] = False

        if cell["channel"]:
            ap["channel"] = cell["channel"]
        else:
            ap["channel"] = self._FreqToChannel(cell["frequency"])

        ap["bssid"] = cell["bssid"]
        ap["mode"] = cell["mode"]
        ap["bitrates"] = cell["bitrate"]

        if cell["enc"]:
            ap["encryption"] = True
            if cell["ie"] and cell["ie"].get('type'):
                if "WPA2" in cell['ie']['type'].upper():
                    ap['encryption_method'] = 'WPA2'
                elif "WPA" in cell['ie']['type'].upper():
                    ap['encryption_method'] = 'WPA'
            else:
                ap['encryption_method'] = 'WEP'
        else:
            ap["encryption"] = False

        # Link Quality
        ap['qual_found'] = True
        ap['quality'] = self._get_link_quality(cell['stats'])
        if ap['quality'] is None:
            ap['qual_found'] = False
            ap['quality'] = -1

        # Signal Strength (only used if user doesn't want link
        # quality displayed or it isn't found)
        if misc.RunRegex(signaldbm_pattern, cell["stats"]):
            ap['strength'] = misc.RunRegex(signaldbm_pattern, cell["stats"])
        # This is already set for ralink
        elif self.wpa_driver != RALINK_DRIVER:
            ap['strength'] = -1

        return ap
Example #7
0
    def _parse_ap(self, cell):
        """ Parse a single cell from the python-iwscan list. """
        ap = {}
        try:
            ap['essid'] = misc.to_unicode(cell['essid'])
        except UnicodeError:
            print('Unicode problem with the current network essid, ignoring!!')
            return None

        if ap['essid'] in [ "", '<hidden>']:
            ap['essid'] = '<hidden>'
            ap['hidden'] = True
        else:
            ap['hidden'] = False

        if cell["channel"]:
            ap["channel"] = cell["channel"]
        else:
            ap["channel"] = self._FreqToChannel(cell["frequency"])

        ap["bssid"] = cell["bssid"]
        ap["mode"] = cell["mode"]
        ap["bitrates"] = cell["bitrate"]

        if cell["enc"]:
            ap["encryption"] = True
            if cell["ie"] and cell["ie"].get('type'):
                if "WPA2" in cell['ie']['type'].upper():
                    ap['encryption_method'] = 'WPA2'
                elif "WPA" in cell['ie']['type'].upper():
                    ap['encryption_method'] = 'WPA'
            else:
                ap['encryption_method'] = 'WEP'
        else:
            ap["encryption"] = False

        # Link Quality
        ap['qual_found'] = True
        ap['quality'] = self._get_link_quality(cell['stats'])
        if ap['quality'] is None:
            ap['qual_found'] = False
            ap['quality'] = -1

        # Signal Strength (only used if user doesn't want link
        # quality displayed or it isn't found)
        if misc.RunRegex(signaldbm_pattern, cell["stats"]):
            ap['strength'] = misc.RunRegex(signaldbm_pattern, cell["stats"])
        elif self.wpa_driver != RALINK_DRIVER:  # This is already set for ralink
            ap['strength'] = -1  

        return ap
Example #8
0
    def CheckForWireless(self,iwconfig,wireless_ip,set_status):
        if not wireless_ip:
            return False
        network = self._Wireless.GetCurrentNetwork(iwconfig)
        if not network:
            return False
        network = misc.to_unicode(network)
        if daemon.GetSignalDisplayType() == 0:
            strength = self._Wireless.GetCurrentSignalStrength(iwconfig)
        else:
            strength = self._Wireless.GetCurrentDBMStrength(iwconfig)

        if strength is None:
            return False
        strength = misc.to_unicode(self._Daemon.FormatSignalForPrinting(strength))
        ip = misc.to_unicode(wireless_ip)

        print(_('Connected to $A at $B (IP: $C)').replace
                    ('$A', network).replace
                    ('$B', strength).replace
                    ('$C', ip))
        
        return True
Example #9
0
def check_for_wireless(iwconfig, wireless_ip, set_status):
    """ Determine if wireless is active, and if yes, set the status. """
    if not wireless_ip:
        return False

    network = wireless.GetCurrentNetwork(iwconfig)
    if not network:
        return False

    network = misc.to_unicode(network)
    if daemon.GetSignalDisplayType() == 0:
        strength = wireless.GetCurrentSignalStrength(iwconfig)
    else:
        strength = wireless.GetCurrentDBMStrength(iwconfig)

    if strength is None:
        return False
    strength = misc.to_unicode(daemon.FormatSignalForPrinting(strength))
    ip = misc.to_unicode(wireless_ip)
    set_status(
        _('Connected to $A at $B (IP: $C)').replace('$A', network).replace(
            '$B', strength).replace('$C', ip))
    return True
	def GetCurrentNetwork(self, iwconfig=None):
        """ Get the essid of the current network.
        Returns:
        The current network essid.
        """
        if not iwconfig:
            cmd = 'iwconfig ' + self.iface
            if self.verbose: print cmd
            output = misc.Run(cmd)
        else:
            output = iwconfig
        network = misc.RunRegex(re.compile('.*ESSID:"(.*?)"',                                           re.I | re.M  | re.S), output)
        if network:
            network = misc.to_unicode(network)
        return network
 def _parse_ap(self, cell):
     """ Parse a single cell from the python-iwscan list. """
     ap = {}
     try:
         ap['essid'] = misc.to_unicode(cell['essid'])
     except UnicodeError:
         print 'Unicode problem with the current network essid, ignoring!!'
         return None
     if ap['essid'] in [ "", '<hidden>']:
         ap['essid'] = 'Hidden'
         ap['hidden'] = True
     else:
         ap['hidden'] = False
     ap["channel"] = True and cell["channel"] or \
                     self._FreqToChannel(cell["frequency"])
     ap["bssid"] = cell["bssid"]
     ap["mode"] = cell["mode"]
     if cell["enc"]:
         ap["encryption"] = True
         if cell["ie"]:
             if "WPA2" in cell['ie']['type'].upper():
                 ap['encryption_method'] = 'WPA2'
             elif "WPA" in cell['ie']['type'].upper():
                 ap['encryption_method'] = 'WPA'
         else:
             ap['encryption_method'] = 'WEP'
     else:
         ap["encryption"] = False
     ap['qual_found'] = True
     try:
         [(strength, max_strength)] = strength_pattern.findall(cell["stats"])
         if max_strength:
             ap["quality"] = 100 * int(strength) // int(max_strength)
         else:
             ap["quality"] = int(strength)
     except ValueError:
         ap['quality'] = misc.RunRegex(altstrength_pattern,cell["stats"])
         if not ap['quality']:
             ap['qual_found'] = False
             ap['quality'] = -1
     if misc.RunRegex(signaldbm_pattern, cell["stats"]):
         ap['strength'] = misc.RunRegex(signaldbm_pattern, cell["stats"])
     elif self.wpa_driver != RALINK_DRIVER:  
         ap['strength'] = -1  
     return ap
Example #12
0
    def set_option(self, section, option, value, write=False):
        """ Wrapper around ConfigParser.set

        Adds the option to write the config file change right away.
        Also forces all the values being written to type str, and
        adds the section the option should be written to if it
        doesn't exist already.
        
        """
        if not self.has_section(section):
            self.add_section(section)
        if isinstance(value, str):
            value = to_unicode(value)
            if value.startswith(' ') or value.endswith(' '):
                value = "%(ws)s%(value)s%(ws)s" % {"value" : value,
                                                   "ws" : self.mrk_ws}
        RawConfigParser.set(self, section, str(option), value)
        if write:
            self.write()
Example #13
0
    def set_option(self, section, option, value, write=False):
        """ Wrapper around ConfigParser.set

        Adds the option to write the config file change right away.
        Also forces all the values being written to type str, and
        adds the section the option should be written to if it
        doesn't exist already.
        
        """
        if not self.has_section(section):
            self.add_section(section)
        if isinstance(value, basestring):
            value = to_unicode(value)
            if value.startswith(' ') or value.endswith(' '):
                value = "%(ws)s%(value)s%(ws)s" % {"value" : value,
                                                   "ws" : self.mrk_ws}
        RawConfigParser.set(self, section, str(option), value)
        if write:
            self.write()
Example #14
0
    def write(self, fp=None):
        """ Writes the loaded config file to disk. """
        in_this_file = []
        sec_r = [to_unicode(s) for s in self.sections()]
        for sname in sorted(sec_r):
            fname = self.get_option(sname, '_filename_')
            if fname and fname != self.config_file:
                # Write sections from other files
                section = self._copy_section(sname)
                section._write_one()
            else:
                # Save names of local sections
                in_this_file.append(sname)
        print("in_this_file", in_this_file)

        # Make an instance with only these sections
        p = ConfigManager("", self.debug, self.mrk_ws)
        p.config_file = self.config_file
        for sname in in_this_file:
            p.add_section(sname)
            for (iname, value) in self.items(sname):
                p.set(sname, iname, value)
            p.remove_option(sname, '_filename_')
        p._write_one()
	def _ParseAccessPoint(self, cell, ralink_info):
        """ Parse a single cell from the output of iwlist.
        Keyword arguments:
        cell -- string containing the cell information
        ralink_info -- string contating network information needed
                       for ralink cards.
        Returns:
        A dictionary containing the cell networks properties.
        """
        ap = {}
        ap['essid'] = misc.RunRegex(essid_pattern, cell)
        try:
            ap['essid'] = misc.to_unicode(ap['essid'])
        except (UnicodeDecodeError, UnicodeEncodeError):
            print 'Unicode problem with current network essid, ignoring!!'
            return None
        if ap['essid'] in ['<hidden>', ""]:
            ap['essid'] = 'Hidden'
            ap['hidden'] = True
        else:
            ap['hidden'] = False
        ap['channel'] = misc.RunRegex(channel_pattern, cell)
        if ap['channel'] == None:
            freq = misc.RunRegex(freq_pattern, cell)
            ap['channel'] = self._FreqToChannel(freq)
        ap['bssid'] = misc.RunRegex(ap_mac_pattern, cell)
        ap['mode'] = misc.RunRegex(mode_pattern, cell)
        if self.wpa_driver == RALINK_DRIVER:
            ap = self._ParseRalinkAccessPoint(ap, ralink_info, cell)
        elif misc.RunRegex(wep_pattern, cell) == 'on':
            ap['encryption'] = True
            ap['encryption_method'] = 'WEP'
            if misc.RunRegex(wpa1_pattern, cell) == 'WPA Version 1':
                ap['encryption_method'] = 'WPA'
            if misc.RunRegex(altwpa_pattern, cell) == 'wpa_ie':
                ap['encryption_method'] = 'WPA'
            if misc.RunRegex(wpa2_pattern, cell) == 'WPA2':
                ap['encryption_method'] = 'WPA2'
        else:
            ap['encryption'] = False
        if (strength_pattern.match(cell)):
            [(strength, max_strength)] = strength_pattern.findall(cell)
            if max_strength:
                ap["quality"] = 100 * int(strength) // int(max_strength)
            else:
                ap["quality"] = int(strength)
        elif misc.RunRegex(altstrength_pattern,cell):
            ap['quality'] = misc.RunRegex(altstrength_pattern, cell)
        else:
            ap['quality'] = -1
        if misc.RunRegex(signaldbm_pattern, cell):
            ap['strength'] = misc.RunRegex(signaldbm_pattern, cell)
        elif self.wpa_driver != RALINK_DRIVER:
            ap['strength'] = -1
        return ap
    
	def ValidateAuthentication(self, auth_time):
        """ Validate WPA authentication.
            Validate that the wpa_supplicant authentication
            process was successful.
            NOTE: It's possible this could return False,
            though in reality wpa_supplicant just isn't
            finished yet.
            Keyword arguments:
            auth_time -- The time at which authentication began.
            Returns:
            True if wpa_supplicant authenticated succesfully,
            False otherwise.
        """
        if self.wpa_driver == RALINK_DRIVER or not self.WPA_CLI_FOUND:
            return True
        MAX_TIME = 15
        MAX_DISCONNECTED_TIME = 3
        while (time.time() - auth_time) < MAX_TIME:
            cmd = 'wpa_cli -i ' + self.iface + ' status'
            output = misc.Run(cmd)
            result = misc.RunRegex(auth_pattern, output)
            if self.verbose:
                print 'WPA_CLI RESULT IS', result
            if not result:
                return False
            if result == "COMPLETED":
                return True
            elif result == "DISCONNECTED" and \
                 (time.time() - auth_time) > MAX_DISCONNECTED_TIME:
                self._ForceSupplicantScan()
                MAX_TIME += 5
            time.sleep(1)
        print 'wpa_supplicant authentication may have failed.'
        return False
    
	def _ForceSupplicantScan(self):
        """ Force wpa_supplicant to rescan available networks.
        This function forces wpa_supplicant to rescan.
        This works around authentication validation sometimes failing for
        wpa_supplicant because it remains in a DISCONNECTED state for
        quite a while, after which a rescan is required, and then
        attempting to authenticate.  This whole process takes a long
        time, so we manually speed it up if we see it happening.
        """
        print 'wpa_supplicant rescan forced...'
        cmd = 'wpa_cli -i' + self.iface + ' scan'
        misc.Run(cmd)
    
	def GetBSSID(self, iwconfig=None):
        """ Get the MAC address for the interface. """
        if not iwconfig:
            cmd = 'iwconfig ' + self.iface
            if self.verbose: print cmd
            output = misc.Run(cmd)
        else:
            output = iwconfig
        bssid = misc.RunRegex(bssid_pattern, output)
        return bssid
    
	def GetSignalStrength(self, iwconfig=None):
        """ Get the signal strength of the current network.
        Returns:
        The signal strength.
        """
        if not iwconfig:
            cmd = 'iwconfig ' + self.iface
            if self.verbose: print cmd
            output = misc.Run(cmd)
        else:
            output = iwconfig
        [(strength, max_strength)] = strength_pattern.findall(output)
        if max_strength and strength:
            return 100 * int(strength) // int(max_strength)
        if strength is None:
            strength = misc.RunRegex(altstrength_pattern, output)
        return strength
    
	def GetDBMStrength(self, iwconfig=None):
        """ Get the dBm signal strength of the current network.
        Returns:
        The dBm signal strength.
        """
        if not iwconfig:
            cmd = 'iwconfig ' + self.iface
            if self.verbose: print cmd
            output = misc.Run(cmd)
        else:
            output = iwconfig
        dbm_strength = misc.RunRegex(signaldbm_pattern, output)
        return dbm_strength
    
	def GetCurrentNetwork(self, iwconfig=None):
        """ Get the essid of the current network.
        Returns:
        The current network essid.
        """
        if not iwconfig:
            cmd = 'iwconfig ' + self.iface
            if self.verbose: print cmd
            output = misc.Run(cmd)
        else:
            output = iwconfig
        network = misc.RunRegex(re.compile('.*ESSID:"(.*?)"',                                           re.I | re.M  | re.S), output)
        if network:
            network = misc.to_unicode(network)
        return network
Example #16
0
 def test_to_unicode_1(self):
     self.assertEquals(misc.to_unicode('邪悪'), '邪悪')
Example #17
0
 def test_to_unicode_6(self):
     self.assertEquals(misc.to_unicode('berk\xe5k'), "berkåk")
Example #18
0
 def test_to_unicode_5(self):
     self.assertEquals(misc.to_unicode("berkåk"), "berkåk")
Example #19
0
 def test_to_unicode_4(self):
     self.assertEquals(type(misc.to_unicode('abcdef'.encode('latin-1'))), str)
Example #20
0
 def test_to_unicode_3(self):
     self.assertEquals(misc.to_unicode(u'abcdef'), 'abcdef')
Example #21
0
 def test_to_unicode_6(self):
     self.assertEqual(misc.to_unicode('berk\xe5k'), "berkåk")
Example #22
0
 def test_to_unicode_5(self):
     self.assertEqual(misc.to_unicode("berkåk"), "berkåk")
Example #23
0
 def test_to_unicode_4(self):
     self.assertEqual(type(misc.to_unicode('abcdef'.encode('latin-1'))), bytes)
Example #24
0
 def test_to_unicode_3(self):
     self.assertEqual(misc.to_unicode('abcdef'), 'abcdef')
Example #25
0
 def test_to_unicode_2(self):
     self.assertEqual(misc.to_unicode('邪悪'), '邪悪')