Esempio n. 1
0
def clone(srcFile, dstFile, path, args):
	pythoncom.CoInitialize()
	
	shortcut_src = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
	shortcut_src.QueryInterface(pythoncom.IID_IPersistFile).Load(srcFile)
	
	iconLocation = shortcut_src.GetIconLocation()[0]
	if len(iconLocation) == 0:
		iconLocation = shortcut_src.GetPath(0)[0]
	
	workingDirectory = shortcut_src.GetWorkingDirectory()
	description = shortcut_src.GetDescription()
	
	
	shortcut_dst = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink)
	try:
		shortcut_dst.SetPath(path)
	except:
		Logger.warn("LnkFile::clone: unable to setPath. Check that the following command is available on the system: '%s'"%(path))
		return False
	
	shortcut_dst.SetArguments(args)
	shortcut_dst.SetIconLocation(iconLocation, 0)
	shortcut_dst.SetWorkingDirectory(workingDirectory)
	shortcut_dst.SetDescription(description)
	
	shortcut_dst.QueryInterface(pythoncom.IID_IPersistFile).Save(dstFile, 0)
	return True
	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
Esempio n. 3
0
    def rewrite_xml(self, body):
        try:
            session = parser.XML(body)
            if session.tag.lower() != 'session':
                raise Exception("not a 'session' XML response")
        except Exception:
            Logger.exception("Gateway:: parsing XML session failed")
            return None

        session.set('mode_gateway', 'on')
        for server in session.findall('server'):
            port = Protocol.RDP

            if server.attrib.has_key("port"):
                try:
                    port = int(server.attrib["port"])
                except ValueError, err:
                    Logger.warn(
                        "Gateway:: Invalid protocol: server port attribute is not a digit (%s)"
                        % (server.attrib["port"]))

            token = self.f_ctrl.send(
                ('insert_token', (server.attrib['fqdn'], port)))
            server.set('token', token)
            del server.attrib['fqdn']
            if server.attrib.has_key("port"):
                del server.attrib["port"]
Esempio n. 4
0
    def req_manage(self, request):

        try:
            document = minidom.parseString(request["data"])
            rootNode = document.documentElement

            if rootNode.nodeName != "vm":
                raise Exception("invalid root node")

        except:
            Logger.warn("Invalid xml input !!")
            doc = Document()
            rootNode = doc.createElement('error')
            rootNode.setAttribute("id", "name")
            doc.appendChild(rootNode)

            return self.req_answer(doc)

        vname = rootNode.getAttribute("id")
        action = rootNode.getAttribute("action")
        ret = self.role_instance.manage("ulteo_ovd_" + vname, action)

        doc = Document()
        rootNode = doc.createElement("vm")
        rootNode.setAttribute("status", ret)
        doc.appendChild(rootNode)

        return self.req_answer(doc)
Esempio n. 5
0
	def req_user_logout(self, request):
		try:
			document = minidom.parseString(request["data"])
			rootNode = document.documentElement
			
			if rootNode.nodeName != "user":
				raise Exception("invalid root node")
			
			if not rootNode.hasAttribute("login"):
				raise Exception("invalid root node")
			
			login = rootNode.getAttribute("login")
			
		except:
			Logger.warn("Invalid xml input !!")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		
		try:
			ret = Platform.TS.getSessionID(login)
		except Exception,err:
			Logger.error("RDP server dialog failed ... ")
			Logger.debug("Dialog::req_user_logout: %s"%(str(err)))
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "internalerror")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
Esempio n. 6
0
	def req_debian(self, request):
		try:
			document = minidom.parseString(request["data"])
			rootNode = document.documentElement
			if rootNode.nodeName != "debian":
				raise Exception("invalid root node")
			
			request = rootNode.getAttribute("request")
			if request not in ["upgrade", "install", "remove", "available"]:
				raise Exception("usage")
			
			packageNodes = rootNode.getElementsByTagName("package")
			if request in ["install", "remove"] and len(packageNodes)==0:
				raise Exception("usage")
			
			packages = []
			for packageNode in packageNodes:
				packages.append(packageNode.getAttribute("name"))
		
		except Exception, err:
			Logger.warn("Invalid xml input: "+str(err))
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
Esempio n. 7
0
	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
