def p7zopen(cls, name, mode="r", fileobj=None):
        """Open 7z compressed cpio archive name for reading, writing.
                
                Appending is not allowed
                """
        if len(mode) > 1 or mode not in "rw":
            raise ValueError, "mode must be 'r' or 'w'."

        pre, ext = os.path.splitext(name)
        pre = os.path.basename(pre)
        if ext == ".7z":
            ext = ""
        cpioname = pre + ext

        try:
            # To extract: 7z e -so <fname>
            # To create an archive: 7z a -si <fname>
            cmd = "7z %s -%s %s" % ({
                'r': 'e',
                'w': 'a'
            }[mode], {
                'r': 'so',
                'w': 'si'
            }[mode], name)
            p = subprocess.Popen(cmd.split(),
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE)
            pobj = p.stdout
            if mode == "w":
                pobj = p.stdin

            comptype = "cpio"
            bufsize = 20 * 512

            obj = _Stream(cpioname, mode, comptype, pobj, bufsize)
            t = cls.cpioopen(cpioname, mode, obj)
        except IOError:
            raise ReadError, "read/write via 7z failed"
        t._extfileobj = False
        return t
Example #2
0
    def testRemoveOfRunningExecutable(self):
        if util.get_canonical_os_type() != 'windows':
            return
        import pkg.portable.os_windows as os_windows
        cwd = os.getcwdu()
        exefilesrc = 'C:\\Windows\\system32\\more.com'
        self.assertTrue(os.path.exists(exefilesrc))

        # create an image, copy an executable into it,
        # run the executable, remove the executable
        tdir1 = tempfile.mkdtemp()
        img1 = image.Image(tdir1,
                           imgtype=image.IMG_USER,
                           should_exist=False,
                           user_provided_dir=True)
        img1.history.client_name = "pkg-test"
        img1.set_attrs(False,
                       "test",
                       origins=["http://localhost:10000"],
                       refresh_allowed=False)
        exefile = os.path.join(tdir1, 'less.com')
        shutil.copyfile(exefilesrc, exefile)
        proc = subprocess.Popen([exefile], stdin=subprocess.PIPE)
        self.assertRaises(OSError, os.unlink, exefile)
        portable.remove(exefile)
        self.assertTrue(not os.path.exists(exefile))
        proc.communicate()

        # Make sure that the moved executable gets deleted
        # This is a white-box test
        # To simulate running another process, we delete the cache
        # and call get_trashdir as if another file was being moved
        # to the trash.
        os_windows.cached_image_info = []
        os_windows.get_trashdir(exefile)
        self.assertTrue(not os.path.exists(
            os.path.join(img1.imgdir, os_windows.trashname)))

        # cleanup
        os.chdir(cwd)
        shutil.rmtree(tdir1)
