예제 #1
0
	def create(self, password):
		cmd = "useradd -d /dev/null -s /bin/false -G %s,%s %s"%(Config.group, "sambashare", self.login)
		p = System.execute(cmd)
		if p.returncode == 9:
			Logger.warn("FS: unable to create user: already exists")
			return False
		elif p.returncode != 0:
			Logger.error("FS: unable to create user")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
			return False
		
		cmd = 'smbpasswd -s -a %s'%(self.login)
		p = System.execute(cmd, wait = False)
		p.stdin.write("%s\n%s\n"%(password, password))
		p.wait()
		
		if p.returncode != 0:
			Logger.error("FS: unable to set samba password")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
			return False
		
		cmd = 'htpasswd -b %s "%s" "%s"'%(Config.dav_passwd_file, self.login, password)
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.error("FS: unable to update apache auth file")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
			return False
		
		return True
예제 #2
0
	def destroy(self):
		ret = True
		
		cmd = 'htpasswd -D %s "%s"'%(Config.dav_passwd_file, self.login)
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.error("FS: unable to update apache auth file")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
			return False
		
		cmd = 'smbpasswd -x %s'%(self.login)
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.error("FS: unable to del smb password")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
			ret = False
		
		cmd = "userdel -f %s"%(self.login)
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.error("FS: unable to del user")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
			ret = False
		
		return ret
예제 #3
0
파일: Share.py 프로젝트: poorboy/openulteo
    def enable(self, mode):
        for i in ['ro', 'rw']:
            cmd = "groupadd  %s_%s" % (self.group, i)
            p = System.execute(cmd)
            if p.returncode is not 0:
                Logger.error("FS: unable to create group")
                Logger.debug(
                    "FS: command '%s' return %d: %s" %
                    (cmd, p.returncode, p.stdout.read().decode("UTF-8")))
                return False

        cmd = 'net usershare add %s "%s" %s %s_ro:r,%s_rw:f guest_ok=n' % (
            self.name, self.frontDirectory, self.name, self.group, self.group)
        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.error("FS: unable to add share")
            Logger.debug("FS: command '%s' return %d: %s" %
                         (cmd, p.returncode, p.stdout.read().decode("UTF-8")))
            return False

        self.do_right_normalization()

        self.htaccess.addGroup(self.group)
        self.htaccess.save()

        self.active = True
        return True
예제 #4
0
파일: User.py 프로젝트: bloveing/openulteo
	def check_remaining_mount_points(self):
		try:
			user = pwd.getpwnam(System.local_encode(self.name))
		except KeyError:
			return False
		
		mount_points = MountPoint.get_list(user.pw_dir)
		if mount_points is None:
			return False
		
		success = True
		for d in mount_points:
			path = System.local_encode(d)
			Logger.warn("Remaining mount point '%s'"%(path))
			cmd = 'umount "%s"'%(path)
			
			p = System.execute(cmd)
			if p.returncode == 0:
				continue
			
			Logger.warn("Unable to unmount remaining mount point %s: force the unmount"%(path))
			Logger.debug('umount command "%s" return: %s'%(cmd,  p.stdout.read()))
			cmd = 'umount -l "%s"'%(path)
			p = System.execute(cmd)
			if p.returncode != 0:
				Logger.error("Unable to force the unmount remaining mount point %s"%(path))
				Logger.debug('umount command "%s" return: %s'%(cmd,  p.stdout.read()))
			
			success = False
		
		if success == False:
			Logger.error("Unable to unmount remaining mount point, home dir %s won't be purged"%(user.pw_dir))
		
		return success
예제 #5
0
파일: Apt.py 프로젝트: bloveing/openulteo
	def perform(self):
		os.mkdir(self.directory)
		f_stdout = open(os.path.join(self.directory, "stdout"), "w")
		f_stderr = open(os.path.join(self.directory, "stderr"), "w")
		process_out = {"stdout": f_stdout, "stderr": f_stderr}
		
		p = System.execute(["apt-get", "update"], True, {}, process_out)
		if p.returncode != 0:
			f_stdout.close()
			f_stderr.close()
			return False
		
		apt_env = {"DEBIAN_FRONTEND": "noninteractive", "DEBIAN_PRIORITY": "critical", "DEBCONF_NONINTERACTIVE_SEEN": "true"}
		command = ["apt-get", "--yes", "--force-yes", "--option", "DPkg::Options::=--force-confold"]
		if self.order == "upgrade":
			command.append("dist-upgrade")
		elif self.order == "install":
			command.append("install")
		elif self.order == "remove":
			command.append("autoremove")
			command.append("--purge")
		
		if self.order in ["install", "remove"]:
			command.extend(self.packages)
		
		p = System.execute(command, True, apt_env, process_out)
		if p.returncode != 0:
			f_stdout.close()
			f_stderr.close()
			return False
		
		f_stdout.close()
		f_stderr.close()
		return True
예제 #6
0
파일: Share.py 프로젝트: bloveing/openulteo
	def do_right_normalization(self):
		cmd = 'chown -R %s:%s "%s"'%(Config.uid, Config.gid, self.directory)
		p = System.execute(cmd)
		if p.returncode is not 0:
			Logger.debug("FS: following command '%s' returned %d => %s"%(cmd, p.returncode, p.stdout.read()))
		
		cmd = 'chmod -R u=rwX,g=rwX,o-rwx "%s"'%(self.directory)
		p = System.execute(cmd)
		if p.returncode is not 0:
			Logger.debug("FS: following command '%s' returned %d => %s"%(cmd, p.returncode, p.stdout.read()))
예제 #7
0
파일: Share.py 프로젝트: poorboy/openulteo
    def do_right_normalization(self):
        cmd = 'chown -R %s:%s "%s"' % (Config.uid, Config.gid, self.directory)
        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.debug("FS: following command '%s' returned %d => %s" %
                         (cmd, p.returncode, p.stdout.read()))

        cmd = 'chmod -R u=rwX,g=rwX,o-rwx "%s"' % (self.directory)
        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.debug("FS: following command '%s' returned %d => %s" %
                         (cmd, p.returncode, p.stdout.read()))
예제 #8
0
파일: Role.py 프로젝트: bloveing/openulteo
	def cleanup_repository(self):
		cmd = 'chown -R %s:%s "%s"'%(Config.uid, Config.gid, Config.backendSpool)
		p = System.execute(cmd)
		if p.returncode is not 0:
			Logger.debug("FS: following command '%s' returned %d => %s"%(cmd, p.returncode, p.stdout.read()))
			return False
		
		cmd = 'chmod -R u=rwX,g=rwX,o-rwx "%s"'%(Config.backendSpool)
		p = System.execute(cmd)
		if p.returncode is not 0:
			Logger.debug("FS: following command '%s' returned %d => %s"%(cmd, p.returncode, p.stdout.read()))
			return False
		
		return True
예제 #9
0
	def existSomeWhere(self):
		try:
			pwd.getpwnam(self.login)
			return True
		except:
			pass
		
		cmd = "smbpasswd -e %s"%(self.login)
		p = System.execute(cmd)
		if p.returncode == 0:
			return True
		
		accessOK = False
		try:
			f = file(Config.dav_passwd_file, "r")
			accessOK = True
		except:
			pass
		if accessOK:
			lines = f.readlines()
			f.close
			
			for line in lines:
				if line.startswith(self.login+":"):
					return True
		
		return False