Esempio n. 8
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
Esempio n. 9
0
	def send_server_status(self, status):
		doc = Document()
		rootNode = doc.createElement('server')
		rootNode.setAttribute("status", status)
		doc.appendChild(rootNode)
		response = self.send_packet("/server/status", doc)
		if response is False:
			Logger.warn("SMRequest::send_server_status Unable to send packet")
			return False
		
		document = self.get_response_xml(response)
		if document is None:
			Logger.warn("SMRequest::send_server_status response not XML")
			return False
		
		rootNode = document.documentElement
		
		if rootNode.nodeName != "server":
			Logger.error("SMRequest::send_server_status response not valid %s"%(rootNode.toxml()))
			return False
		
		if not rootNode.hasAttribute("name") or rootNode.getAttribute("name") != self.name:
			Logger.error("SMRequest::send_server_status response invalid name")
			return False
		
		if not rootNode.hasAttribute("status") or rootNode.getAttribute("status") != status:
			Logger.error("SMRequest::send_server_status response invalid status")
			return False
		
		return True
Esempio n. 10
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
Esempio n. 11
0
	def destroy(self):
		sid = self.getSid()
		if sid is None:
			return
		
		succefulDelete = False
		try:
			win32profile.DeleteProfile(sid)
			succefulDelete = True
		except:
			pass
		
		if not succefulDelete:
			if not self.unload(sid):
				Logger.error("Unable to unload User reg key for user %s"%(self.name))
				return False
			try:
				win32profile.DeleteProfile(sid)
				succefulDelete = True
			except Exception, e:
				Logger.warn("Unable to unload user reg: %s"%(str(e)))
				
				try:
					path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%s"%(sid)
					Reg.DeleteTree(win32con.HKEY_LOCAL_MACHINE, path)
				except Exception, err:
					Logger.warn("RegDeleteTree of %s return: %s"%(path, str(err)))
					return False
Esempio n. 12
0
	def req_debian_id(self, req):
		try:
			(rid, request) = req.split("/", 2)
			req = self.role_instance.apt.get(rid)
			if req is None:
				req = Apt.Request()
				req.status = "unknown"
				return self.req_answer(self.debian_request2xml(rid, req))
			
			if request == "status":
				return self.req_answer(self.debian_request2xml(rid, req))
			
			elif request in ["stdout", "stderr"]:
				response = {}
				response["code"] = httplib.OK
				response["Content-Type"] = "text/plain"
				response["data"] = req.getLog(request)
				return response
			
			else:
				raise Exception("usage")
			
		except Exception, err:
			Logger.warn("Invalid xml input: "+str(err))
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
Esempio n. 13
0
    def uninstall_client(self):
        if not self.succefully_initialized:
            return

        self.archive_shell_dump()

        if self.profile is not None and self.profile.hasProfile():
            if not self.profile.mount():
                Logger.warn(
                    "Unable to mount profile at uninstall_client of session " +
                    self.id)
            else:
                self.profile.copySessionStop()

                desktop_path = os.path.join(self.profile.mountPoint,
                                            self.profile.DesktopDir)
                self.cleanupShortcut(desktop_path)

                for shortcut in self.installedShortcut:
                    dstFile = os.path.join(self.profile.mountPoint,
                                           self.profile.DesktopDir, shortcut)
                    if os.path.exists(dstFile):
                        os.remove(dstFile)

                if not self.profile.umount():
                    Logger.error(
                        "Unable to umount profile at uninstall_client of session "
                        + self.id)

        self.domain.onSessionEnd()
        return True
