def with_privileges(username, func): ''' Run supplied function with privileges for specified username. ''' current_uid = os.getuid() current_groups = os.getgrouplist('root', 0) if not current_uid == 0: raise Exception('Not enough permissions to drop privileges') user_uid = pwd.getpwnam(username).pw_uid user_gid = pwd.getpwnam(username).pw_gid user_groups = os.getgrouplist(username, user_gid) # Drop privileges set_privileges(username, user_uid, user_gid, user_groups) # We need to catch exception in order to be able to restore # privileges later in this function try: func() except Exception as exc: logging.debug(slogm(exc)) # Restore privileges set_privileges('root', current_uid, 0, current_groups)
def get_users_group_list(self,user,group): ''' os.getgrouplist(user, group) Return list of group ids that user belongs to. If group is not in the list, it is included; typically, group is specified as the group ID field from the password record for user. ''' return os.getgrouplist(user, group)
def get_uncached_user(self, username=None, uid=None, getgroups=False): """ Returns dictionary containing pwd_struct data for the specified user or uid. Will raise an exception if the user does not exist. This method is appropriate for user validation. """ if username: u = pwd.getpwnam(username) elif uid is not None: u = pwd.getpwuid(uid) else: return {} user_obj = { 'pw_name': u.pw_name, 'pw_uid': u.pw_uid, 'pw_gid': u.pw_gid, 'pw_gecos': u.pw_gecos, 'pw_dir': u.pw_dir, 'pw_shell': u.pw_shell, } if getgroups: user_obj['grouplist'] = os.getgrouplist(u.pw_name, u.pw_gid) return user_obj
def collect_pwd(info_add): try: import pwd except ImportError: return import os uid = os.getuid() try: entry = pwd.getpwuid(uid) except KeyError: entry = None info_add('pwd.getpwuid(%s)' % uid, entry if entry is not None else '<KeyError>') if entry is None: # there is nothing interesting to read if the current user identifier # is not the password database return if hasattr(os, 'getgrouplist'): groups = os.getgrouplist(entry.pw_name, entry.pw_gid) groups = ', '.join(map(str, groups)) info_add('os.getgrouplist', groups)
def get_user_group_groups(self, user=None, group=None): if not self.superuser: return None, None, None if os.getuid() != 0: return None, None, None uid = None gid = None groups = None if user: try: pw = pwd.getpwuid(int(user)) except: pw = pwd.getpwnam(str(user)) uid = pw.pw_uid user = pw.pw_name gid = pw.pw_gid if group: try: gr = grp.getgrgid(int(group)) except: gr = grp.getgrnam(group) gid = gr.gr_gid groups = [gid] if gid is not None else None if user is not None: try: groups = os.getgrouplist(user, gid) except: pass return (uid, gid, groups)
def _getgrouplist(name, group): """Wrapper function to protect against `os._getgrouplist` not being available on Windows """ import os return os.getgrouplist(name, group)
def get_peer_credentials(self, sock): """Return the user and group name of the peer of a UNIX socket.""" ucred = sock.getsockopt(socket.SOL_SOCKET, SO_PEERCRED, s_ucred.size) _, uid, gid = s_ucred.unpack(ucred) user = pwd.getpwuid(uid).pw_name groups = {grp.getgrgid(g).gr_name for g in os.getgrouplist(user, gid)} return user, groups
def _validate_permissions(self) -> None: # confirm that user is root or part of haclient group" user = getpass.getuser() group_id = os.getgid() group_list = os.getgrouplist(user, group_id) try: # find group id for root and haclient id_ha = grp.getgrnam(const.USER_GROUP_HACLIENT) id_root = grp.getgrnam(const.USER_GROUP_ROOT) # if group not root or haclient return error if id_ha.gr_gid not in group_list and id_root.gr_gid not in group_list: Log.error( f"User {user} does not have necessary permissions to execute this CLI" ) raise HAInvalidPermission( f"User {user} does not have necessary permissions to execute this CLI" ) # TODO : Check if user needs to be changed to hauser except KeyError: Log.error("haclient group is not present on the system") raise HAInvalidPermission( "haclient group is not present on the system")
def get_group_list(user, include_default=True): """ Returns a list of all of the system group names of which the user is a member. """ if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, "getgrouplist"): # Try os.getgrouplist, available in python >= 3.3 log.trace("Trying os.getgrouplist for '%s'", user) try: group_names = [ grp.getgrgid(grpid).gr_name for grpid in os.getgrouplist(user, pwd.getpwnam(user).pw_gid) ] except Exception: # pylint: disable=broad-except pass elif HAS_PYSSS: # Try pysss.getgrouplist log.trace("Trying pysss.getgrouplist for '%s'", user) try: group_names = list(pysss.getgrouplist(user)) except Exception: # pylint: disable=broad-except pass if group_names is None: # Fall back to generic code # Include the user's default group to match behavior of # os.getgrouplist() and pysss.getgrouplist() log.trace("Trying generic group list for '%s'", user) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = get_default_group(user) if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass if group_names is not None: ugroups.update(group_names) if include_default is False: # Historically, saltstack code for getting group lists did not # include the default group. Some things may only want # supplemental groups, so include_default=False omits the users # default group. try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass log.trace("Group list for user '%s': %s", user, sorted(ugroups)) return sorted(ugroups)
def get_user_groups(self, user): gid = pwd.getpwnam(user).pw_gid groups_gids = os.getgrouplist(user, gid) groups = [grp.getgrgid(x).gr_name for x in groups_gids] groups.append("*") groups.append("anonymous") groups.append(grp.getgrgid(gid).gr_name) return groups
def drop_privileges(user): if os.getuid() != 0: return pwnam = pwd.getpwnam(user) os.setgroups(os.getgrouplist(pwnam.pw_name, pwnam.pw_gid)) os.setgid(pwnam.pw_gid) os.setuid(pwnam.pw_uid) os.environ['HOME'] = pwnam.pw_dir logging.info('Dropped privileges to user "%s"', user)
def _init_converter() -> None: # Drop privileges logger.debug(f"{os.getuid()=}, {os.getgid()=}, {os.getgroups()=}") passwd: struct_passwd = pwd.getpwnam(username) os.setgroups(os.getgrouplist(passwd.pw_name, passwd.pw_gid)) os.setresgid(passwd.pw_gid, os.getgid(), os.getgid()) os.setresuid(passwd.pw_uid, os.getuid(), os.getuid()) logger.debug(f"{os.getuid()=}, {os.getgid()=}, {os.getgroups()=}") # Set environment variables os.putenv("HOME", passwd.pw_dir) os.putenv("HISTFILE", "/dev/null")
def init_lower_privileges(uid: int, gid: int) -> None: """Function to lower privileges (*i.e.* change *real* and *effective* UIDs and GIDs to UID/GID values given as arguments) intended to be called at cosmk module importation.""" # Reset the supplementary groups of the current user to the supplementary # groups of the target unprivileged user: username = pwd.getpwuid(uid).pw_name usergroups = os.getgrouplist(username, gid) os.setgroups(usergroups) # And then hange real, effective and saved-set UID and GID: os.setresgid(gid, gid, 0) # GID before UID otherwise this fails os.setresuid(uid, uid, 0)
def _get_user_info(user): import pwd username = uid = gid = groups = None if user is None: uid = os.geteuid() #username = os.getlogin() username = pwd.getpwuid(uid)[0] gid = os.getgid() groups = os.getgroups() else: if isinstance(user, int): uid = user entry = pwd.getpwuid(uid) username = entry.pw_name elif isinstance(user, str): username = user entry = pwd.getpwnam(username) uid = entry.pw_uid else: raise NotImplementedError(user) gid = entry.pw_gid os.getgrouplist(username, gid) return username, uid, gid, groups
def setuser(username): """ Returns a function that sets process uid, gid according to the given username. If the user does not exist, it raises an error. """ uid, gid, home = id(username) groups = list(set(os.getgrouplist(username, gid))) def chuser(): os.setgroups(groups) os.setgid(gid) os.setuid(uid) os.environ['HOME'] = home return chuser
def show_groups(user_name): """Determine groups user belongs to; print""" check_user(user_name) group_id = os.getgid() groups = os.getgrouplist(user_name, group_id) print("The user " + user_name + " belongs to the following groups:") for g in groups: group_db = grp.getgrgid(g) gname = group_db[0] print(gname)
def check_root(self): user = os.environ["USER"] group_found = False #old groups method #for g in grp.getgrall(): # if(g.gr_name in LlxUpCheckRoot.GROUPS): # for member in g.gr_mem: # if(member==user): # group_found=True gid = pwd.getpwnam(user).pw_gid groups_gids = os.getgrouplist(user, gid) user_groups = [grp.getgrgid(x).gr_name for x in groups_gids] for g in user_groups: if (g in LlxUpCheckRoot.GROUPS): group_found = True if not self.checkImageBeingEdited(): if group_found: screensaver_inhibitor = lliurex.screensaver.InhibitScreensaver( ) screensaver_inhibitor.inHibit() cmd = 'pkexec lliurex-up' os.system(cmd) screensaver_inhibitor.unInhibit() else: text = _( "You need administration privileges to run this application." ) cmd = 'kdialog --icon lliurex-up --title "Lliurex-Up" --passivepopup \ "%s" 5' % text os.system(cmd) else: if 'root' in user_groups: cmd = 'lliurex-up' os.system(cmd) else: text = _( "You need administration privileges to run this application." ) cmd = 'kdialog --icon lliurex-up --title "Lliurex-Up" --passivepopup \ "%s" 5' % text os.system(cmd)
def setuser(username): """ Returns a function that sets process uid, gid according to the given username. If the user does not exist, it raises an error. """ uid, gid, home = id(username) groups = list(set(os.getgrouplist(username, gid))) def chuser(): try: os.setgroups(groups) os.setgid(gid) os.setuid(uid) os.environ['HOME'] = home except: pass # Probably the container started as a not root user return chuser
def run_test(test): uid = pwd.getpwnam(test.user).pw_uid gid = pwd.getpwnam(test.user).pw_gid # set supplementary groups, just like after user login os.setgroups(os.getgrouplist(test.user, gid)) os.setgid(gid) os.setuid(uid) cmd = test.cmd.replace('$BIN$', prown_path) if not test.shell: cmd = cmd.split(' ') status = 0 errors = [] run = subprocess.run(cmd, shell=test.shell, cwd=projects_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={'LANG': 'C'}) if run.returncode != test.exitcode: errors.append( "exit code %d is different from expected exit code %d\n" % (run.returncode, test.exitcode)) msg = cmp_output('stdout', run.stdout.decode('utf-8'), test.stdout) if msg: errors.append("stdout is not conform:\n%s" % (msg)) msg = cmp_output('stderr', run.stderr.decode('utf-8'), test.stderr) if msg: errors.append("stderr is not conform:\n%s" % (msg)) if len(errors): warn(u"❌test « %s » failed, errors:" % (test.name)) for error in errors: warn(textwrap.indent(error, ' + ', lambda line: True)) status = 1 # at this point, we cannot tell if the test is successful as the parent # with root permissions must check stats. # terminate child process sys.exit(status)
def get_user_groups(self,user): ##old groups method #groups = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] #groups.append("*") #groups.append("anonymous") #gid = pwd.getpwnam(user).pw_gid #groups.append(grp.getgrgid(gid).gr_name) gid = pwd.getpwnam(user).pw_gid groups_gids = os.getgrouplist(user, gid) groups = [ grp.getgrgid(x).gr_name for x in groups_gids ] groups.append("*") groups.append("anonymous") groups.append(grp.getgrgid(gid).gr_name) return groups
def get_groups(username: str) -> Tuple[List[str], List[str]]: """Return list of system groups for given user. Uses ``os.getgrouplist`` and ``os.NGROUPS_MAX`` to get system groups for a given user. ``grp.getgrgid`` then parses these to return a list of group names. Args: username: username used to check system groups. Returns: list: system groups for username given """ groupmax = os.NGROUPS_MAX # type: ignore group_ids = os.getgrouplist(username, groupmax) group_ids.remove(groupmax) # turn list of group_ids into group names with group identifier prepended return parse_group_ids(group_ids)
def check_permissions(self): if "PKEXEC_UID" in os.environ: self.user = pwd.getpwuid(int(os.environ["PKEXEC_UID"])).pw_name else: self.user = os.environ["USER"] #old groups method #groups = [g.gr_name for g in grp.getgrall() if self.user in g.gr_mem] gid = pwd.getpwnam(self.user).pw_gid groups_gids = os.getgrouplist(self.user, gid) groups = [grp.getgrgid(x).gr_name for x in groups_gids] if "sudo" not in groups and "admins" not in groups: return False else: return True
def detach_process(self): # Don't be hit by CTRL+C setpgrp() # Drop privileges if needed uid, gid = getenv('SUDO_UID'), getenv('SUDO_GID') if uid and gid: uid, gid = int(uid), int(gid) setgroups(getgrouplist(getpwuid(uid).pw_name, gid)) setresgid(gid, gid, -1) setresuid(uid, uid, -1)
def setuser(user): """ Returns a function that sets process uid, gid according to the given username. If the user does not exist, it raises an error. """ try: pw = getpw(user) except KeyError: raise Exception('No such user: %s' % user) groups = list(set(os.getgrouplist(pw.pw_name, pw.pw_gid))) def chuser(): os.setgroups(groups) os.setgid(pw.pw_gid) os.setuid(pw.pw_uid) os.environ['HOME'] = pw.pw_dir return chuser
def start(uid): pwnam = pwd.getpwuid(uid) createhome(pwnam) home = f"/srv/home/{pwnam.pw_name}" # Start mammutfs with arguments args = [mammutfs, config_user, "--mountpoint", home, "--username", pwnam.pw_name] ## Force jotweh to run in foreground. DO NOT DO THIS UNDER AUTOMOUNT CONDITIONS! #if pwnam.pw_name == "007394": # args += [ "--deamonize", "0" ] # Drop into the users priviliges os.setgroups(os.getgrouplist(pwnam.pw_name, pwnam.pw_gid)) os.setgid(pwnam.pw_gid) os.setuid(pwnam.pw_uid) print("Starting " + str(args)) os.execv(mammutfs, args)
def get_group_list(user=None, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' group_names = None ugroups = set() if not isinstance(user, string_type): raise Exception if hasattr(os, 'getgrouplist'): # Try os.getgrouplist, available in python >= 3.3 logger.debug('Trying os.getgrouplist for {0!r}'.format(user)) try: group_names = list(os.getgrouplist(user, pwd.getpwnam(user).pw_gid)) except Exception: pass if group_names is None: # Fall back to generic code # Include the user's default group to behave like # os.getgrouplist() and pysss.getgrouplist() do logger.debug('Trying generic group list for {0!r}'.format(user)) group_names = [g.gr_name for g in grp.getgrall() if user in g.gr_mem] try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name if default_group not in group_names: group_names.append(default_group) except KeyError: # If for some reason the user does not have a default group pass ugroups.update(group_names) if include_default is False: try: default_group = grp.getgrgid(pwd.getpwnam(user).pw_gid).gr_name ugroups.remove(default_group) except KeyError: # If for some reason the user does not have a default group pass logger.debug('Group list for user {0!r}: {1!r}'.format( user, sorted(ugroups))) return sorted(ugroups)
def drop_privs(api): """Drop privileges of the running process. Will first set the umask to 0027, then set the groups to those of the user number 'api.uid', then finally set the new GID and UID. Args: api (ApiExec): object containing the UID and GID values to drop to. Returns: NoneType: always returns 'None'. Raises: PrivError: raised for any errors encountered. """ if api.uid == None: return None gid = get_gid(api) try: os.umask(0o027) except OSError as ex: raise Except.PrivError( "setting umask failed: {}".format(ex.strerror.lower())) try: os.setgroups( os.getgrouplist(pwd.getpwuid(api.uid).pw_name, gid) ) except KeyError: raise Except.PrivError("dropping privileges failed: could not set new group permissions") try: os.setgid(gid) except OSError as ex: raise Except.PrivError("droping GID privileges to group '{}' failed: {}".format(gid, ex.strerror.lower())) try: os.setuid(api.uid) except OSError as ex: raise Except.PrivError("droping UID privileges to user '{}' failed: {}".format(api.uid, ex.strerror.lower()))
def change_uidgid(user_and_group): """Change uid and gid of the current process. The user_and_group parameter must be a string of the format '<user>[:[<group>]]' or [<user>]:<group>. User and group can be strings or integers. :raises ValueError: if user or group could not be resolved :raises RuntimeError: if setting gid or uid did not succeed """ uid, gid = string_to_uidgid(user_and_group) # First change group and then user if gid is not None: try: os.setgid(gid) except (OSError, PermissionError) as e: raise RuntimeError(f"Could not set gid to {gid}: {e}") from e if uid is not None and gid is not None: try: passwd = pwd.getpwuid(uid) username = passwd.pw_name except KeyError as e: raise ValueError(f"Could not resolve user {uid}: {e}") from e try: groups = os.getgrouplist(username, gid) os.setgroups(groups) except (OSError, PermissionError) as e: raise RuntimeError( f"Could not set group list to {groups}: {e}") from e if uid is not None: try: os.setuid(uid) except (OSError, PermissionError) as e: raise RuntimeError(f"Could not set uid to {uid}: {e}") from e
def main(): opts, args = parser.parse_known_args() if ':' in opts.user: user, group = opts.user.split(':', 1) else: user, group = opts.user, None if user.isdigit(): uid = int(user) try: pw = pwd.getpwuid(uid) except KeyError: pw = None else: try: pw = pwd.getpwnam(user) except KeyError: if group is None: parser.error("Unknown user name %r." % user) else: uid = os.getuid() try: pw = pwd.getpwuid(uid) except KeyError: pw = None else: uid = pw.pw_uid if pw: home = pw.pw_dir name = pw.pw_name else: home = '/' name = user if group: if group.isdigit(): gid = int(group) else: try: gr = grp.getgrnam(group) except KeyError: parser.error("Unknown group name %r." % user) else: gid = gr.gr_gid elif pw: gid = pw.pw_gid else: gid = uid if group: os.setgroups([gid]) else: gl = getgrouplist(name, gid) os.setgroups(gl) os.setgid(gid) os.setuid(uid) os.environ['USER'] = name os.environ['HOME'] = home os.environ['UID'] = str(uid) os.execvp(opts.command, [opts.command] + args)
def check_path_accessibility(path, file=True, executable=False): """Return None if file is readable by greeter and error message otherwise""" if not os.path.exists(path): return _("File not found: {path}").format(path=path) try: uid, gids = check_path_accessibility.id_cached_data except AttributeError: files = glob.glob("/etc/lightdm/lightdm.d/*.conf") files += ["/etc/lightdm/lightdm.conf"] config = configparser.RawConfigParser(strict=False) config.read(files) username = config.get("LightDM", "greeter-user", fallback="lightdm") pw = pwd.getpwnam(username) uid = pw.pw_uid gids = set(os.getgrouplist(username, pw.pw_gid)) check_path_accessibility.id_cached_data = uid, gids parts = os.path.normpath(path).split(os.path.sep) if not parts[0]: parts[0] = os.path.sep def check(p): try: st = os.stat(p) except OSError as e: return _("Failed to check permissions: {error}".format(error=e.strerror)) if stat.S_ISDIR(st.st_mode) and not stat.S_IREAD: return _("Directory is not readable: {path}".format(path=p)) if st.st_uid == uid: return not (st.st_mode & stat.S_IRUSR) and _( "LightDM do not have permissions to read path: {path}".format(path=p) ) if st.st_gid in gids: return not (st.st_mode & stat.S_IRGRP) and _( "LightDM do not have permissions to read path: {path}".format(path=p) ) return not (st.st_mode & stat.S_IROTH) and _( "LightDM do not have permissions to read path: {path}".format(path=p) ) errors = (check(p) for p in accumulate(parts, os.path.join)) error = next((error for error in errors if error), None) if not error and file and not os.path.isfile(path): return _("Path is not a regular file: {path}".format(path=path)) if not error and executable: st = os.stat(path) if st.st_uid == uid: if not st.st_mode & stat.S_IXUSR: return _("LightDM do not have permissions to execute file: {path}".format(path=path)) elif st.st_gid in gids: if not st.st_mode & stat.S_IXGRP: return _("LightDM do not have permissions to execute file: {path}".format(path=path)) elif not st.st_mode & stat.S_IXOTH: return _("LightDM do not have permissions to execute file: {path}".format(path=path)) return error
def getgroups() -> list: return [ grp.getgrgid(i).gr_name for i in os.getgrouplist( pwd.getpwuid(os.geteuid()).pw_name, os.getegid()) ]
def _get_user_group_ids(self, username): user_gid = self._get_user_gid_by_name(username) return os.getgrouplist(username, user_gid)
def main(): MPD_default_socket_path = "/run/mpd/socket" # Create argument parser and help parser = argparse.ArgumentParser() ui_interface = parser.add_mutually_exclusive_group(required=True) ui_interface.add_argument("-c", "--console", action="store_true", help="The UI is console based") ui_interface.add_argument("-p", "--panel", action="store_true", help="The UI is routed to the front panel") #parser.add_argument("--lcd_cols",type=int,default=20,help="Specify the number of columns of the LCD") #parser.add_argument("--lcd_rows",type=int,default=4,help="Specify the number of rows of the LCD") parser.add_argument("--mpd_host", default=None, help="Specify the hostname/IP of the MPD server") parser.add_argument("--mpd_port", type=int, default=6600, help="Specify the port of the MPD server") parser.add_argument( "--mpd_socket", default=MPD_default_socket_path, help="Specify the path to the MPD server socket (default): " + MPD_default_socket_path) parser.add_argument("--user", default="palms", help="User to run as.") parser.add_argument( "--loglevel", default="INFO", help= "Level to log at. Should be one of DEBUG/INFO/WARNING/ERROR/CRITICAL.") parser.add_argument( "--debug", default="", help="Comma seperated list of modules to enable debugging for.") args = parser.parse_args() # Are we running as root? if os.getuid() == 0: PALMS_DATA_DIR = "/var/lib/palms/" PALMS_LOG_DIR = "/var/log/palms/" try: pwnam = pwd.getpwnam(args.user) except: print("PALMS: Could not find user - " + args.user) return -1 # Check data directory exists if os.path.exists(PALMS_DATA_DIR): stat_info = os.stat(PALMS_DATA_DIR) # Check data directory permissions if (pwnam.pw_uid != stat_info.st_uid) or (pwnam.pw_gid != stat_info.st_gid): print("PALMS: Check permissions for data directory " + PALMS_DATA_DIR) return -1 else: print("PALMS: Data directory " + PALMS_DATA_DIR + " does not exist.") return -1 # Check log directory exists if os.path.exists(PALMS_LOG_DIR): stat_info = os.stat(PALMS_LOG_DIR) # Check log directory permissions if (pwnam.pw_uid != stat_info.st_uid) or (pwnam.pw_gid != stat_info.st_gid): print("PALMS: Check permissions for log directory " + PALMS_LOG_DIR) return -1 else: print("PALMS: Log directory " + PALMS_LOG_DIR + " does not exist.") return -1 # Drop privileges # Remove group privileges os.setgroups(os.getgrouplist(pwnam.pw_name, pwnam.pw_gid)) # Try setting the new uid/gid os.setgid(pwnam.pw_gid) os.setuid(pwnam.pw_uid) # Update 'HOME' environment variable os.environ['HOME'] = pwnam.pw_dir # # Change to directory # os.chdir(pwnam.pw_dir) #Ensure a reasonable umask old_umask = os.umask(0o22) else: PALMS_DATA_DIR = os.environ['HOME'] PALMS_LOG_DIR = os.environ['HOME'] # Check that privileges have dropped if os.getuid() == 0: print("PALMS: Privileges not dropped still root.") return -1 PALMS_SQLPATH = PALMS_DATA_DIR + "/palms.dat" # Start logging palms_logfile = PALMS_LOG_DIR + "/palms.log" numeric_loglevel = getattr(logging, args.loglevel.upper(), None) if not isinstance(numeric_loglevel, int): raise ValueError('Invalid log level: %s' % args.loglevel) log_format = '%(asctime)s - %(name)s:%(levelname)s; %(message)s' logging.basicConfig(filename=palms_logfile, format=log_format, level=numeric_loglevel) logger = logging.getLogger(__name__) # Reduce the log level of libraries logging.getLogger("apscheduler").setLevel(logging.WARNING) logging.getLogger("mpd").setLevel(logging.WARNING) # Reduce the log level of module except the ones we are interested in debug_modules = args.debug.split(',') if not "main" in debug_modules: logging.getLogger("__main__").setLevel(logging.INFO) if not "browser" in debug_modules: logging.getLogger("palms.browser").setLevel(logging.INFO) if not "config" in debug_modules: logging.getLogger("palms.config").setLevel(logging.INFO) if not "curses_wrapper" in debug_modules: logging.getLogger("palms.curses_wrapper").setLevel(logging.INFO) if not "home" in debug_modules: logging.getLogger("palms.home").setLevel(logging.INFO) if not "mpd_request_files" in debug_modules: logging.getLogger("palms.mpd_request_files").setLevel(logging.INFO) if not "radio" in debug_modules: logging.getLogger("palms.radio").setLevel(logging.INFO) if not "ticker" in debug_modules: logging.getLogger("palms.ticker").setLevel(logging.INFO) # Connect to SQLite DB logger.debug("Preparing to open SQL data file: " + PALMS_SQLPATH) try: sqlcon = sqlite3.connect(PALMS_SQLPATH) except: print("PALMS: Could not open SQL file - " + PALMS_SQLPATH) return -1 logger.info("Opened SQL data file.") # Create configuration conf = config(sqlcon) # Setup connection tp MPD Server logger.debug("Preparing to connect to MPD daemon using socket: " + MPD_default_socket_path) mpd_client = MPDClient_extra(conf) mpd_client.timeout = 240 mpd_client.idletimeout = 240 mpd_client.connect(MPD_default_socket_path, None) mpd_client.clear() mpd_client.load_config() logger.info("Connected to MPD daemon.") # Setup the scheduler to read meta data from mplayer sched = BackgroundScheduler(daemon=False) sched.start() logger.debug("Started task scheduler.") # Create a screen scr_typ = curses_wrapper.SCREEN_TYPE_NONE if args.console: scr_typ = curses_wrapper.SCREEN_TYPE_NCURSES elif args.panel: scr_typ = curses_wrapper.SCREEN_TYPE_FPDEVICE stdscr = curses_wrapper(scr_typ) # Init Home logger.info("Starting P.A.L.M.S.") home = Home(stdscr, sched, conf, mpd_client) # Idle loop while not home.is_poweroff(): sleep(0.5) logger.info("Shutting down P.A.L.M.S.") # Close down widgets (this will save changes) home.close() # Destroy screen stdscr.close() # Shutdown screen logger.debug("Shutting down task scheduler.") sched.shutdown() # Close MPD connection logger.info("Closing MPD connection.") mpd_client.close() mpd_client.disconnect() # Save configuration conf.save_config() # Close DB connection logger.info("Closing SQL data file.") sqlcon.close() return 0