예제 #10
0
파일: Share.py 프로젝트: bloveing/openulteo
	def del_user(self, user):
		if user not in self.ro_users and user not in self.rw_users:
			return True
		
		ret = True
		if user in self.ro_users:
			cmd = "deluser %s %s_ro"%(user, self.group)
		else:
			cmd = "deluser %s %s_rw"%(user, self.group)
		
		p = System.execute(cmd)
		if p.returncode is not 0:
			ret = False
			Logger.error("FS: unable to del user in group")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
		
		htgroup = HTGroup(Config.dav_group_file)
		
		if user in self.ro_users:
			self.ro_users.remove(user)
			htgroup.delete(user, self.group+"_ro")
		if user in self.rw_users:
			self.rw_users.remove(user)
			htgroup.delete(user, self.group+"_rw")
		
		if (len(self.ro_users) + len(self.rw_users)) == 0:
			return self.disable()
		
		return True
예제 #11
0
파일: User.py 프로젝트: bloveing/openulteo
	def destroy(self):
		lock = FileLock("/tmp/user.lock")
		
		arg_remove = ""
		if self.check_remaining_mount_points():
			arg_remove = "--remove"
		
		cmd = "userdel --force %s %s"%(arg_remove, System.local_encode(self.name))
		
		retry = 5
		while retry !=0:
			lock.acquire()
			p = System.execute(cmd)
			lock.release()
			if p.returncode == 0:
				return True
			if p.returncode == 12:
				Logger.debug("mail dir error: '%s' return %d => %s"%(str(cmd), p.returncode, p.stdout.read()))
				return True
			
			Logger.debug("User delete of %s: retry %i"%(self.name, 6-retry))
			if p.returncode == 1 or p.returncode == 10: # an other process is creating a user
				Logger.debug("An other process is creating a user")
				retry -=1
				time.sleep(0.2)
				continue
			if p.returncode != 0:
				Logger.error("userdel return %d (%s)"%(p.returncode, p.stdout.read()))
				return False
		
		return True
예제 #12
0
	def getIcon(self, filename):
		Logger.debug("ApplicationsDetection::getIcon %s"%(filename))
		
		try:
			entry = xdg.DesktopEntry.DesktopEntry(filename)
		except xdg.Exceptions.Error as detail:
			Logger.warn("ApplicationsDetection::getIcon %s" % detail)
			return None
		
		iconName = entry.getIcon()
		if entry.getIcon() == u'':
			# icon field is not required for type=Application
			return None
		
		iconPath = xdg.IconTheme.getIconPath(iconName, size = 32, theme=Config.linux_icon_theme, extensions = ["png", "xpm"])
		if iconPath == None:
			return None
		
		bufFile = tempfile.mktemp(".png")		
		cmd = 'convert -resize 32x32 "%s" "%s"'%(iconPath, bufFile)
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.debug("getIcon cmd '%s' returned (%d): %s"%(cmd, p.returncode, p.stdout.read()))
			Logger.error("getIcon: imagemagick error")
			if os.path.exists(bufFile):
				os.remove(bufFile)
			
			return None
		
		try:
			f = file(bufFile, "r")
		except IOError, err:
			Logger.error("ApplicationsDetection::getIcon finale icon file '%s' does not exists"%(bufFile))
			return None
예제 #13
0
    def copySessionStart(self):
        profile_tmp_dir = os.path.join(Profile.TEMPORARY_PROFILE_PATH,
                                       self.session.user.name)
        if os.path.exists(profile_tmp_dir):
            System.rchown(profile_tmp_dir, self.session.user.name)

        if self.homeDir is None or not os.path.isdir(self.homeDir):
            return

        d = os.path.join(self.profile_mount_point, "conf.Linux")
        if not System.mount_point_exist(d):
            return

        if self.profile['profile_mode'] == 'advanced':
            return

        # Copy conf files
        d = self.transformToLocaleEncoding(d)
        cmd = self.getRsyncMethod(d, self.homeDir,
                                  Config.profile_filters_filename, True)
        Logger.debug("rsync cmd '%s'" % (cmd))

        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.error("Unable to copy conf from profile")
            Logger.debug(
                "Unable to copy conf from profile, cmd '%s' return %d: %s" %
                (cmd, p.returncode, p.stdout.read()))
예제 #14
0
파일: Share.py 프로젝트: poorboy/openulteo
    def del_user(self, user):
        if user not in self.ro_users and user not in self.rw_users:
            return True

        ret = True
        if user in self.ro_users:
            cmd = "deluser %s %s_ro" % (user, self.group)
        else:
            cmd = "deluser %s %s_rw" % (user, self.group)

        p = System.execute(cmd)
        if p.returncode is not 0:
            ret = False
            Logger.error("FS: unable to del user in group")
            Logger.debug("FS: command '%s' return %d: %s" %
                         (cmd, p.returncode, p.stdout.read().decode("UTF-8")))

        htgroup = HTGroup(Config.dav_group_file)

        if user in self.ro_users:
            self.ro_users.remove(user)
            htgroup.delete(user, self.group + "_ro")
        if user in self.rw_users:
            self.rw_users.remove(user)
            htgroup.delete(user, self.group + "_rw")

        if (len(self.ro_users) + len(self.rw_users)) == 0:
            return self.disable()

        return True
예제 #15
0
    def destroy(self):
        lock = FileLock("/tmp/user.lock")

        arg_remove = ""
        if self.check_remaining_mount_points():
            arg_remove = "--remove"

        cmd = "userdel --force %s %s" % (arg_remove,
                                         System.local_encode(self.name))

        retry = 5
        while retry != 0:
            lock.acquire()
            p = System.execute(cmd)
            lock.release()
            if p.returncode == 0:
                return True
            if p.returncode == 12:
                Logger.debug("mail dir error: '%s' return %d => %s" %
                             (str(cmd), p.returncode, p.stdout.read()))
                return True

            Logger.debug("User delete of %s: retry %i" %
                         (self.name, 6 - retry))
            if p.returncode == 1 or p.returncode == 10:  # an other process is creating a user
                Logger.debug("An other process is creating a user")
                retry -= 1
                time.sleep(0.2)
                continue
            if p.returncode != 0:
                Logger.error("userdel return %d (%s)" %
                             (p.returncode, p.stdout.read()))
                return False

        return True
예제 #16
0
    def mount_cifs(self, share, uri, dest):
        mount_env = {}
        if share.has_key("login") and share.has_key("password"):
            cmd = "mount -t cifs -o 'uid=%s,gid=0,%s,iocharset=utf8' //%s%s %s" % (
                self.session.user.name,
                self.DEFAULT_PERMISSION,
                uri.netloc,
                uri.path,
                dest,
            )
            mount_env["USER"] = share["login"]
            mount_env["PASSWD"] = share["password"]
        else:
            cmd = "mount -t cifs -o 'guest,uid=%s,gid=0,%s,iocharset=utf8' //%s%s %s" % (
                self.session.user.name,
                self.DEFAULT_PERMISSION,
                uri.netloc,
                uri.path,
                dest,
            )

        cmd = self.transformToLocaleEncoding(cmd)
        Logger.debug("Profile, share mount command: '%s'" % (cmd))
        p = System.execute(cmd, env=mount_env)
        if p.returncode != 0:
            Logger.debug("CIFS mount failed (status: %d) => %s" % (p.returncode, p.stdout.read()))
            return False

        return True