Example #3
0
def __call(args, zone=None):
    # a way to invoke a separate executable for testing
    cmds_dir = DebugValues.get_value("smf_cmds_dir")
    if cmds_dir:
        args = (os.path.join(cmds_dir, args[0].lstrip("/")), ) + args[1:]
    if zone:
        cmd = DebugValues.get_value("bin_zlogin")
        if cmd is None:
            cmd = zlogin_path
        args = (cmd, zone) + args

    try:
        proc = subprocess.Popen(args,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
        buf = [misc.force_str(l) for l in proc.stdout.readlines()]
        ret = proc.wait()
    except OSError as e:
        raise RuntimeError("cannot execute {0}: {1}".format(args, e))

    if ret != 0:
        raise NonzeroExitException(args, ret, buf)
    return buf
Example #4
0
 def __get_dates_of_creation(be_list):
     #zfs list -H -o creation rpool/ROOT/opensolaris-1
     cmd = ["/sbin/zfs", "list", "-H", "-o", "creation"]
     for bee in be_list:
         if bee.get("orig_be_name"):
             name = bee.get("orig_be_name")
             pool = bee.get("orig_be_pool")
             cmd += [pool + "/ROOT/" + name]
     if len(cmd) <= 5:
         return None
     list_of_dates = []
     try:
         proc = subprocess.Popen(
             cmd,
             stdout=subprocess.PIPE,
             stderr=subprocess.PIPE,
         )
         line_out = proc.stdout.readline()
         while line_out:
             list_of_dates.append(line_out)
             line_out = proc.stdout.readline()
     except OSError:
         return list_of_dates
     return list_of_dates
    def __initial_start(self):
        if self.__state != self.HALTED:
            raise DepotStateException("Depot already starting or running")

        # XXX what about stdin and stdout redirection?
        args = self.get_args()

        if self.__network_ping():
            raise DepotStateException("A depot (or some " +
                                      "other network process) seems to be " +
                                      "running on port %d already!" %
                                      self.__port)

        self.__state = self.STARTING

        self.__output = open(self.__logpath, "w", 0)

        self.__depot_handle = subprocess.Popen(args=args,
                                               stdin=subprocess.PIPE,
                                               stdout=self.__output,
                                               stderr=self.__output,
                                               close_fds=True)
        if self.__depot_handle == None:
            raise DepotStateException("Could not start Depot")
Example #6
0
        if x == 7:
            # ta requires a password to unlock cert, don't use
            continue
        fn = "{0}/ta{1:d}/ta{2:d}_cert.pem".format(output_dir, x, x)
        fhr = open(fn, "r")
        fhw.write(fhr.read())
        fhr.close()
    fhw.close()

    # Create a certificate with an extension that Cryptography can't
    # understand. We can't do it by the OpenSSL CLI, but we can use a C
    # program that calls OpenSSL libraries to do it.
    os.chdir("../../../util/mkcert")
    cmdline = "./certgen"
    p = subprocess.Popen(cmdline,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         shell=True)
    p.wait()

    output, error = p.communicate()
    if p.returncode == 127:
        print("certgen not found; execute 'make' in the mkcert "
              "directory first")
        sys.exit(p.returncode)
    elif p.returncode != 0:
        print("failed: {0} {1}".format(output, error))
        sys.exit(p.returncode)

    # copy the generated cert files from util/mkcert to the ro_data area
    shutil.copy("cust_key.pem",
                "../../tests/ro_data/signing_certs/produced/keys/")
Example #7
0
        def check_firmware(self, dep_action, firmware_name):
                """Check firmware dependency.
                returns ((true, false, none (internal error)),
                error text)"""

                firmware_dir = "/usr/lib/fwenum"
                # leverage smf test infrastructure
                cmds_dir = DebugValues["smf_cmds_dir"]
                if DebugValues["firmware-dependency-bypass"]:
                        return (True, None)
                if cmds_dir: # we're testing;
                        firmware_dir = cmds_dir

                args = [os.path.join(firmware_dir, firmware_name[len("feature/firmware/"):])]
                args.extend([
                    "{0}={1}".format(k, quote_attr_value(v))
                    for k,v in sorted(six.iteritems(dep_action.attrs))
                    if k not in ["type", "root-image", "fmri"]
                ])

                key = str(args)

                # use a cache since each check may be expensive and each
                # pkg version may have the same dependency.
                # ignore non-solaris systems here

                if portable.osname != "sunos" and key not in self.firmware:
                    self.__firmware[key] = (True, None)

                if key not in self.__firmware:
                        try:
                                proc = subprocess.Popen(args, stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)
                                # output from proc is bytes
                                buf = [misc.force_str(l) for l in
                                    proc.stdout.readlines()]
                                ret = proc.wait()
                                # if there was output, something went wrong.
                                # Since generic errors are often exit(1),
                                # map this to an internal error.
                                if ret == 1 and len(buf) > 0:
                                        ret = 255
                                if ret == 0:
                                        ans = (True, None)
                                elif 0 < ret <= 239:
                                        ans = (False, (_("There are {0} instances"
                                            " of downrev firmware for the '{1}' "
                                            " devices present on this system. "
                                            "Update each to version {2} or better."
                                            ).format(ret, args[1],
                                            dep_action.attrs.get("minimum-version",
                                            _("UNSPECIFIED")))))
                                elif ret == 240:
                                        ans = (False, (_("There are 240 or more "
                                            "instances of downrev firmware for the"
                                            "'{0}' devices present on this system. "
                                            "Update each to version {1} or better."
                                            ).format(args[1],
                                            dep_action.attrs.get("minimum-version",
                                            _("UNSPECIFIED")))))
                                elif ret < 0:
                                        ans = (None,
                                            (_("Firmware dependency error: {0} "
                                            " exited due to signal {1}").format(
                                            " ".join(args), misc.signame(-ret))))
                                else:
                                        ans = (None,
                                            (_("Firmware dependency error: General "
                                            "internal error {0} running '{1}': '{2}'"
                                            ).format(str(ret), " ".join(args),
                                            "\n".join(buf))))

                        except OSError as e:
                                # we have no enumerator installed.  This can
                                # occur if this driver is being installed
                                # for the first time or, more likely, we
                                # just added enumerators & a firmware dependency
                                # for the first time.  For now, drive on and
                                # ignore this to permit the addition of such
                                # dependencies concurrently with their
                                # enumerarators.
                                # ans = (None, (_("Firmware dependency error:"
                                # " Cannot exec {0}: {1}").format(" ".join(args)
                                # , str(e))))
                                ans = (True, 0)

                        self.__firmware[key] = ans

                return self.__firmware[key]
Example #8
0
        http_proxy = get_http_proxy()
        if os.getenv(HTTP_PROXY_VARIABLE) == None:
            os.putenv(HTTP_PROXY_VARIABLE, http_proxy)
        if os.getenv(HTTPS_PROXY_VARIABLE) == None:
            os.putenv(HTTPS_PROXY_VARIABLE, http_proxy)

    # If /usr/bin/packagemanager was checked for instead, that would make
    # testing (especially automated) impossible for web links.
    allow_links = False
    args = sys.argv[1:]
    if args[0].find("packagemanager") != -1 and not portable.is_admin():
        allow_links = True
        args.append("--allow-links")
    args = ["/usr/bin/gksu", " ".join(args)]

    proc = subprocess.Popen(args, stdout=subprocess.PIPE, close_fds=True)

    # Reap the defunct gksu now rather than wait for kernel to do it.
    proc.wait()

    if not allow_links:
        # Nothing to do for other programs.
        sys.exit()

    # XXX PackageManager should not run as a privileged process!
    # This rather convoluted solution allows packagemanager to open links
    # as the original user that launched the packagemanager instead of as
    # a privileged user.  It does this by using select to poll the output
    # of the packagemanager, and open links as it requests them.  Once
    # the packagemanager has exited, the pipe is broken and pm-launch will
    # exit as well.