示例#1
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
示例#2
0
def copyDirOverride(src, dst, exception=None):
    src = System.local_encode(src)
    dst = System.local_encode(dst)
    if not os.path.isdir(src):
        return

    if exception is None:
        exception = []

    try:
        attr = win32file.GetFileAttributes(src)
        if attr & FILE_ATTRIBUTE_SYSTEM and attr & FILE_ATTRIBUTE_REPARSE_POINT:
            return
        win32file.SetFileAttributes(dst, attr)
    except:
        #print "Unable to setAttribute of",dst
        pass

    if not os.path.isdir(dst):
        os.makedirs(dst)

    dirs = None
    try:
        dirs = os.listdir(src)
    except Exception, err:
        return
示例#3
0
def copyDirOverride(src, dst, exception=None):
	src = System.local_encode(src)
	dst = System.local_encode(dst)
	if not os.path.isdir(src):
		return
	
	if exception is None:
		exception = []
	
	try:
		attr = win32file.GetFileAttributes(src)
		if attr & FILE_ATTRIBUTE_SYSTEM and attr & FILE_ATTRIBUTE_REPARSE_POINT:
			return 
		win32file.SetFileAttributes(dst, attr)
	except:
		#print "Unable to setAttribute of",dst
		pass
	
	if not os.path.isdir(dst):
		os.makedirs(dst)

	dirs = None
	try:
		dirs = os.listdir(src)
	except Exception, err:
		return
示例#4
0
	def install_client(self):
		name = System.local_encode(self.user.name)
		
		d = os.path.join(self.SPOOL_USER, self.user.name)
		self.init_user_session_dir(d)
		self.install_desktop_shortcuts()
		
		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)
		
		for p in ["icons", "pixmaps", "mime", "themes"]:
			src_dir = os.path.join("/usr/share/", p)
			dst_dir =  os.path.join(xdg_dir, p)
			
			os.symlink(src_dir, dst_dir)
		
		
		os.system('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()
		
		
		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:
			self.profile.mount()
			
			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
示例#5
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)
示例#6
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)
示例#7
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()
			s,o = commands.getstatusoutput(cmd)
			lock.release()
		        if s == 0:
		                return True
                        if s == 3072:
                                Logger.debug("mail dir error: '%s' return %d => %s"%(str(cmd), s, o))
                                return True

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

		return True
示例#8
0
    def exists(self):
        try:
            pwd.getpwnam(System.local_encode(self.name))
        except KeyError:
            return False

        return True
示例#9
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
示例#10
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
示例#11
0
	def exists(self):
		try:
			pwd.getpwnam(System.local_encode(self.name))
		except KeyError:
			return False
		
		return True
示例#12
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()
示例#13
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
示例#14
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
示例#15
0
    def post_create(self):
        name = System.local_encode(self.name)

        if self.infos.has_key("shell"):
            xrdp.UserSetShell(name, self.infos["shell"])
            xrdp.UserAllowUserShellOverride(name, True)

        try:
            self.home = pwd.getpwnam(name)[5]
        except KeyError:
            return False
        return True
示例#16
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
示例#17
0
    def exec_command(cls, cmd, wait=True):
        subprocess_args = {}
        subprocess_args["stdin"] = subprocess.PIPE
        subprocess_args["stdout"] = subprocess.PIPE
        subprocess_args["stderr"] = subprocess.STDOUT
        subprocess_args["shell"] = True
        subprocess_args["preexec_fn"] = os.setpgrp

        p = subprocess.Popen(System.local_encode(cmd), **subprocess_args)
        if wait:
            p.wait()

        return p
示例#18
0
	def exec_command(cls, cmd, wait=True):
			subprocess_args = {}
			subprocess_args["stdin"] = subprocess.PIPE
			subprocess_args["stdout"] = subprocess.PIPE
			subprocess_args["stderr"] = subprocess.STDOUT
			subprocess_args["shell"] = True
			subprocess_args["preexec_fn"] = os.setpgrp
			
			p = subprocess.Popen(System.local_encode(cmd), **subprocess_args)
			if wait:
					p.wait()
			
			return p
示例#19
0
	def post_create(self):
		name = System.local_encode(self.name)
		
		if self.infos.has_key("shell"):
			xrdp.UserSetShell(name, self.infos["shell"])
			xrdp.UserAllowUserShellOverride(name, True)
		
		
		try:		
			self.home = pwd.getpwnam(name)[5]
		except KeyError:
			return False
		return True