예제 #17
0
    def copySessionStart(self):
        profile_tmp_dir = os.path.join(Profile.TEMPORARY_PROFILE_PATH, self.session.user.name)
        if os.path.exists(profile_tmp_dir):
            System.rchown(profile_tmp_dir, self.session.user.name)

        if self.homeDir is None or not os.path.isdir(self.homeDir):
            return

        d = os.path.join(self.profile_mount_point, "conf.Linux")
        if not System.mount_point_exist(d):
            return

        if self.profile["profile_mode"] == "advanced":
            return

            # Copy conf files
        d = self.transformToLocaleEncoding(d)
        cmd = self.getRsyncMethod(d, self.homeDir, Config.profile_filters_filename, True)
        Logger.debug("rsync cmd '%s'" % (cmd))

        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.error("Unable to copy conf from profile")
            Logger.debug(
                "Unable to copy conf from profile, cmd '%s' return %d: %s" % (cmd, p.returncode, p.stdout.read())
            )
예제 #18
0
    def cleanup_repository(self):
        cmd = 'chown -R %s:%s "%s"' % (Config.uid, Config.gid,
                                       Config.backendSpool)
        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.debug("FS: following command '%s' returned %d => %s" %
                         (cmd, p.returncode, p.stdout.read()))
            return False

        cmd = 'chmod -R u=rwX,g=rwX,o-rwx "%s"' % (Config.backendSpool)
        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.debug("FS: following command '%s' returned %d => %s" %
                         (cmd, p.returncode, p.stdout.read()))
            return False

        return True
예제 #19
0
파일: User.py 프로젝트: bloveing/openulteo
	def create(self):
		lock = FileLock("/tmp/user.lock")
		
		# TODO get the default home in /etc/default/useradd
		default_home_dir = os.path.join(u"/home", self.name)
		home_dir = default_home_dir
		i = 0
		while os.path.exists(home_dir) and i < 100:
			home_dir = default_home_dir+"_%d"%(i)
			i+= 1

		if i > 0:
			Logger.warn("Unable to create home directory %s, the home is now %s"%(default_home_dir, home_dir))

		if os.path.exists(home_dir):
			Logger.error("Unable to find a valid home directory")
			return False
		
		cmd = u"useradd -m -d '%s' -k '%s'"%(home_dir, Config.linux_skel_directory)
		if self.infos.has_key("displayName"):
			cmd+= u""" --comment "%s,,," """%(self.infos["displayName"].replace('"', ""))
		
		groups = ["video", "audio", "pulse", "pulse-access", Config.linux_fuse_group]
		if self.infos.has_key("groups"):
			groups+= self.infos["groups"]
		cmd+= u" --groups %s"%(",".join(groups))
		
		cmd+= u" "+self.name
		
		retry = 5
		while retry !=0:
			if retry < 0:
				  Logger.error("ERROR: unable to add a new user")
			lock.acquire()
			p = System.execute(System.local_encode(cmd))
			lock.release()
			if p.returncode == 0:
				break
			
			Logger.debug("Add user :retry %i"%(6-retry))
			if p.returncode == 9: # user already exist
				Logger.error("User %s already exist"%(self.name))
				break;
			if p.returncode == 1: # an other process is creating a user
				Logger.error("An other process is creating a user")
				retry -=1
				time.sleep(0.2)
				continue
			if p.returncode != 0:
				Logger.error("UserAdd return %d (%s)"%(p.returncode, p.stdout.read()))
				return False
		
		
		if self.infos.has_key("password"):
			if not self.set_password():
				return False
		
		return self.post_create()
예제 #20
0
    def createShortcut(self, application_):
        png_file = os.path.join(self.spool, application_["id"] + ".png")
        ico_file = os.path.join(self.spool, application_["id"] + ".ico")

        cmd = """"%s" "%s" "%s" """ % ("png2ico.exe", ico_file, png_file)

        p = System.execute(cmd, True)
        if p.returncode != 0:
            Logger.warn("createShortcut following command returned %d: %s" %
                        (p.returncode, cmd))
            if os.path.exists(ico_file):
                os.remove(ico_file)

            return False

        if not os.path.exists(ico_file):
            Logger.warn("createShortcut: No ico file returned")
            return False

        (executable, arguments) = self.extract_command(application_["command"])

        pythoncom.CoInitialize()

        shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None,
                                              pythoncom.CLSCTX_INPROC_SERVER,
                                              shell.IID_IShellLink)
        try:
            shortcut.SetPath(executable)
        except:
            Logger.warn(
                "Unable to shortcut SetPath. Check if the following command is available on the system: '%s'"
                % (executable))
            return False

        if arguments is not None:
            try:
                shortcut.SetArguments(arguments)
            except:
                Logger.warn("Unable to shortcut SetArguments ('%s')" %
                            (arguments))
                return False

        if application_.has_key("directory"):
            try:
                shortcut.SetWorkingDirectory(application_["directory"])
            except:
                Logger.warn("Unable to shortcut SetWorkingDirectory ('%s')" %
                            (application_["directory"]))
                return False

        shortcut.SetIconLocation(ico_file, 0)
        #shortcut.SetWorkingDirectory(workingDirectory)
        shortcut.SetDescription(application_["description"])

        shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(
            os.path.join(self.spool, application_["id"] + ".lnk"), 0)
        return True
예제 #21
0
파일: Share.py 프로젝트: bloveing/openulteo
	def delete(self):
		cmd = "rm -rf %s"%(self.directory)
		p = System.execute(cmd)
		if p.returncode is not 0:
			Logger.error("FS: unable to del share")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
			return False
		
		return True
예제 #22
0
	def clean(self):
		cmd = 'htpasswd -D %s "%s"'%(Config.dav_passwd_file, self.login)
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.warn("FS: unable to remove user %s in 'clean' process"%(self.login))
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
		
		cmd = 'smbpasswd -x %s'%(self.login)
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.warn("FS: unable to remove user %s in 'clean' process"%(self.login))
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
		
		cmd = "userdel -f %s"%(self.login)
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.warn("FS: unable to remove user %s in 'clean' process"%(self.login))
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
예제 #23
0
파일: Share.py 프로젝트: poorboy/openulteo
    def delete(self):
        cmd = "rm -rf %s" % (self.directory)
        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.error("FS: unable to del share")
            Logger.debug("FS: command '%s' return %d: %s" %
                         (cmd, p.returncode, p.stdout.read().decode("UTF-8")))
            return False

        return True
예제 #24
0
파일: Role.py 프로젝트: bloveing/openulteo
	def get_enabled_usershares(self):
		p = System.execute("net usershare list")
		if p.returncode is not 0:
			Logger.error("FS: unable to 'net usershare list': %d => %s"%(p.returncode, p.stdout.read()))
			res = []
			try:
				res = os.listdir("/var/lib/samba/usershares/")
			except Exception, e:
				Logger.exception("FS: unable to list content of /var/lib/samba/usershares")
			return res
예제 #25
0
	def get_lsof(self, path):
		cmd = "lsof -t \"%s\""%(path)
		
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.warn("Failed to get the list of processus blocked on a share")
			return None
		
		res = p.stdout.read().decode("UTF-8")
		return res.split()