Esempio n. 14
0
    def uninstall_client(self):
        if not self.succefully_initialized:
            return

        self.archive_shell_dump()

        if self.profile is not None and self.profile.hasProfile():
            if not self.profile.mount():
                Logger.warn("Unable to mount profile at uninstall_client of session " + self.id)
            else:
                self.profile.copySessionStop()

                desktop_path = os.path.join(self.profile.mountPoint, self.profile.DesktopDir)
                self.cleanupShortcut(desktop_path)

                for shortcut in self.installedShortcut:
                    dstFile = os.path.join(self.profile.mountPoint, self.profile.DesktopDir, shortcut)
                    if os.path.exists(dstFile):
                        os.remove(dstFile)

                if not self.profile.umount():
                    Logger.error("Unable to umount profile at uninstall_client of session " + self.id)

        self.domain.onSessionEnd()
        return True
Esempio n. 15
0
    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
Esempio n. 16
0
    def handle(self):
        self.role.kill_mutex.acquire()

        best_proc = None
        for pid, proc in self.role.processes.items():
            ctrl = proc[0][1]
            nb_conn = ctrl.send('nb_conn')
            self.role.processes[pid][1] = nb_conn
            if nb_conn < Config.max_connection:
                best_proc = pid
                break
        if best_proc is None:
            if len(self.role.processes) < Config.max_process:
                best_proc = self.role.create_process()
            else:
                best_proc = min(self.role.processes,
                                key=lambda pid: self.role.processes[pid][1])
                Logger.warn(
                    "WebApps service has reached the open connections limit")

        ctrl = self.role.processes[best_proc][0][1]
        pickled_sock = pickle.dumps(reduce_socket(self.request)[1])
        ctrl.send(('socket', pickled_sock))

        self.role.kill_mutex.release()
Esempio n. 17
0
    def mount(self):
        buf = self.getFreeLetter()
        if buf is None:
            Logger.warn("No drive letter available: unable to init profile")
            return

        self.mountPoint = "%s:" % (buf)

        try:
            win32wnet.WNetAddConnection2(
                win32netcon.RESOURCETYPE_DISK, self.mountPoint,
                r"\\%s\%s" % (self.profile["server"], self.profile["dir"]),
                None, self.profile["login"], self.profile["password"])

        except Exception, err:
            Logger.error("Unable to mount drive")
            Logger.debug("WNetAddConnection2 return %s" % (err))
            Logger.debug(
                "Unable to mount drive, '%s', try the net use command equivalent: '%s'"
                %
                (str(err), "net use %s \\\\%s\\%s %s /user:%s" %
                 (self.mountPoint, self.profile["server"], self.profile["dir"],
                  self.profile["password"], self.profile["login"])))

            self.mountPoint = None
            return False
Esempio n. 18
0
	def SvcDoRun(self):
		self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
		#win32evtlogutil.ReportEvent(self.log_type, 2, eventType=win32evtlog.EVENTLOG_INFORMATION_TYPE, strings=["Message d'arret"])
		
		if not SlaveServer.init(self):
			Logger.error("Unable to initialize SlaveServer")
			SlaveServer.stop(self)
			return
		
		self.ReportServiceStatus(win32service.SERVICE_RUNNING)
		
		inited = False
		rc = win32event.WAIT_TIMEOUT
		while rc == win32event.WAIT_TIMEOUT:
			if not inited:
				ret = SlaveServer.push_production(self)
				if ret:
					inited = True
					Logger.info("SlaveServer started")
				else:
					Logger.warn("Session Manager not connected. Sleeping for a while ...")
			
			if inited:
				SlaveServer.loop_procedure(self)
			
			rc = win32event.WaitForSingleObject(self.hWaitStop, 30 * 1000)
		
		if not self.stopped:
			SlaveServer.stop(self)
		
		Logger.info("SlaveServer stopped")