示例#20
0
def setup_apps(reset=False):
    """
	"""
    from ApplicationsRepository import ApplicationsRepository
    if reset:
        ApplicationsRepository.reset()

    sm_request_manager = SMRequestManager()
    webapps_dom = sm_request_manager.get_webapps()

    if webapps_dom == None:
        return True

    for webapp_dom in webapps_dom.childNodes:
        config_nodes = webapp_dom.getElementsByTagName('configuration')
        if len(config_nodes) < 1:
            continue

        config = json.loads(config_nodes[0].firstChild.data)
        if config.keys() < 1:
            continue

        app_id = webapp_dom.getAttribute('id')
        app_name = config.keys()[0]
        try:
            app_id = System.local_encode(app_id)
            app_name = System.local_encode(app_name)
            appl = setup_app(config, app_id, app_name, Config.mode)
        except:
            Logger.exception(
                "Setting up an application failed. Correct its configuration.")
            continue
        if appl is None:
            continue
        ApplicationsRepository.register(appl)

    Logger.info("Configured %s webapp(s)" % len(ApplicationsRepository.list()))
    return True
示例#21
0
    def clean_tmp_dir(self):
        # Purge TMP directory
        uid = pwd.getpwnam(System.local_encode(self.user.name))[2]
        for f in os.listdir("/tmp"):
            filename = os.path.join("/tmp", f)
            s = os.lstat(filename)
            if s.st_uid != uid:
                continue

            try:
                if os.path.isdir(filename):
                    shutil.rmtree(filename)
                else:
                    os.remove(filename)
            except:
                Logger.exception("Unable to remove %s" % (filename))
示例#22
0
    def clean_tmp_dir(self):
        # Purge TMP directory
        uid = pwd.getpwnam(System.local_encode(self.user.name))[2]
        for f in os.listdir("/tmp"):
            filename = os.path.join("/tmp", f)
            s = os.lstat(filename)
            if s.st_uid != uid:
                continue

            try:
                if os.path.isdir(filename):
                    shutil.rmtree(filename)
                else:
                    os.remove(filename)
            except:
                Logger.exception("Unable to remove %s" % (filename))