예제 #26
0
    def copySessionStop(self):
        # etre sur que le type est logoff !

        d = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, 0, 0)
        profile_tmp_dir = os.path.join(d, "ulteo", "profile",
                                       self.session.user.name)
        profile_tmp_dir = System.local_encode(profile_tmp_dir)
        profile_filter = System.local_encode(Config.profile_filters_filename)

        d = os.path.join(self.mountPoint,
                         "conf.Windows.%s" % System.getWindowsVersionName())
        trial = 5
        while not os.path.exists(d):
            try:
                os.makedirs(d)
            except OSError:
                trial -= 1
                if trial == 0:
                    Logger.exception("Failed to create directory %s" % d)
                    return False

                time.sleep(random.randint(1, 10) / 100.0)
                Logger.debug2(
                    "conf.Windows mkdir failed (concurrent access because of more than one ApS)"
                )
                continue

        # Copy user registry
        src = os.path.join(self.session.windowsProfileDir, "NTUSER.DAT")
        dst = os.path.join(d, "NTUSER.DAT")

        if os.path.exists(src):
            try:
                win32file.CopyFile(src, dst, False)
            except:
                Logger.error("Unable to copy registry to profile")
        else:
            Logger.warn("Weird: no NTUSER.DAT in user home dir ...")

        # Copy configuration File
        if self.profile['profile_mode'] == 'standard':
            cmd = self.getRsyncMethod(Profile.toCygPath(profile_tmp_dir),
                                      Profile.toCygPath(d),
                                      Profile.toCygPath(profile_filter))
            Logger.debug("rsync cmd '%s'" % (cmd))

            p = System.execute(cmd)
            if p.returncode is not 0:
                Logger.error("Unable to copy conf to profile")
                Logger.debug(
                    "Unable to copy conf to profile, cmd '%s' return %d: %s" %
                    (cmd, p.returncode, p.stdout.read()))

        if os.path.exists(profile_tmp_dir):
            System.DeleteDirectory(profile_tmp_dir)
예제 #27
0
    def check_remaining_mount_points(self):
        try:
            user = pwd.getpwnam(System.local_encode(self.name))
        except KeyError:
            return False

        mount_points = MountPoint.get_list(user.pw_dir)
        if mount_points is None:
            return False

        success = True
        for d in mount_points:
            path = System.local_encode(d)
            Logger.warn("Remaining mount point '%s'" % (path))
            cmd = 'umount "%s"' % (path)

            p = System.execute(cmd)
            if p.returncode == 0:
                continue

            Logger.warn(
                "Unable to unmount remaining mount point %s: force the unmount"
                % (path))
            Logger.debug('umount command "%s" return: %s' %
                         (cmd, p.stdout.read()))
            cmd = 'umount -l "%s"' % (path)
            p = System.execute(cmd)
            if p.returncode != 0:
                Logger.error(
                    "Unable to force the unmount remaining mount point %s" %
                    (path))
                Logger.debug('umount command "%s" return: %s' %
                             (cmd, p.stdout.read()))

            success = False

        if success == False:
            Logger.error(
                "Unable to unmount remaining mount point, home dir %s won't be purged"
                % (user.pw_dir))

        return success
예제 #28
0
    def get_lsof(self, path):
        cmd = "lsof -t \"%s\"" % (path)

        p = System.execute(cmd)
        if p.returncode != 0:
            Logger.warn(
                "Failed to get the list of processus blocked on a share")
            return None

        res = p.stdout.read().decode("UTF-8")
        return res.split()
예제 #29
0
    def perform(self):
        os.mkdir(self.directory)
        f_stdout = open(os.path.join(self.directory, "stdout"), "w")
        f_stderr = open(os.path.join(self.directory, "stderr"), "w")
        process_out = {"stdout": f_stdout, "stderr": f_stderr}

        p = System.execute(["apt-get", "update"], True, {}, process_out)
        if p.returncode != 0:
            f_stdout.close()
            f_stderr.close()
            return False

        apt_env = {
            "DEBIAN_FRONTEND": "noninteractive",
            "DEBIAN_PRIORITY": "critical",
            "DEBCONF_NONINTERACTIVE_SEEN": "true"
        }
        command = [
            "apt-get", "--yes", "--force-yes", "--option",
            "DPkg::Options::=--force-confold"
        ]
        if self.order == "upgrade":
            command.append("dist-upgrade")
        elif self.order == "install":
            command.append("install")
        elif self.order == "remove":
            command.append("autoremove")
            command.append("--purge")

        if self.order in ["install", "remove"]:
            command.extend(self.packages)

        p = System.execute(command, True, apt_env, process_out)
        if p.returncode != 0:
            f_stdout.close()
            f_stderr.close()
            return False

        f_stdout.close()
        f_stderr.close()
        return True
예제 #30
0
	def tuneGroups(self, username, groups):
		if groups is None or len(groups) == 0:
			return False
		
		groupString = ','.join(groups)
		cmd = u"usermod -G %s %s"%(groupString, username)
		p = System.execute(System.local_encode(cmd))
		if p.returncode != 0:
			Logger.error("UserAdd return %d (%s)"%(p.returncode, p.stdout.read()))
			return False
		
		return True
예제 #31
0
 def get_enabled_usershares(self):
     p = System.execute("net usershare list")
     if p.returncode is not 0:
         Logger.error("FS: unable to 'net usershare list': %d => %s" %
                      (p.returncode, p.stdout.read()))
         res = []
         try:
             res = os.listdir("/var/lib/samba/usershares/")
         except Exception, e:
             Logger.exception(
                 "FS: unable to list content of /var/lib/samba/usershares")
         return res
예제 #32
0
    def tuneGroups(self, username, groups):
        if groups is None or len(groups) == 0:
            return False

        groupString = ','.join(groups)
        cmd = u"usermod -G %s %s" % (groupString, username)
        p = System.execute(System.local_encode(cmd))
        if p.returncode != 0:
            Logger.error("UserAdd return %d (%s)" %
                         (p.returncode, p.stdout.read()))
            return False

        return True
예제 #33
0
파일: Share.py 프로젝트: poorboy/openulteo
    def disable(self):
        path = os.path.join(self.directory, ".htaccess")
        if not os.path.exists(path):
            ret = False
            Logger.error("FS: no .htaccess")
            Logger.debug("FS: no .htaccess '%s'" % (path))
        else:
            try:
                os.remove(path)
            except Exception:
                ret = False
                Logger.exception("FS: unable to remove .htaccess '%s'" % path)

        cmd = "net usershare delete %s" % (self.name)
        p = System.execute(cmd)
        ret = True
        if p.returncode is not 0:
            ret = False
            Logger.error("FS: unable to del share")
            Logger.debug("FS: command '%s' return %d: %s" %
                         (cmd, p.returncode, p.stdout.read().decode("UTF-8")))

        for i in ['rw', 'ro']:
            cmd = "groupdel  %s_%s" % (self.group, i)
            p = System.execute(cmd)
            if p.returncode is not 0:
                ret = False
                Logger.error("FS: unable to del group")
                Logger.debug(
                    "FS: command '%s' return %d: %s" %
                    (cmd, p.returncode, p.stdout.read().decode("UTF-8")))

        self.do_right_normalization()

        self.htaccess.delGroup(self.group)
        self.htaccess.save()

        self.active = False
        return ret