Esempio n. 19
0
    def create(self, password):
        cmd = "useradd -d /dev/null -s /bin/false -G %s %s" % (Config.group, self.login)
        s, o = commands.getstatusoutput(cmd)
        if s == 2304:
            Logger.warn("FS: unable to create user: already exists")
            return False
        elif s != 0:
            Logger.error("FS: unable to create user")
            Logger.debug("FS: command '%s' return %d: %s" % (cmd, s, o.decode("UTF-8")))
            return False

        cmd = 'echo "%s\\n%s" | smbpasswd -s -a %s' % (password, password, self.login)
        s, o = commands.getstatusoutput(cmd)
        if s == 256:
            # "echo" is different between bash and dash
            cmd = 'echo -e "%s\\n%s" | smbpasswd -s -a %s' % (password, password, self.login)
            s, o = commands.getstatusoutput(cmd)

        if s != 0:
            Logger.error("FS: unable to set samba password")
            Logger.debug("FS: command '%s' return %d: %s" % (cmd, s, o.decode("UTF-8")))
            return False

        cmd = 'htpasswd -b %s "%s" "%s"' % (Config.dav_passwd_file, self.login, password)
        s, o = commands.getstatusoutput(cmd)
        if s != 0:
            Logger.error("FS: unable to update apache auth file")
            Logger.debug("FS: command '%s' return %d: %s" % (cmd, s, o.decode("UTF-8")))
            return False

        return True
Esempio n. 20
0
    def req_sendip(self, request):

        try:
            document = minidom.parseString(request["data"])
            rootNode = document.documentElement

            if rootNode.nodeName != "vm":
                raise Exception("invalid root node")

        except:
            Logger.error("Invalid input XML")
            doc = Document()
            rootNode = doc.createElement("error")
            rootNode.setAttribute("reason", "Invalid input XML")
            doc.appendChild(rootNode)

        response = self.send_packet("/vm/info", document)

        if response is False:

            Logger.warn(
                "DialogHypVM::send_ip unable to send request to the session manager"
            )
            return False

        return self.req_answer(document)
Esempio n. 21
0
	def run(self):
		self.updateApplications()
		self.has_run = True
		
		Logger._instance.lock.acquire()
		Logger._instance.close()
		for thread in self.threads:
			thread.start()
		Logger._instance.lock.release()
		
		t0_update_app = time.time()
		
		self.status = Role.STATUS_RUNNING
		
		while self.thread.thread_continue():
			while True:
				try:
					session = self.sessions_sync.get_nowait()
				except Queue.Empty, e:
					break
				except (EOFError, socket.error):
					Logger.debug("Role stopping")
					return
				
				if not self.sessions.has_key(session.id):
					Logger.warn("Session %s do not exist, session information are ignored"%(session.id))
					continue
				
				if session.status != self.sessions[session.id].status:
					self.manager.session_switch_status(session, session.status)
				
				if session.status == RolePlatform.Session.SESSION_STATUS_DESTROYED:
					del(self.sessions[session.id])
				else:
					self.sessions[session.id] = session
Esempio n. 22
0
	def req_user_logout(self, request):
		try:
			document = minidom.parseString(request["data"])
			rootNode = document.documentElement
			
			if rootNode.nodeName != "user":
				raise Exception("invalid root node")
			
			if not rootNode.hasAttribute("login"):
				raise Exception("invalid root node")
			
			login = rootNode.getAttribute("login")
			
		except:
			Logger.warn("Invalid xml input !!")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		
		session = self.role_instance.get_session_from_login(login)
		
		if session is None:
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "unknown user")
			doc.appendChild(rootNode)
			
			return self.req_answer(doc)
		
		self.role_instance.spool_action("logoff", session.id)
		
		return self.req_answer(document)
Esempio n. 23
0
	def req_manage(self, request):
		
		try:
			document = minidom.parseString(request["data"])
			rootNode = document.documentElement
		
			if rootNode.nodeName != "vm":
				raise Exception("invalid root node")
			
		except:
			Logger.warn("Invalid xml input !!")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "name")
			doc.appendChild(rootNode)
			
			return self.req_answer(doc)
		
		vname = rootNode.getAttribute("id")	
		action = rootNode.getAttribute("action")
		ret = self.role_instance.manage("ulteo_ovd_"+vname,action)
		
		doc = Document()
		rootNode = doc.createElement("vm")
		rootNode.setAttribute("status",ret)
		doc.appendChild(rootNode)
		
		return self.req_answer(doc)