示例#23
0
	def check_remaining_mount_points(self):
		try:
			user = pwd.getpwnam(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:
			Logger.warn("Remaining mount point '%s'"%(d))
			cmd = 'umount "%s"'%(System.local_encode(d))
			
			s,o = commands.getstatusoutput(cmd)
			if s != 0:
				Logger.error("Unable to unmount remaining mount point, home dir %s won't be purged"%(user.pw_dir))
				Logger.debug('umount command "%s" return: %s'%(cmd,  o))
				success = False
		
		return success
示例#24
0
	def createShortcut(self, application_):
		lines = []
		lines.append("[Desktop Entry]")
		lines.append("Type=Application")
		lines.append("Terminal=false")
		lines.append("Version=1.0")
		lines.append("Icon=%s"%(os.path.join(self.spool, application_["id"]+".png")))
		lines.append("Name=%s"%(application_["name"]))
		lines.append("Comment=%s"%(application_["description"]))
		lines.append("Exec=%s"%(application_["command"]))
		if application_.has_key("directory"):
			lines.append("Path=%s"%(application_["directory"]))
		
		lines.append("MimeType=%s"%(";".join(application_["mimetypes"])))
		#parser = ConfigParser.ConfigParser()
		#parser.add_section("Desktop Entry")
		#parser.set("Desktop Entry", "Type", "Application")
		#parser.set("Desktop Entry", "Version", "1.0")
		#parser.set("Desktop Entry", "Terminal", "false")
		#parser.set("Desktop Entry", "Icon", os.path.join(self.spool, application_["id"]+".png"))
		#parser.set("Desktop Entry", "Name", application_["name"])
		#parser.set("Desktop Entry", "Comment", application_["description"])
		#parser.set("Desktop Entry", "Exec", application_["command"])
		#parser.set("Desktop Entry", "MimeType", ";".join(application_["mimetypes"]))
		
		path = os.path.join(self.spool, application_["id"]+".desktop")
		try:
			f= file(path, "w")
		except:
			Logger.error("Unable to open file '%s'"%(path))
			return False
		
		f.writelines([System.local_encode(s)+"\n" for s in lines])
		#parser.write(f)
		f.close()
		
		return True
示例#25
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()
示例#26
0
	def copySessionStart(self):
		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)
		
		for f in [self.DesktopDir, self.DocumentsDir]:
			d = os.path.join(self.mountPoint, "Data", f)
			
			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("Profile mkdir failed (concurrent access because of more than one ApS)")
					continue
		
		
		d = os.path.join(self.mountPoint, "conf.Windows.%s"%System.getWindowsVersionName())
		if os.path.exists(d):
			
			# clean temporary file used by windows to load registry
			dirs = None
			try:
				dirs = os.listdir(d)
			except Exception:
				Logger.exception("Unable to list content of the directory %s"%d)
				return
			
			for content in dirs:
				if content.startswith(r"NTUSER.DAT.LOG") or content.startswith(r"NTUSER.DAT{"):
					try :
						path = os.path.join(d, content)
						os.remove(path)
					except Exception:
						Logger.exception("Unable to delete %s"%path)
			
			# Copy user registry
			
			src = os.path.join(d, "NTUSER.DAT")
			if os.path.exists(src):
				dst = os.path.join(self.session.windowsProfileDir, "NTUSER.DAT")
				
				rand = random.randrange(10000, 50000)
				
				hiveName_src = "OVD_%s_%d"%(str(self.session.id), rand)
				win32api.RegLoadKey(win32con.HKEY_USERS, hiveName_src, src)
				
				hiveName_dst = "OVD_%s_%d"%(str(self.session.id), rand+1)
				win32api.RegLoadKey(win32con.HKEY_USERS, hiveName_dst, dst)
				
				hkey_src = win32api.RegOpenKey(win32con.HKEY_USERS, r"%s"%(hiveName_src), 0, win32con.KEY_ALL_ACCESS)
				hkey_dst = win32api.RegOpenKey(win32con.HKEY_USERS, r"%s"%(hiveName_dst), 0, win32con.KEY_ALL_ACCESS)
				
				Reg.CopyTree(hkey_src, "Software", hkey_dst, self.registry_copy_blacklist)
				
				win32api.RegCloseKey(hkey_src)
				win32api.RegCloseKey(hkey_dst)
				
				win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName_src)
				win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName_dst)
			
			# Copy configuration File
			if self.profile['profile_mode'] == 'standard':
				cmd = self.getRsyncMethod(Profile.toCygPath(d), Profile.toCygPath(profile_tmp_dir), 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 from profile")
                        		Logger.debug("Unable to copy conf from profile, cmd '%s' return %d: %s"%(cmd, p.returncode, p.stdout.read()))
			
		if os.path.exists(profile_tmp_dir):
			System.rchown(profile_tmp_dir, self.session.user.name)
示例#27
0
 def add(self, level, message):
     log = "%s [%s] %s" % (time.strftime("%Y-%m-%d %H:%M:%S"), level,
                           message)
     self.log.append(System.local_encode(log))
示例#28
0
	def add(self, level, message):
		log = "%s [%s] %s"%(time.strftime("%Y-%m-%d %H:%M:%S"), level, message)
		self.log.append(System.local_encode(log))
示例#29
0
	def getSessionID(username_):
		return xrdp.SessionGetId(System.local_encode(username_))
示例#30
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
示例#31
0
	def getSessionID(username_):
		return xrdp.SessionGetId(System.local_encode(username_))
示例#32
0
    def copySessionStart(self):
        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)

        for f in [self.DesktopDir, self.DocumentsDir]:
            d = os.path.join(self.mountPoint, "Data", f)

            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(
                        "Profile mkdir failed (concurrent access because of more than one ApS)"
                    )
                    continue

        d = os.path.join(self.mountPoint,
                         "conf.Windows.%s" % System.getWindowsVersionName())
        if os.path.exists(d):

            # clean temporary file used by windows to load registry
            dirs = None
            try:
                dirs = os.listdir(d)
            except Exception:
                Logger.exception("Unable to list content of the directory %s" %
                                 d)
                return

            for content in dirs:
                if content.startswith(r"NTUSER.DAT.LOG") or content.startswith(
                        r"NTUSER.DAT{"):
                    try:
                        path = os.path.join(d, content)
                        os.remove(path)
                    except Exception:
                        Logger.exception("Unable to delete %s" % path)

            # Copy user registry

            src = os.path.join(d, "NTUSER.DAT")
            if os.path.exists(src):
                dst = os.path.join(self.session.windowsProfileDir,
                                   "NTUSER.DAT")

                rand = random.randrange(10000, 50000)

                hiveName_src = "OVD_%s_%d" % (str(self.session.id), rand)
                win32api.RegLoadKey(win32con.HKEY_USERS, hiveName_src, src)

                hiveName_dst = "OVD_%s_%d" % (str(self.session.id), rand + 1)
                win32api.RegLoadKey(win32con.HKEY_USERS, hiveName_dst, dst)

                hkey_src = win32api.RegOpenKey(win32con.HKEY_USERS,
                                               r"%s" % (hiveName_src), 0,
                                               win32con.KEY_ALL_ACCESS)
                hkey_dst = win32api.RegOpenKey(win32con.HKEY_USERS,
                                               r"%s" % (hiveName_dst), 0,
                                               win32con.KEY_ALL_ACCESS)

                Reg.CopyTree(hkey_src, "Software", hkey_dst,
                             self.registry_copy_blacklist)

                win32api.RegCloseKey(hkey_src)
                win32api.RegCloseKey(hkey_dst)

                win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName_src)
                win32api.RegUnLoadKey(win32con.HKEY_USERS, hiveName_dst)

            # Copy configuration File
            if self.profile['profile_mode'] == 'standard':
                cmd = self.getRsyncMethod(Profile.toCygPath(d),
                                          Profile.toCygPath(profile_tmp_dir),
                                          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 from profile")
                    Logger.debug(
                        "Unable to copy conf from profile, cmd '%s' return %d: %s"
                        % (cmd, p.returncode, p.stdout.read()))

        if os.path.exists(profile_tmp_dir):
            System.rchown(profile_tmp_dir, self.session.user.name)