예제 #34
0
파일: Share.py 프로젝트: bloveing/openulteo
	def enable(self, mode):
		for i in ['ro', 'rw']:
			cmd = "groupadd  %s_%s"%(self.group, i)
			p = System.execute(cmd)
			if p.returncode is not 0:
				Logger.error("FS: unable to create group")
				Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
				return False
		
		cmd = 'net usershare add %s "%s" %s %s_ro:r,%s_rw:f guest_ok=n'%(self.name, self.frontDirectory, self.name, self.group, self.group)
		p = System.execute(cmd)
		if p.returncode is not 0:
			Logger.error("FS: unable to add share")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
			return False
		
		self.do_right_normalization()
		
		self.htaccess.addGroup(self.group)
		self.htaccess.save()
		
		self.active = True
		return True
예제 #35
0
파일: Share.py 프로젝트: bloveing/openulteo
	def disable(self):
		path = os.path.join(self.directory, ".htaccess")
		if not os.path.exists(path):
			ret = False
			Logger.error("FS: no .htaccess")
			Logger.debug("FS: no .htaccess '%s'"%(path))
		else:
			try:
				os.remove(path)
			except Exception:
				ret = False
				Logger.exception("FS: unable to remove .htaccess '%s'"%path)
		
		
		cmd = "net usershare delete %s"%(self.name)
		p = System.execute(cmd)
		ret = True
		if p.returncode is not 0:
			ret = False
			Logger.error("FS: unable to del share")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
		
		for i in ['rw', 'ro']:
			cmd = "groupdel  %s_%s"%(self.group, i)
			p = System.execute(cmd)
			if p.returncode is not 0:
				ret = False
				Logger.error("FS: unable to del group")
				Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
		
		self.do_right_normalization()
		
		self.htaccess.delGroup(self.group)
		self.htaccess.save()
		
		self.active = False
		return ret
예제 #36
0
	def createShortcut(self, application_):
		png_file = os.path.join(self.spool, application_["id"]+".png")
		ico_file = os.path.join(self.spool, application_["id"]+".ico")
		
		cmd = """"%s" "%s" "%s" """%("png2ico.exe", ico_file, png_file)
		
		p = System.execute(cmd, True)
		if p.returncode != 0:
			Logger.warn("createShortcut following command returned %d: %s"%(p.returncode, cmd))
			if os.path.exists(ico_file):
			  os.remove(ico_file)
			
			return False
		
		if not os.path.exists(ico_file):
			Logger.warn("createShortcut: No ico file returned")
			return False
		
		(executable, arguments) = self.extract_command(application_["command"])
		
		pythoncom.CoInitialize()
		
		shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
		try:
			shortcut.SetPath(executable)
		except:
			Logger.warn("Unable to shortcut SetPath. Check if the following command is available on the system: '%s'"%(executable))
			return False
		
		if arguments is not None:
			try:
				shortcut.SetArguments(arguments)
			except:
				Logger.warn("Unable to shortcut SetArguments ('%s')"%(arguments))
				return False
		
		if application_.has_key("directory"):
			try:
				shortcut.SetWorkingDirectory(application_["directory"])
			except:
				Logger.warn("Unable to shortcut SetWorkingDirectory ('%s')"%(application_["directory"]))
				return False
		
		shortcut.SetIconLocation(ico_file, 0)
		#shortcut.SetWorkingDirectory(workingDirectory)
		shortcut.SetDescription(application_["description"])
		
		shortcut.QueryInterface(pythoncom.IID_IPersistFile).Save(os.path.join(self.spool, application_["id"]+".lnk"), 0)
		return True