Esempio n. 24
0
	def req_configure(self, request):
		
		try:
			document = minidom.parseString(request["data"])
			rootNode = document.documentElement
			
			if rootNode != "vm" :
				raise Exception("invalid root node")
			
		except:
			Logger.warn("Invalid input XML")
			doc = Document()
			rootNode = doc.createElement("error")
			rootNode.setAttribute("id", "name")
			doc.appendChild(rootNode)
			
			return self.req_answer(doc)
			
		vname = rootnode.getAttribute("id")
		ram = rootNode.getAttribute("ram")
		vcpus = rootNode.getAttribute("cpu")
		
		self.role_instance.config(vname, vcpus, ram)
		
		rootNode.setAttribute("status", "OK")
		
		return self.req_answer(document)
Esempio n. 25
0
    def uninstall_client(self):
        if not self.succefully_initialized:
            return

        self.archive_shell_dump()

        if self.profile is not None and self.profile.hasProfile():
            if not self.profile.mount():
                Logger.warn(
                    "Unable to mount profile at uninstall_client of session " +
                    self.id)
            else:
                self.profile.copySessionStop()

                if not self.profile.umount():
                    Logger.error(
                        "Unable to umount profile at uninstall_client of session "
                        + self.id)

        try:
            shutil.rmtree(self.user_session_dir)
        except Exception:
            Logger.exception("Failed to remove spool directory '%s'" %
                             self.user_session_dir)

        self.domain.onSessionEnd()
        return True
Esempio n. 26
0
	def req_user_loggedin(self, request):
		try:
			document = minidom.parseString(request["data"])
			rootNode = document.documentElement
			
			if rootNode.nodeName != "user":
				raise Exception("invalid root node")
			
			if not rootNode.hasAttribute("login"):
				raise Exception("invalid root node")
			
			login = rootNode.getAttribute("login")
			
		except:
			Logger.warn("Invalid xml input !!")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "usage")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		try:
			ret = TS.getSessionID(login)
		except Exception:
			Logger.exception("RDP server dialog failed ... ")
			doc = Document()
			rootNode = doc.createElement('error')
			rootNode.setAttribute("id", "internalerror")
			doc.appendChild(rootNode)
			return self.req_answer(doc)
		
		rootNode.setAttribute("loggedin", str((ret is not None)).lower())
		
		return self.req_answer(document)
Esempio n. 27
0
    def destroy(self):
        sid = self.getSid()
        if sid is None:
            return

        succefulDelete = False
        try:
            win32profile.DeleteProfile(sid)
            succefulDelete = True
        except:
            pass

        if not succefulDelete:
            if not self.unload(sid):
                Logger.error("Unable to unload User reg key for user %s" %
                             (self.name))
                return False
            try:
                win32profile.DeleteProfile(sid)
                succefulDelete = True
            except Exception, e:
                Logger.warn("Unable to unload user reg: %s" % (str(e)))

                try:
                    path = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\%s" % (
                        sid)
                    Reg.DeleteTree(win32con.HKEY_LOCAL_MACHINE, path)
                except Exception, err:
                    Logger.warn("RegDeleteTree of %s return: %s" %
                                (path, str(err)))
                    return False
Esempio n. 28
0
    def req_configure(self, request):

        try:
            document = minidom.parseString(request["data"])
            rootNode = document.documentElement

            if rootNode != "vm":
                raise Exception("invalid root node")

        except:
            Logger.warn("Invalid input XML")
            doc = Document()
            rootNode = doc.createElement("error")
            rootNode.setAttribute("id", "name")
            doc.appendChild(rootNode)

            return self.req_answer(doc)

        vname = rootnode.getAttribute("id")
        ram = rootNode.getAttribute("ram")
        vcpus = rootNode.getAttribute("cpu")

        self.role_instance.config(vname, vcpus, ram)

        rootNode.setAttribute("status", "OK")

        return self.req_answer(document)
