Пример #1
0
    def testExistFile__readfile(self):
        """ common.readfile: returns contents for existing files.
            """
        # text file
        data = 'this is a test' + os.linesep
        filename = self.make_file(data)
        self.assertEqual(common.readfile(filename, binary=False), data)

        # binary file
        data = '\x00\x12\x34\x56\x78'
        filename = self.make_file(data)
        self.assertEqual(common.readfile(filename, binary=True), data)
Пример #2
0
    def testExistFile__readfile(self):
        """ common.readfile: returns contents for existing files.
            """
        # text file
        data = 'this is a test' + os.linesep
        filename = self.make_file(data)
        self.assertEqual(common.readfile(filename, binary=False), data)

        # binary file
        data = '\x00\x12\x34\x56\x78'
        filename = self.make_file(data)
        self.assertEqual(common.readfile(filename, binary=True), data)
Пример #3
0
    def _clean_prior(self):
        """ Cleans up from a previous task that didn't exit cleanly.

            Returns ``True`` if previous task was cleaned.
            """

        if self._loaded:
            try:
                pid_file = daemon.get_daemon_pidfile(self)

                # check if it exists so we don't raise
                if os.path.isfile(pid_file):
                    # read pid from file
                    pid = int(common.readfile(pid_file))

                    # check if pid file is stale
                    if pid and not daemon.pid_exists(pid):
                        common.safe_remove_file(pid_file)
                        raise ValueError

            except (ValueError, TypeError):
                self._clean()
                return True

        return False
Пример #4
0
    def _clean_prior(self):
        """ Cleans up from a previous task that didn't exit cleanly.

            Returns ``True`` if previous task was cleaned.
            """

        if self._loaded:
            try:
                pid_file = daemon.get_daemon_pidfile(self)

                # check if it exists so we don't raise
                if os.path.isfile(pid_file):
                    # read pid from file
                    pid = int(common.readfile(pid_file))

                    # check if pid file is stale
                    if pid and not daemon.pid_exists(pid):
                        common.safe_remove_file(pid_file)
                        raise ValueError

            except (ValueError, TypeError):
                self._clean()
                return True

        return False
Пример #5
0
 def testNotExistFile__readfile(self):
     """ common.readfile: returns ``None`` for non-existent files.
         """
     filename = self.make_file()
     self.clean_paths(filename)
     self.assertIsNone(common.readfile(filename))
Пример #6
0
    def _handle_block(self, task, disable=False):
        """ Handles blocking domains using hosts file.

            `task`
                ``Task`` instance.

            `disable`
                Set to ``True``, to turn off blocking and restore hosts file;
                otherwise, ``False`` will enable blocking by updating hosts
                file.

            Returns boolean.
            """

        backup_file = os.path.join(task.task_dir, '.hosts.bak')
        self.orig_data = self.orig_data or common.readfile(backup_file)
        self.last_updated = self.last_updated or -1

        if not self.orig_data:
            # should't attempt restore without good original data, bail
            if disable:
                return False

            # attempt to fetch data from the source
            self.orig_data = common.readfile(self.hosts_file)
            if not self.orig_data:
                return False

        # restore backup
        if not os.path.exists(backup_file):
            common.writefile(backup_file, self.orig_data)

        # bail early if hosts file modification time hasn't changed
        try:
            should_write = (disable or self.last_updated
                            != os.path.getmtime(self.hosts_file))

        except OSError:
            should_write = True  # file was removed, let's write!

        if not should_write:
            return True

        # make copy of original data, in case we need to modify
        data = self.orig_data

        # if not restoring, tack on domains mapped
        # to localhost to end of file data
        if not disable:
            # convert the set to a list and sort
            domains = list(self.domains)
            domains.sort()

            data += ('\n'.join('127.0.0.1\t{0}\t# FOCUS'
                     .format(d) for d in domains) + '\n')

        # make temp file with new host file data
        with tempfile.NamedTemporaryFile(prefix='focus_') as tempf:
            tempf.write(data)
            tempf.flush()

            # overwrite hosts file with our modified copy.
            if not self.run_root('cp "{0}" "{1}"'.format(tempf.name,
                                                         self.hosts_file)):
                return False

            # MacOS X generally requires flushing the system dns cache to pick
            # up changes to the hosts file:
            #   dscacheutil -flushcache or lookupd -flushcache
            if common.IS_MACOSX:
                dscacheutil, lookupd = [common.which(x) for x in
                                        ('dscacheutil', 'lookupd')]
                self.run_root(' '.join([dscacheutil or lookupd,
                                        '-flushcache']))

        if disable:
            common.safe_remove_file(backup_file)  # cleanup the backup

        # store last modification time
        try:
            self.last_updated = os.path.getmtime(self.hosts_file)

        except OSError:
            # file was removed, let's update next time around
            self.last_updated = -1

        return True
Пример #7
0
 def testNotExistFile__readfile(self):
     """ common.readfile: returns ``None`` for non-existent files.
         """
     filename = self.make_file()
     self.clean_paths(filename)
     self.assertIsNone(common.readfile(filename))
Пример #8
0
    def _handle_block(self, task, disable=False):
        """ Handles blocking domains using hosts file.

            `task`
                ``Task`` instance.

            `disable`
                Set to ``True``, to turn off blocking and restore hosts file;
                otherwise, ``False`` will enable blocking by updating hosts
                file.

            Returns boolean.
            """

        backup_file = os.path.join(task.task_dir, '.hosts.bak')
        self.orig_data = self.orig_data or common.readfile(backup_file)
        self.last_updated = self.last_updated or -1

        if not self.orig_data:
            # should't attempt restore without good original data, bail
            if disable:
                return False

            # attempt to fetch data from the source
            self.orig_data = common.readfile(self.hosts_file)
            if not self.orig_data:
                return False

        # restore backup
        if not os.path.exists(backup_file):
            common.writefile(backup_file, self.orig_data)

        # bail early if hosts file modification time hasn't changed
        try:
            should_write = (
                disable
                or self.last_updated != os.path.getmtime(self.hosts_file))

        except OSError:
            should_write = True  # file was removed, let's write!

        if not should_write:
            return True

        # make copy of original data, in case we need to modify
        data = self.orig_data

        # if not restoring, tack on domains mapped
        # to localhost to end of file data
        if not disable:
            # convert the set to a list and sort
            domains = list(self.domains)
            domains.sort()

            data += ('\n'.join('127.0.0.1\t{0}\t# FOCUS'.format(d)
                               for d in domains) + '\n')

        # make temp file with new host file data
        with tempfile.NamedTemporaryFile(prefix='focus_') as tempf:
            tempf.write(data)
            tempf.flush()

            # overwrite hosts file with our modified copy.
            if not self.run_root('cp "{0}" "{1}"'.format(
                    tempf.name, self.hosts_file)):
                return False

            # MacOS X generally requires flushing the system dns cache to pick
            # up changes to the hosts file:
            #   dscacheutil -flushcache or lookupd -flushcache
            if common.IS_MACOSX:
                dscacheutil, lookupd = [
                    common.which(x) for x in ('dscacheutil', 'lookupd')
                ]
                self.run_root(' '.join([dscacheutil or lookupd,
                                        '-flushcache']))

        if disable:
            common.safe_remove_file(backup_file)  # cleanup the backup

        # store last modification time
        try:
            self.last_updated = os.path.getmtime(self.hosts_file)

        except OSError:
            # file was removed, let's update next time around
            self.last_updated = -1

        return True