예제 #37
0
	def copySessionStop(self):
		# etre sur que le type est logoff !
		
		
		d = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_APPDATA, 0, 0)
		profile_tmp_dir = os.path.join(d, "ulteo", "profile", self.session.user.name)
		profile_tmp_dir = System.local_encode(profile_tmp_dir)
		profile_filter = System.local_encode(Config.profile_filters_filename)

		d = os.path.join(self.mountPoint, "conf.Windows.%s"%System.getWindowsVersionName())
		trial = 5
		while not os.path.exists(d):
			try:
				os.makedirs(d)
			except OSError:
				trial -= 1
				if trial == 0:
					Logger.exception("Failed to create directory %s"%d)
					return False
				
				time.sleep(random.randint(1,10)/100.0)	
				Logger.debug2("conf.Windows mkdir failed (concurrent access because of more than one ApS)")
				continue
		
		# Copy user registry
		src = os.path.join(self.session.windowsProfileDir, "NTUSER.DAT")
		dst = os.path.join(d, "NTUSER.DAT")
		
		if os.path.exists(src):
			try:
				win32file.CopyFile(src, dst, False)
			except:
				Logger.error("Unable to copy registry to profile")
		else:
			Logger.warn("Weird: no NTUSER.DAT in user home dir ...")
		
		
		# Copy configuration File
		if self.profile['profile_mode'] == 'standard':
			cmd = self.getRsyncMethod(Profile.toCygPath(profile_tmp_dir), Profile.toCygPath(d), Profile.toCygPath(profile_filter))
			Logger.debug("rsync cmd '%s'"%(cmd))
		
			p = System.execute(cmd)
			if p.returncode is not 0:
				Logger.error("Unable to copy conf to profile")
				Logger.debug("Unable to copy conf to profile, cmd '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read()))
		
		if os.path.exists(profile_tmp_dir):
			System.DeleteDirectory(profile_tmp_dir)
예제 #38
0
	def getDebianPackage(self, applications):
		for key in applications.keys():
			application = applications[key]
			
			cmd = 'dpkg -S "%s"'%(application["filename"])
			
			p = System.execute(cmd)
			if p.returncode != 0:
				continue
			
			out = p.stdout.read()
			if not ":" in out:
				continue
			
			(package, _) = out.split(":", 1)
			application["package"] = package
예제 #39
0
	def stop(self):
		if (len(self.path) == 0) or not os.path.ismount(self.path["spool"]):
			Logger.warn("FSBackend is already stopped")
			return True
		
		cmd = "umount \"%s\""%(self.path["spool"])
		Logger.debug("FSBackend release command '%s'"%(cmd))
		if not os.path.ismount(self.path["spool"]):
			return True
			
		p = System.execute(cmd)
		if p.returncode != 0:
			Logger.debug("FSBackend is busy")
			return False
		
		return True
예제 #40
0
    def stop(self):
        if (len(self.path) == 0) or not os.path.ismount(self.path["spool"]):
            Logger.warn("FSBackend is already stopped")
            return True

        cmd = "umount \"%s\"" % (self.path["spool"])
        Logger.debug("FSBackend release command '%s'" % (cmd))
        if not os.path.ismount(self.path["spool"]):
            return True

        p = System.execute(cmd)
        if p.returncode != 0:
            Logger.debug("FSBackend is busy")
            return False

        return True
예제 #41
0
    def getDebianPackage(self, applications):
        for key in applications.keys():
            application = applications[key]

            cmd = 'dpkg -S "%s"' % (application["filename"])

            p = System.execute(cmd)
            if p.returncode != 0:
                continue

            out = p.stdout.read()
            if not ":" in out:
                continue

            (package, _) = out.split(":", 1)
            application["package"] = package
예제 #42
0
파일: Role.py 프로젝트: bloveing/openulteo
	def cleanup_samba(self):
		# check samba conf
		ret = True
		
		for share in self.shares.values():
			if share.isActive():
				if not share.disable():
					ret = False
		
		for usershare in self.get_enabled_usershares():
			Logger.debug("FileServer:: Removing samba usershare '%s'"%(usershare))
			p = System.execute("net usershare delete %s"%(usershare))
			if p.returncode is not 0:
				Logger.error("FS: unable to 'net usershare delete': %d => %s"%(p.returncode, p.stdout.read()))
				ret = False
		
		return ret
예제 #43
0
    def cleanup_samba(self):
        # check samba conf
        ret = True

        for share in self.shares.values():
            if share.isActive():
                if not share.disable():
                    ret = False

        for usershare in self.get_enabled_usershares():
            Logger.debug("FileServer:: Removing samba usershare '%s'" %
                         (usershare))
            p = System.execute("net usershare delete %s" % (usershare))
            if p.returncode is not 0:
                Logger.error("FS: unable to 'net usershare delete': %d => %s" %
                             (p.returncode, p.stdout.read()))
                ret = False

        return ret
예제 #44
0
    def mount_webdav(self, share, uri, dest):
        davfs_conf = os.path.join(self.cifs_dst, "davfs.conf")
        davfs_secret = os.path.join(self.cifs_dst, "davfs.secret")
        if uri.scheme == "webdav":
            mount_uri = urlparse.urlunparse(
                ("http", uri.netloc, uri.path, uri.params, uri.query,
                 uri.fragment))
        else:
            mount_uri = urlparse.urlunparse(
                ("https", uri.netloc, uri.path, uri.params, uri.query,
                 uri.fragment))

        if not System.mount_point_exist(davfs_conf):
            f = open(davfs_conf, "w")
            f.write("ask_auth 0\n")
            f.write("use_locks 0\n")
            f.write("secrets %s\n" % (davfs_secret))
            f.close()

        if not System.mount_point_exist(davfs_secret):
            f = open(davfs_secret, "w")
            f.close()
            os.chmod(davfs_secret, stat.S_IRUSR | stat.S_IWUSR)

        if share.has_key("login") and share.has_key("password"):
            f = open(davfs_secret, "a")
            f.write("%s %s %s\n" %
                    (mount_uri, share["login"], share["password"]))
            f.close()

        cmd = "mount -t davfs -o 'conf=%s,uid=%s,gid=0,%s' '%s' %s" % (
            davfs_conf, self.session.user.name, self.DEFAULT_PERMISSION,
            mount_uri, dest)
        cmd = self.transformToLocaleEncoding(cmd)
        Logger.debug("Profile, sharedFolder mount command: '%s'" % (cmd))
        p = System.execute(cmd)
        if p.returncode != 0:
            Logger.debug("WebDAV mount failed (status: %d) => %s" %
                         (p.returncode, p.stdout.read()))
            return False

        return True
예제 #45
0
파일: Share.py 프로젝트: bloveing/openulteo
	def add_user(self, user, mode):
		if not self.active:
			self.enable(mode)
		
		cmd = "adduser %s %s_%s"%(user, self.group, mode)
		p = System.execute(cmd)
		if p.returncode is not 0:
			Logger.error("FS: unable to add user in group")
			Logger.debug("FS: command '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read().decode("UTF-8")))
			return False
		
		htgroup = HTGroup(Config.dav_group_file)
		
		if mode == 'rw':
			self.rw_users.append(user)
			htgroup.add(user, self.group+"_rw")
		else:
			self.ro_users.append(user)
			htgroup.add(user, self.group+"_ro")

		return True
예제 #46
0
    def mount_webdav(self, share, uri, dest):
        davfs_conf = os.path.join(self.cifs_dst, "davfs.conf")
        davfs_secret = os.path.join(self.cifs_dst, "davfs.secret")
        if uri.scheme == "webdav":
            mount_uri = urlparse.urlunparse(("http", uri.netloc, uri.path, uri.params, uri.query, uri.fragment))
        else:
            mount_uri = urlparse.urlunparse(("https", uri.netloc, uri.path, uri.params, uri.query, uri.fragment))

        if not System.mount_point_exist(davfs_conf):
            f = open(davfs_conf, "w")
            f.write("ask_auth 0\n")
            f.write("use_locks 0\n")
            f.write("secrets %s\n" % (davfs_secret))
            f.close()

        if not System.mount_point_exist(davfs_secret):
            f = open(davfs_secret, "w")
            f.close()
            os.chmod(davfs_secret, stat.S_IRUSR | stat.S_IWUSR)

        if share.has_key("login") and share.has_key("password"):
            f = open(davfs_secret, "a")
            f.write("%s %s %s\n" % (mount_uri, share["login"], share["password"]))
            f.close()

        cmd = "mount -t davfs -o 'conf=%s,uid=%s,gid=0,%s' '%s' %s" % (
            davfs_conf,
            self.session.user.name,
            self.DEFAULT_PERMISSION,
            mount_uri,
            dest,
        )
        cmd = self.transformToLocaleEncoding(cmd)
        Logger.debug("Profile, sharedFolder mount command: '%s'" % (cmd))
        p = System.execute(cmd)
        if p.returncode != 0:
            Logger.debug("WebDAV mount failed (status: %d) => %s" % (p.returncode, p.stdout.read()))
            return False

        return True
예제 #47
0
    def getIcon(self, filename):
        Logger.debug("ApplicationsDetection::getIcon %s" % (filename))

        try:
            entry = xdg.DesktopEntry.DesktopEntry(filename)
        except xdg.Exceptions.Error as detail:
            Logger.warn("ApplicationsDetection::getIcon %s" % detail)
            return None

        iconName = entry.getIcon()
        if entry.getIcon() == u'':
            # icon field is not required for type=Application
            return None

        iconPath = xdg.IconTheme.getIconPath(iconName,
                                             size=32,
                                             theme=Config.linux_icon_theme,
                                             extensions=["png", "xpm"])
        if iconPath == None:
            return None

        bufFile = tempfile.mktemp(".png")
        cmd = 'convert -resize 32x32 "%s" "%s"' % (iconPath, bufFile)
        p = System.execute(cmd)
        if p.returncode != 0:
            Logger.debug("getIcon cmd '%s' returned (%d): %s" %
                         (cmd, p.returncode, p.stdout.read()))
            Logger.error("getIcon: imagemagick error")
            if os.path.exists(bufFile):
                os.remove(bufFile)

            return None

        try:
            f = file(bufFile, "r")
        except IOError, err:
            Logger.error(
                "ApplicationsDetection::getIcon finale icon file '%s' does not exists"
                % (bufFile))
            return None
예제 #48
0
    def mount_cifs(self, share, uri, dest):
        mount_env = {}
        if share.has_key("login") and share.has_key("password"):
            cmd = "mount -t cifs -o 'uid=%s,gid=0,%s,iocharset=utf8' //%s%s %s" % (
                self.session.user.name, self.DEFAULT_PERMISSION, uri.netloc,
                uri.path, dest)
            mount_env["USER"] = share["login"]
            mount_env["PASSWD"] = share["password"]
        else:
            cmd = "mount -t cifs -o 'guest,uid=%s,gid=0,%s,iocharset=utf8' //%s%s %s" % (
                self.session.user.name, self.DEFAULT_PERMISSION, uri.netloc,
                uri.path, dest)

        cmd = self.transformToLocaleEncoding(cmd)
        Logger.debug("Profile, share mount command: '%s'" % (cmd))
        p = System.execute(cmd, env=mount_env)
        if p.returncode != 0:
            Logger.debug("CIFS mount failed (status: %d) => %s" %
                         (p.returncode, p.stdout.read()))
            return False

        return True
예제 #49
0
파일: Share.py 프로젝트: poorboy/openulteo
    def add_user(self, user, mode):
        if not self.active:
            self.enable(mode)

        cmd = "adduser %s %s_%s" % (user, self.group, mode)
        p = System.execute(cmd)
        if p.returncode is not 0:
            Logger.error("FS: unable to add user in group")
            Logger.debug("FS: command '%s' return %d: %s" %
                         (cmd, p.returncode, p.stdout.read().decode("UTF-8")))
            return False

        htgroup = HTGroup(Config.dav_group_file)

        if mode == 'rw':
            self.rw_users.append(user)
            htgroup.add(user, self.group + "_rw")
        else:
            self.ro_users.append(user)
            htgroup.add(user, self.group + "_ro")

        return True
예제 #50
0
	def force_stop(self):
		if (len(self.path) == 0) or not os.path.ismount(self.path["spool"]):
			Logger.warn("FSBackend is already stopped")
			return True
		
		cmd = "umount \"%s\""%(self.path["spool"])
		if not os.path.ismount(self.path["spool"]):
			return True
			
		p = System.execute(cmd)
		if p.returncode == 0:
			return True
		
		pids = self.get_lsof(self.path["spool"])
		
		for pid in pids:
			try:
				pid = int(pid)
				os.kill(pid, signal.SIGTERM)
				time.sleep(0.5)
				os.kill(pid, signal.SIGKILL)
			except Exception, e:
				if e.errno != errno.ESRCH:
					Logger.exception("Failed to kill processus %s"%pid)
예제 #51
0
    def force_stop(self):
        if (len(self.path) == 0) or not os.path.ismount(self.path["spool"]):
            Logger.warn("FSBackend is already stopped")
            return True

        cmd = "umount \"%s\"" % (self.path["spool"])
        if not os.path.ismount(self.path["spool"]):
            return True

        p = System.execute(cmd)
        if p.returncode == 0:
            return True

        pids = self.get_lsof(self.path["spool"])

        for pid in pids:
            try:
                pid = int(pid)
                os.kill(pid, signal.SIGTERM)
                time.sleep(0.5)
                os.kill(pid, signal.SIGKILL)
            except Exception, e:
                if e.errno != errno.ESRCH:
                    Logger.exception("Failed to kill processus %s" % pid)
예제 #52
0
        p = System.execute(cmd)
        if p.returncode == 0:
            return True

        pids = self.get_lsof(self.path["spool"])

        for pid in pids:
            try:
                pid = int(pid)
                os.kill(pid, signal.SIGTERM)
                time.sleep(0.5)
                os.kill(pid, signal.SIGKILL)
            except Exception, e:
                if e.errno != errno.ESRCH:
                    Logger.exception("Failed to kill processus %s" % pid)

        if not os.path.ismount(self.path["spool"]):
            return True

        Logger.error("FSBackend force the unmount of %s" %
                     (self.path["spool"]))
        cmd = "umount -l \"%s\"" % (self.path["spool"])
        p = System.execute(cmd)
        if p.returncode == 0:
            return True

        Logger.error("Unable to stop FSBackend %s" %
                     (p.stdout.read().decode("UTF-8")))
        return False
예제 #53
0
    def install_client(self):
        name = System.local_encode(self.user.name)

        self.clean_tmp_dir()

        d = os.path.join(self.SPOOL_USER, self.user.name)
        self.init_user_session_dir(d)

        os.chown(self.instanceDirectory, pwd.getpwnam(name)[2], -1)
        os.chown(self.user_session_dir, pwd.getpwnam(name)[2], -1)

        xdg_dir = os.path.join(d, "xdg")
        xdg_app_d = os.path.join(xdg_dir, "applications")
        if not os.path.isdir(xdg_app_d):
            os.makedirs(xdg_app_d)
            os.chown(xdg_app_d, pwd.getpwnam(name)[2], -1)

        self.install_desktop_shortcuts()

        System.execute('update-desktop-database "%s"' % (System.local_encode(xdg_app_d)))

        if self.parameters.has_key("desktop_icons") and self.parameters["desktop_icons"] == "1":
            path = os.path.join(xdg_app_d, ".show_on_desktop")
            f = file(path, "w")
            f.close()

        for f in os.listdir(xdg_app_d):
            os.chown(os.path.join(xdg_app_d, f), pwd.getpwnam(name)[2], -1)

        env_file_lines = []
        # Set the language
        if self.parameters.has_key("locale"):
            env_file_lines.append("LANG=%s.UTF-8\n" % (self.parameters["locale"]))
            env_file_lines.append("LC_ALL=%s.UTF-8\n" % (self.parameters["locale"]))
            env_file_lines.append("LANGUAGE=%s.UTF-8\n" % (self.parameters["locale"]))

        if self.parameters.has_key("timezone"):
            tz_file = "/usr/share/zoneinfo/" + self.parameters["timezone"]
            if not os.path.exists(tz_file):
                Logger.warn("Unsupported timezone '%s'" % (self.parameters["timezone"]))
                Logger.debug(
                    "Unsupported timezone '%s'. File '%s' does not exists" % (self.parameters["timezone"], tz_file)
                )
            else:
                env_file_lines.append("TZ=%s\n" % (tz_file))

        f = file(os.path.join(d, "env"), "w")
        f.writelines(env_file_lines)
        f.close()

        if self.profile is not None:
            profile_cache_dir = os.path.join(self.SPOOL_USER, "profiles", self.user.name)
            if not os.path.isdir(profile_cache_dir):
                os.makedirs(profile_cache_dir)
            os.chown(profile_cache_dir, pwd.getpwnam(name)[2], -1)

            if self.profile.mount() == False:
                if self.parameters.has_key("need_valid_profile") and self.parameters["need_valid_profile"] == "1":
                    return False

            shares_dir = os.path.join(d, "shares")
            if not os.path.isdir(shares_dir):
                os.makedirs(shares_dir)

            self.profile.register_shares(shares_dir)

        return True
예제 #54
0
    def create(self):
        lock = FileLock("/tmp/user.lock")

        # TODO get the default home in /etc/default/useradd
        default_home_dir = os.path.join(u"/home", self.name)
        home_dir = default_home_dir
        i = 0
        while os.path.exists(home_dir) and i < 100:
            home_dir = default_home_dir + "_%d" % (i)
            i += 1

        if i > 0:
            Logger.warn(
                "Unable to create home directory %s, the home is now %s" %
                (default_home_dir, home_dir))

        if os.path.exists(home_dir):
            Logger.error("Unable to find a valid home directory")
            return False

        cmd = u"useradd -m -d '%s' -k '%s'" % (home_dir,
                                               Config.linux_skel_directory)
        if self.infos.has_key("displayName"):
            cmd += u""" --comment "%s,,," """ % (
                self.infos["displayName"].replace('"', ""))

        groups = [
            "video", "audio", "pulse", "pulse-access", Config.linux_fuse_group
        ]
        if self.infos.has_key("groups"):
            groups += self.infos["groups"]
        cmd += u" --groups %s" % (",".join(groups))

        cmd += u" " + self.name

        retry = 5
        while retry != 0:
            if retry < 0:
                Logger.error("ERROR: unable to add a new user")
            lock.acquire()
            p = System.execute(System.local_encode(cmd))
            lock.release()
            if p.returncode == 0:
                break

            Logger.debug("Add user :retry %i" % (6 - retry))
            if p.returncode == 9:  # user already exist
                Logger.error("User %s already exist" % (self.name))
                break
            if p.returncode == 1:  # an other process is creating a user
                Logger.error("An other process is creating a user")
                retry -= 1
                time.sleep(0.2)
                continue
            if p.returncode != 0:
                Logger.error("UserAdd return %d (%s)" %
                             (p.returncode, p.stdout.read()))
                return False

        if self.infos.has_key("password"):
            if not self.set_password():
                return False

        return self.post_create()
예제 #55
0
class FSBackend:
    def __init__(self):
        self.path = {}
        self.pid = None
        self.sharesFile = "/etc/ulteo/rufs/shares.conf"
        self.pidFile = "/tmp/FSBackend.pid"

    def update_shares(self, share, quota, toAdd):
        if self.pid is None:
            try:
                f = open(self.pidFile, "r")
                pidStr = f.readline()
                if len(pidStr) == 0:
                    Logger.error("Invalid FSBackend pid: %s" % (pidStr))
                    return False

                self.pid = int(pidStr)
            except Exception:
                Logger.exception("Failed to get FSBackend pid")
                return False

        try:
            # TODO use a file lock
            f = open(self.sharesFile, "rw")
            lines = f.readlines()
            out = ""
            found = False
            f.close()

            for line in lines:
                compo = line.split(',')
                if len(compo) != 2:
                    # Check comment
                    strippedLine = line.strip()
                    if strippedLine.startswith("#") or strippedLine.startswith(
                            ";") or len(strippedLine) == 0:
                        out += line
                        continue

                    Logger.error(
                        "The following line '%s' is not properly formated, removing it"
                        % (line))
                    continue

                if share == compo[0].strip():
                    if toAdd:
                        # updating entry
                        out += "%s, %s\n" % (share, quota)
                        found = True
                    continue

                # we restore the entry
                out += line

            if not found and toAdd:
                # we append a new entry
                out += "%s, %s\n" % (share, quota)

            f = open(self.sharesFile, "w+")
            f.write(out)
            f.close()

            # force share data relaod
            os.kill(self.pid, signal.SIGHUP)
            return True

        except Exception:
            Logger.exception("Failed to add entry for the share '%s'" % share)
            return False

    def start(self):
        self.path["spool"] = Config.spool
        self.path["spool.real"] = Config.spool + ".real"
        if os.path.ismount(self.path["spool"]):
            Logger.warn("Failed to start FS backend, %s is already mounted" %
                        (self.path["spool"]))
            return False

        for p in self.path:
            path = self.path[p]
            try:
                os.makedirs(path)
            except OSError, err:
                if err[0] is not errno.EEXIST:
                    Logger.exception("Failed to create spool directory: %s" %
                                     path)
                    return False

            try:
                os.lchown(path, Config.uid, Config.gid)
            except OSError:
                Logger.exception("Unable to change file owner for '%s'" % path)
                return False

            if not os.path.exists(path):
                Logger.error("Spool directory %s do not exist" % (path))
                return False

        cmd = "RegularUnionFS \"%s\" \"%s\" -o user=%s -o fsconfig=%s" % (
            self.path["spool.real"], self.path["spool"], Config.user,
            Config.FSBackendConf)
        Logger.debug("Backend init command '%s'" % (cmd))
        p = System.execute(cmd)
        if p.returncode != 0:
            Logger.error(
                "Failed to initialize spool directory (status: %d) %s" %
                (p.returncode, p.stdout.read()))
            return False

        return True
예제 #56
0
	def getIcon(self, filename):
		Logger.debug("ApplicationsDetection::getIcon %s"%(filename))
		if not os.path.exists(filename):
			Logger.warn("ApplicationsDetection::getIcon no such file")
			return None
		
		pythoncom.CoInitialize()
		
		if win32process.IsWow64Process():
			wow64_value = Util.Wow64DisableWow64FsRedirection()
		
		shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
		shortcut.QueryInterface( pythoncom.IID_IPersistFile ).Load(filename)
		
		(iconLocation_src, iconId) = shortcut.GetIconLocation()
		iconLocation = win32api.ExpandEnvironmentStrings(iconLocation_src)
		
		if not os.path.exists(iconLocation) and win32process.IsWow64Process():
			iconLocation = Util.clean_wow64_path(iconLocation)
		
		if len(iconLocation) == 0 or not os.path.exists(iconLocation):
			Logger.debug("ApplicationsDetection::getIcon No IconLocation, use shortcut target")
			iconLocation = win32api.ExpandEnvironmentStrings(shortcut.GetPath(shell.SLGP_RAWPATH)[0])
			
			if not os.path.exists(iconLocation) and win32process.IsWow64Process():
				iconLocation = Util.clean_wow64_path(iconLocation)
			
			if len(iconLocation) == 0 or not os.path.exists(iconLocation):
				Logger.warn("ApplicationsDetection::getIcon Neither IconLocation nor shortcut target on %s (%s)"%(filename, iconLocation))
				if win32process.IsWow64Process():
					Util.Revert64DisableWow64FsRedirection(wow64_value)
				
				return None
		
		if win32process.IsWow64Process():
			Util.Revert64DisableWow64FsRedirection(wow64_value)
		
		path_tmp = tempfile.mktemp()
		
		path_bmp = path_tmp + ".bmp"
		path_png = path_tmp + ".png"
		
		
		cmd = """"%s" "%s,%d" "%s" """%("exeIcon2png.exe", iconLocation, iconId, path_png)
		p = System.execute(cmd, True)
		if p.returncode != 0:
			Logger.warn("Unable to extract icon, use alternative method")
			Logger.debug("ApplicationsDetection::getIcon following command returned %d: %s"%(p.returncode, cmd))
			if os.path.exists(path_png):
				os.remove(path_png)
			
			cmd = """"%s" "%s" "%s" """%("extract_icon.exe", iconLocation, path_bmp)
			
			p = System.execute(cmd, True)
			if p.returncode != 0:
				Logger.warn("Unable to extract icon with the alternative method")
				Logger.debug("ApplicationsDetection::getIcon following command returned %d: %s"%(p.returncode, cmd))
				if os.path.exists(path_bmp):
					os.remove(path_bmp)
				
				return None
			
			if not os.path.exists(path_bmp):
				Logger.debug("ApplicationsDetection::getIcon No bmp file returned")
				return None
			
			
			cmd = """"%s" -Q -O "%s" "%s" """%("bmp2png.exe", path_png, path_bmp)
			p = System.execute(cmd, True)
			if p.returncode != 0:
				Logger.warn("Unable to extract icon with the alternative method")
				Logger.debug("ApplicationsDetection::getIcon following command returned %d: %s"%(p.returncode, cmd))
				os.remove(path_bmp)
				if os.path.exists(path_png):
					os.remove(path_png)
				
				return None
			
			os.remove(path_bmp)
		
		if not os.path.exists(path_png):
			Logger.debug("ApplicationsDetection::getIcon No png file returned")
			return None
		
		f = open(path_png, 'rb')
		buf = f.read()
		f.close()
		
		os.remove(path_png)
		return buf