Esempio n. 29
0
def clone(srcFile, dstFile, path, args):
    pythoncom.CoInitialize()

    shortcut_src = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None,
                                              pythoncom.CLSCTX_INPROC_SERVER,
                                              shell.IID_IShellLink)
    shortcut_src.QueryInterface(pythoncom.IID_IPersistFile).Load(srcFile)

    iconLocation = shortcut_src.GetIconLocation()[0]
    if len(iconLocation) == 0:
        iconLocation = shortcut_src.GetPath(0)[0]

    workingDirectory = shortcut_src.GetWorkingDirectory()
    description = shortcut_src.GetDescription()

    shortcut_dst = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None,
                                              pythoncom.CLSCTX_INPROC_SERVER,
                                              shell.IID_IShellLink)
    try:
        shortcut_dst.SetPath(path)
    except:
        Logger.warn(
            "LnkFile::clone: unable to setPath. Check that the following command is available on the system: '%s'"
            % (path))
        return False

    shortcut_dst.SetArguments(args)
    shortcut_dst.SetIconLocation(iconLocation, 0)
    shortcut_dst.SetWorkingDirectory(workingDirectory)
    shortcut_dst.SetDescription(description)

    shortcut_dst.QueryInterface(pythoncom.IID_IPersistFile).Save(dstFile, 0)
    return True
Esempio n. 30
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
Esempio n. 31
0
 def unload(self, sid):
     try:
         # Unload user reg
         win32api.RegUnLoadKey(win32con.HKEY_USERS, sid)
         win32api.RegUnLoadKey(win32con.HKEY_USERS, sid + '_Classes')
     except Exception, e:
         Logger.warn("Unable to unload user reg: %s" % (str(e)))
         return False
Esempio n. 32
0
 def getSid(self):
     #get the sid
     try:
         sid, _, _ = win32security.LookupAccountName(None, self.name)
         sid = win32security.ConvertSidToStringSid(sid)
     except Exception, e:
         Logger.warn("Unable to get SID: %s" % (str(e)))
         return None
Esempio n. 33
0
 def isScriptsMustBeSync(self):
     try:
         self.scripts_lock.acquire()
         return self.scripts_must_synced
     except:
         Logger.warn("Unable to lock mutex scripts")
     finally:
         self.scripts_lock.release()
Esempio n. 34
0
	def sock2data(self, sock):
		buf = sock.recv(4)
		try:
			packet_len = struct.unpack('>I', buf)[0]
		except Exception:
			Logger.warn("sock2data: packet recv syntax error")
			return None
		return sock.recv(packet_len)
Esempio n. 35
0
def getTarget(filename):
    cmd = None
    try:
        msi = Msi()
        cmd = msi.getTargetFromShortcut(filename)
    except WindowsError, e:
        Logger.warn("LnkFile::getTarget: Unable to init Msi")
        msi = None
Esempio n. 36
0
	def isScriptsMustBeSync(self):
		try:
			self.scripts_lock.acquire()
			return self.scripts_must_synced
		except:
			Logger.warn("Unable to lock mutex scripts")
		finally:
			self.scripts_lock.release()
Esempio n. 37
0
	def logoff(session_id):
		try:
			Logger.debug("perform_logoff: start logoff %d"%(session_id))
			ret = win32ts.WTSLogoffSession(None, session_id, True)
			Logger.debug("perform_logoff: finish logoff %d ret: %s"%(session_id, str(ret)))
		except Exception, e:
			Logger.warn("perform_logoff: exception %s"%(e))
			return False
Esempio n. 38
0
 def setScriptsMustBeSync(self, value):
     try:
         self.scripts_lock.acquire()
         self.scripts_must_synced = (value is True)
     except:
         Logger.warn("Unable to lock mutex scripts")
     finally:
         self.scripts_lock.release()
Esempio n. 39
0
	def unload(self, sid):
		try:
			#Unload user reg
			win32api.RegUnLoadKey(win32con.HKEY_USERS, sid)
			win32api.RegUnLoadKey(win32con.HKEY_USERS, sid+'_Classes')
		except Exception, e:
			Logger.warn("Unable to unload user reg: %s"%(str(e)))
			return False
Esempio n. 40
0
	def getSid(self):
		#get the sid
		try:
			sid, _, _ = win32security.LookupAccountName(None, self.name)
			sid = win32security.ConvertSidToStringSid(sid)
		except Exception,e:
			Logger.warn("Unable to get SID: %s"%(str(e)))
			return None
Esempio n. 41
0
	def setScriptsMustBeSync(self, value):
		try:
			self.scripts_lock.acquire()
			self.scripts_must_synced = (value is True)
		except:
			Logger.warn("Unable to lock mutex scripts")
		finally:
			self.scripts_lock.release()
Esempio n. 42
0
 def sock2data(self, sock):
     buf = sock.recv(4)
     try:
         packet_len = struct.unpack('>I', buf)[0]
     except Exception:
         Logger.warn("sock2data: packet recv syntax error")
         return None
     return sock.recv(packet_len)
Esempio n. 43
0
def getTarget(filename):
	cmd = None
	try:
		msi = Msi()
		cmd = msi.getTargetFromShortcut(filename)
	except WindowsError,e:
		Logger.warn("LnkFile::getTarget: Unable to init Msi")
		msi = None
Esempio n. 44
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()
Esempio n. 45
0
	def getRAMTotal():
		infos = System._getMeminfo()
		
		try:
			total = int(infos["MemTotal"])
		
		except Exception, e:
			Logger.warn("getRAMTotal: %s"%(str(e)))
			return 0.0
Esempio n. 46
0
	def getIcon(self, filename):
		#Logger.debug("ApplicationsDetection::getIcon %s"%(filename))
		#parser = ConfigParser.ConfigParser()
		#
		#try:
		#	parser.read(filename)
		#except ConfigParser.MissingSectionHeaderError:
		#	Logger.warn("ApplicationsDetection::getIcon invalid desktop file syntax")
		#	return None
	
		#if not parser.has_section('Desktop Entry'):
		#	Logger.warn("ApplicationsDetection::getIcon invalid desktop file syntax")
		#	return None	
		#
		#if not parser.has_option('Desktop Entry', "Icon"):
		#	# icon field is not required for type=Application
		#	return None
		#
		#iconName = parser.get('Desktop Entry', "Icon")
		#if not os.path.isabs(iconName):
		#	iconName = self.chooseBestIcon(iconName)
		#	if iconName is None:
		#		return None
                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, extensions = ["png", "xpm"])
                if iconPath == None:
                        return None
		
		bufFile = tempfile.mktemp(".png")		
		#cmd = 'convert -resize 32x32 "%s" "%s"'%(iconName, bufFile)
		cmd = 'convert -resize 32x32 "%s" "%s"'%(iconPath, bufFile)
		s,o = commands.getstatusoutput(cmd)
		if s != 0:
			Logger.debug("getIcon cmd '%s' returned (%d): %s"%(cmd, s, o))
			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
Esempio n. 47
0
    def getRAMTotal():
        infos = win32api.GlobalMemoryStatusEx()

        try:
            total = infos["TotalPhys"] / 1024

        except Exception, e:
            Logger.warn("getRAMTotal: %s" % (str(e)))
            return 0.0
Esempio n. 48
0
	def getRAMTotal():
		infos = win32api.GlobalMemoryStatusEx()
		
		try:
			total = infos["TotalPhys"]/1024
		
		except Exception, e:
			Logger.warn("getRAMTotal: %s"%(str(e)))
			return 0.0
Esempio n. 49
0
	def setStaticAppsMustBeSync(self, value):
		try:
			self.static_apps_lock.acquire()
			
			self.static_apps_must_synced = (value is True)
		except:
			Logger.warn("Unable to lock mutex static apps")
		finally:
			self.static_apps_lock.release()
Esempio n. 50
0
	def _get(self, sess_id, check_active=True):
		session = self.sessions.get(sess_id)
		if session is None:
			Logger.warn('[WebApps] session id={0} not found'.format(sess_id))
			return
		if check_active and session.status != Session.SESSION_STATUS_ACTIVE:
			Logger.warn('[WebApps] session id={0} is not active'.format(sess_id))
			return
		return session
Esempio n. 51
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
Esempio n. 52
0
    def setStaticAppsMustBeSync(self, value):
        try:
            self.static_apps_lock.acquire()

            self.static_apps_must_synced = (value is True)
        except:
            Logger.warn("Unable to lock mutex static apps")
        finally:
            self.static_apps_lock.release()