def render_POST(self, req): uploaddir = self.default_uploaddir if req.args['path'][0]: if os_path.isdir(req.args['path'][0]): uploaddir = req.args['path'][0] if uploaddir[-1] != "/": uploaddir += "/" else: req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "path '%s' to upload not existing!" % req.args['path'][0] data = req.args['file'][0] if not data: req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "filesize was 0, not uploaded" fd, fn = mkstemp(dir=uploaddir) cnt = os_write(fd, data) os_close(fd) os_chmod(fn, 0755) if cnt <= 0: # well, actually we should check against len(data) but lets assume we fail big time or not at all try: os_unlink(fn) except OSError, oe: pass req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "error writing to disk, not uploaded"
def lock_path(path, timeout): """A context manager that attempts to gain an advisory lock. The advisory lock is attempted for the path given within the timeout given. Raises :py:class:`LockPathTimeout` if time expires before gaining the lock. If the lock is obtained, True is yielded and the lock relinquished when the context ends. For example:: with lock_path(path, timeout): # do things inside path knowing others using the same # advisory locking mechanism will be blocked until you're # done. :param path: The path to gain an advisory lock on. :param timeout: The number of seconds to wait to gain the lock before raising :py:class:`LockPathTimeout`. """ fd = os_open(path, O_RDONLY) try: try_until = time() + timeout while True: try: flock(fd, LOCK_EX | LOCK_NB) break except IOError as err: if err.errno != EAGAIN: raise sleep(0.01) if time() >= try_until: raise LockPathTimeout("Timeout %ds trying to lock %r." % (timeout, path)) yield True finally: os_close(fd)
def loadConfigFile(self): print("[AutomaticVolumeAdjustmentConfig] Loading config file...") self.config = Config() if not os_path.exists(self.CONFIG_FILE): try: fd = os_open(self.CONFIG_FILE, os_O_RDWR | os_O_CREAT) os_close(fd) except Exception as e: print("Error: ", e) try: self.config.loadFromFile(self.CONFIG_FILE) except Exception as e: print("Error: ", e) self.config.entriescount = ConfigInteger(0) self.config.Entries = ConfigSubList() self.config.enable = ConfigYesNo(default=False) self.config.modus = ConfigSelection(choices=[ ("0", _("Automatic volume adjust")), ("1", _("Remember service volume value")) ], default="0") self.config.adustvalue = ConfigSelectionNumber(-50, 50, 5, default=25) self.config.mpeg_max_volume = ConfigSelectionNumber(10, 100, 5, default=100) self.config.show_volumebar = ConfigYesNo(default=False) self.initConfig()
def close_session(): # Do we have a session to save in the first place? if CURRENT_SESSION is None: return try: makedirs(SESSIONS_DIR) except OSError as e: if e.errno == 17: # Already exists pass else: raise # Write to a temporary file and move it in place, for safety tmp_file_path = None try: tmp_file_fh, tmp_file_path = mkstemp() os_close(tmp_file_fh) with open(tmp_file_path, 'wb') as tmp_file: pickle_dump(CURRENT_SESSION, tmp_file) copy(tmp_file_path, get_session_pickle_path(CURRENT_SESSION.get_sid())) except IOError: # failed store: no permissions? raise SessionStoreError finally: if tmp_file_path is not None: remove(tmp_file_path)
def setDelay(self, device, value): #REP_DELAY if self.getDeviceAttribute(device, 'enabled'): print "[iInputDevices] setDelay for device %s to %d ms" % (device,value) event = struct.pack('iihhi', 0, 0, 0x14, 0x00, int(value)) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event) os_close(fd)
def render_POST(self, req): data = req.args['file'][0] print "[filename req.args]", req.args['filename'][0] filename = mbasename(req.args['filename'][0]) print "[filename]", filename if not filename.endswith(".ipk"): return self.res % (_("wrong filetype!") ,_("Close"), _("Add")) if not data: req.setResponseCode(http.OK) return self.res % ( _("filesize was 0, not uploaded") , _("Close"), _("Add") ) fd,fn = mkstemp(dir = "/tmp/") cnt = os_write(fd, data) os_close(fd) os_chmod(fn, 0755) if cnt <= 0: # well, actually we should check against len(data) but lets assume we fail big time or not at all try: os_unlink(fn) except OSError, oe: pass req.setResponseCode(http.OK) return self.res % (_("error writing to disk, not uploaded"),_("Close"), _("Add"))
def getInputDevices(self): for evdev in sorted(listdir("/dev/input")): try: fd = os_open("/dev/input/%s" % evdev, O_RDONLY | O_CLOEXEC) except: continue buf = "\0" * 256 try: size = ioctl(fd, EVIOCGNAME(len(buf)), buf) except: os_close(fd) continue os_close(fd) if size <= 0: continue name = buf[:size - 1] if name: if name == "dreambox advanced remote control (native)" and config.misc.rcused.value not in ( 0, 2): continue if name == "dreambox remote control (native)" and config.misc.rcused.value in ( 0, 2): continue if name == "dreambox front panel": continue self.Devices[evdev] = { 'name': name, 'type': self.getInputDeviceType(name), 'enabled': False, 'configuredName': None }
def render_POST(self, req): req.setResponseCode(http.OK) req.setHeader('Content-type', 'application/xhtml+xml;' ) req.setHeader('charset', 'UTF-8') data = req.args['file'][0] if not data: result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <e2simplexmlresult>\n <e2state>False</e2state> <e2statetext>Filesize was 0, not uploaded</e2statetext> </e2simplexmlresult>\n""" return result fd = os_open( self.FILENAME, os_O_WRONLY|os_O_CREAT ) if fd: cnt = os_write(fd, data) os_close(fd) if cnt <= 0: try: os_remove(FILENAME) except OSError as oe: pass result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <e2simplexmlresult>\n <e2state>False</e2state> <e2statetext>Error writing to disk, not uploaded</e2statetext> </e2simplexmlresult>\n""" else: result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <e2simplexmlresult>\n <e2state>True</e2state> <e2statetext>%s</e2statetext> </e2simplexmlresult>\n""" % self.FILENAME return result
def getInputDevices(self): devices = listdir('/dev/input/') for evdev in devices: try: buffer = '\x00' * 512 self.fd = os_open('/dev/input/' + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find('\x00')] if str(self.name).find('Keyboard') != -1: self.name = 'keyboard' os_close(self.fd) except (IOError, OSError) as err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str( err) + ' >' self.name = None if self.name: self.Devices[evdev] = { 'name': self.name, 'type': self.getInputDeviceType(self.name), 'enabled': False, 'configuredName': None } if getBoxType().startswith('et'): self.setDefaults(evdev)
def setDelay(self, device, value): #REP_DELAY if self.getDeviceAttribute(device, 'enabled') == True: print "[iInputDevices] setDelay for device %s to %d ms" % (device,value) event = struct.pack('iihhi', 0, 0, 0x14, 0x00, int(value)) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event) os_close(fd)
def demonize(): from os import close as os_close for fd in [0, 1, 2]: try: os_close(fd) except OSError: pass
def download_collection(collection, exclude_configs=False): directory = collection real_dir = real_directory(directory) dir_name = basename(dirname(real_dir)) fname = '%s.%s' % (dir_name, 'tar.gz') tmp_file_path = None try: tmp_file_fh, tmp_file_path = mkstemp() os_close(tmp_file_fh) tar_cmd_split = ['tar', '--exclude=.stats_cache'] if exclude_configs: tar_cmd_split.extend(['--exclude=annotation.conf', '--exclude=visual.conf', '--exclude=tools.conf', '--exclude=kb_shortcuts.conf']) tar_cmd_split.extend(['-c', '-z', '-f', tmp_file_path, dir_name]) tar_p = Popen(tar_cmd_split, cwd=path_join(real_dir, '..')) tar_p.wait() hdrs = [('Content-Type', 'application/octet-stream'), #'application/x-tgz'), ('Content-Disposition', 'inline; filename=%s' % fname)] with open(tmp_file_path, 'rb') as tmp_file: tar_data = tmp_file.read() raise NoPrintJSONError(hdrs, tar_data) finally: if tmp_file_path is not None: remove(tmp_file_path)
def getInputDevices(self): for evdev in sorted(listdir("/dev/input")): try: fd = os_open("/dev/input/%s" % evdev, O_RDONLY | O_CLOEXEC) except: continue buf = "\0"*256 try: size = ioctl(fd, EVIOCGNAME(len(buf)), buf) except: os_close(fd) continue os_close(fd) if size <= 0: continue name = buf[:size - 1] if name: if name == "dreambox advanced remote control (native)" and config.misc.rcused.value not in (0, 2): continue if name == "dreambox remote control (native)" and config.misc.rcused.value in (0, 2): continue if name == "dreambox front panel": continue self.Devices[evdev] = {'name': name, 'type': self.getInputDeviceType(name),'enabled': False, 'configuredName': None }
def render_POST(self, req): uploaddir = self.default_uploaddir if req.args['path'][0]: if os_path.isdir(req.args['path'][0]): uploaddir = req.args['path'][0] if uploaddir[-1] != "/": uploaddir += "/" else: req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "path '%s' to upload not existing!" % req.args['path'][0] data = req.args['file'][0] if not data: req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "filesize was 0, not uploaded" fd, fn = mkstemp(dir = uploaddir) cnt = os_write(fd, data) os_close(fd) os_chmod(fn, 0755) if cnt <= 0: # well, actually we should check against len(data) but lets assume we fail big time or not at all try: os_unlink(fn) except OSError, oe: pass req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "error writing to disk, not uploaded"
def setDelay(self, device, value): if self.getDeviceAttribute(device, 'enabled'): print '[iInputDevices] setDelay for device %s to %d ms' % (device, value) event = struct.pack('iihhi', 0, 0, 20, 0, int(value)) fd = os_open('/dev/input/' + device, O_RDWR) os_write(fd, event) os_close(fd)
def _get_terminal_size_linux(): def ioctl_GWINSZ(fd): try: from fcntl import ioctl as fcntl_ioctl import termios cr = struct_unpack('hh', fcntl_ioctl(fd, termios.TIOCGWINSZ, '1234')) return cr except: pass cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) if not cr: try: from os import ctermid as os_ctermid fd = os_open(os_ctermid(), os_O_RDONLY) cr = ioctl_GWINSZ(fd) os_close(fd) except: pass if not cr: try: cr = (os_environ['LINES'], os_environ['COLUMNS']) except: return None return int(cr[1]), int(cr[0])
def setRepeat(self, device, value): #REP_PERIOD if self.getDeviceAttribute(device, 'enabled'): print "[iInputDevices] setRepeat for device %s to %d ms" % (device,value) event = struct.pack('iihhi', 0, 0, 0x14, 0x01, int(value)) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event) os_close(fd)
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: try: buffer = "\0" * 512 self.fd = os_open("/dev/input/" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] if str(self.name).find("Keyboard") != -1: self.name = 'keyboard' os_close(self.fd) except (IOError, OSError), err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str( err) + ' >' self.name = None if self.name: self.Devices[evdev] = { 'name': self.name, 'type': self.getInputDeviceType(self.name), 'enabled': False, 'configuredName': None } if getBoxType().startswith('et'): self.setDefaults( evdev ) # load default remote control "delay" and "repeat" values for ETxxxx ("QuickFix Scrollspeed Menues" proposed by Xtrend Support)
def setRepeat(self, device, value): #REP_PERIOD if self.getDeviceAttribute(device, 'enabled') == True: print "[iInputDevices] setRepeat for device %s to %d ms" % (device,value) event = struct.pack('iihhi', 0, 0, 0x14, 0x01, int(value)) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event) os_close(fd)
def gpiod_chip_open(path: str) -> Optional[gpiod_chip]: """ @brief Open a gpiochip by path. @param path: Path to the gpiochip device file. @return GPIO chip handle or None if an error occurred. """ info = gpiochip_info() try: fd = os_open(path, O_RDWR | O_CLOEXEC) except FileNotFoundError: return None # We were able to open the file but is it really a gpiochip character # device? if not _is_gpiochip_cdev(path): os_close(fd) return None status = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, info) if status < 0: os_close(fd) return None if info.label[0] == "\0": label = "unknown" else: label = info.label.decode() return gpiod_chip( num_lines=info.lines, fd=fd, name=info.name.decode(), label=label )
def match_or_trust(self, host, der_encoded_certificate): base64_encoded_certificate = b64encode(der_encoded_certificate) if isfile(self.path): with open(self.path) as f_in: for line in f_in: known_host, _, known_cert = line.strip().partition(":") known_cert = known_cert.encode("utf-8") if host == known_host: return base64_encoded_certificate == known_cert # First use (no hosts match) try: makedirs(dirname(self.path)) except OSError: pass f_out = os_open(self.path, O_CREAT | O_APPEND | O_WRONLY, 0o600) # TODO: Windows if isinstance(host, bytes): os_write(f_out, host) else: os_write(f_out, host.encode("utf-8")) os_write(f_out, b":") os_write(f_out, base64_encoded_certificate) os_write(f_out, b"\n") os_close(f_out) return True
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: if not evdev.startswith("event"): continue try: buffer = "\0" * 512 self.fd = os_open("/dev/input/" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] os_close(self.fd) except (IOError, OSError), err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str( err) + ' >' self.name = None if self.name: if self.name == 'dreambox front panel': continue if self.name == "dreambox advanced remote control (native)" and config.misc.rcused.value == 1: continue if self.name == "dreambox remote control (native)" and config.misc.rcused.value != 1: continue self.Devices[evdev] = { 'name': self.name, 'type': self.getInputDeviceType(self.name), 'enabled': False, 'configuredName': None }
def setDelay(self, device, value): if self.getDeviceAttribute(device, 'enabled'): print '[iInputDevices] setDelay for device %s to %d ms' % (device, value) event = struct.pack('LLHHi', 0, 0, 20, 0, int(value)) fd = os_open('/dev/input/' + device, O_RDWR) os_write(fd, event) os_close(fd)
def close(self): """Close the lock-file. The Lock object should not be used again after closing. """ if not self.closed: os_close(self.fd) self.closed = True
def download_collection(collection, include_conf=False): directory = collection real_dir = real_directory(directory) dir_name = basename(dirname(real_dir)) fname = '%s.%s' % (dir_name, 'tar.gz') confs = [ 'annotation.conf', 'visual.conf', 'tools.conf', 'kb_shortcuts.conf' ] try: include_conf = int(include_conf) except ValueError: pass tmp_file_path = None try: tmp_file_fh, tmp_file_path = mkstemp() os_close(tmp_file_fh) tar_cmd_split = ['tar', '--exclude=.stats_cache'] conf_names = [] if not include_conf: tar_cmd_split.extend(['--exclude=%s' % c for c in confs]) else: # also include configs from parent directories. for cname in confs: cdir, depth = find_in_directory_tree(real_dir, cname) if depth is not None and depth > 0: relpath = path_join(dir_name, *['..' for _ in range(depth)]) conf_names.append(path_join(relpath, cname)) if conf_names: # replace pathname components ending in ".." with target # directory name so that .confs in parent directories appear # in the target directory in the tar. tar_cmd_split.extend([ '--absolute-names', '--transform', 's|.*\\.\\.|%s|' % dir_name ]) tar_cmd_split.extend(['-c', '-z', '-f', tmp_file_path, dir_name]) tar_cmd_split.extend(conf_names) tar_p = Popen(tar_cmd_split, cwd=path_join(real_dir, '..')) tar_p.wait() hdrs = [ ('Content-Type', 'application/octet-stream'), #'application/x-tgz'), ('Content-Disposition', 'inline; filename=%s' % fname) ] with open(tmp_file_path, 'rb') as tmp_file: tar_data = tmp_file.read() raise NoPrintJSONError(hdrs, tar_data) finally: if tmp_file_path is not None: remove(tmp_file_path)
def setDefaults(self, device): print "[iInputDevices] setDefaults for device %s" % (device) self.setDeviceAttribute(device, 'configuredName', None) event_repeat = struct.pack('iihhi', 0, 0, 0x14, 0x01, 100) event_delay = struct.pack('iihhi', 0, 0, 0x14, 0x00, 700) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event_repeat) os_write(fd, event_delay) os_close(fd)
def loadConfigFile(self): print "[AutomaticVolumeAdjustmentConfig] Loading config file..." self.config = Config() if not os_path.exists(self.CONFIG_FILE): try: fd = os_open(self.CONFIG_FILE, os_O_RDWR | os_O_CREAT) os_close(fd) except Exception, e: print "Error: ", e
def setDefaults(self, device): print "[iInputDevices] setDefaults for device %s" % device self.setDeviceAttribute(device, 'configuredName', None) event_repeat = struct.pack('iihhi', 0, 0, 0x14, 0x01, 100) event_delay = struct.pack('iihhi', 0, 0, 0x14, 0x00, 700) fd = os_open("/dev/input/" + device, O_RDWR) os_write(fd, event_repeat) os_write(fd, event_delay) os_close(fd)
def loadConfigFile(self): print "[AutomaticVolumeAdjustmentConfig] Loading config file..." self.config = Config() if not os_path.exists(self.CONFIG_FILE): try: fd = os_open( self.CONFIG_FILE, os_O_RDWR|os_O_CREAT) os_close( fd ) except Exception, e: print "Error: ", e
def setDefaults(self, device): print '[iInputDevices] setDefaults for device %s' % device self.setDeviceAttribute(device, 'configuredName', None) event_repeat = struct.pack('LLHHi', 0, 0, 20, 1, 100) event_delay = struct.pack('LLHHi', 0, 0, 20, 0, 700) fd = os_open('/dev/input/' + device, O_RDWR) os_write(fd, event_repeat) os_write(fd, event_delay) os_close(fd)
def create_file(self, prefix, filename): full_file_name = "%s%s.txt" % (prefix, filename) file_path = "%s%s" % (self.settings.get_data_folder_path(), full_file_name) try: file = os_open(file_path, O_CREAT | O_EXCL) os_close(file) return full_file_name except IOError as e: log.error("Failed to create a new file! Error: %s", e)
def setDefaults(self, device): print '[InputDevice] setDefaults for device %s' % device self.setDeviceAttribute(device, 'configuredName', None) event_repeat = struct.pack('iihhi', 0, 0, 20, 1, 100) event_delay = struct.pack('iihhi', 0, 0, 20, 0, 700) fd = os_open('/dev/input/' + device, O_RDWR) os_write(fd, event_repeat) os_write(fd, event_delay) os_close(fd) return
def loadConfigFile(self): print "[AutomaticVolumeAdjustmentConfig] Loading config file..." self.config = Config() if not os_path.exists(self.CONFIG_FILE): fd = os_open( self.CONFIG_FILE, os_O_RDWR|os_O_CREAT) os_close( fd ) self.config.loadFromFile(self.CONFIG_FILE) self.config.entriescount = ConfigInteger(0) self.config.Entries = ConfigSubList() self.config.enable = ConfigYesNo(default = False) self.config.adustvalue = ConfigInteger(default=25, limits=(0,95)) self.initConfig()
def download_collection(collection, include_conf=False): directory = collection real_dir = real_directory(directory) dir_name = basename(dirname(real_dir)) fname = '%s.%s' % (dir_name, 'tar.gz') confs = ['annotation.conf', 'visual.conf', 'tools.conf', 'kb_shortcuts.conf'] try: include_conf = int(include_conf) except ValueError: pass tmp_file_path = None try: tmp_file_fh, tmp_file_path = mkstemp() os_close(tmp_file_fh) tar_cmd_split = ['tar', '--exclude=.stats_cache'] conf_names = [] if not include_conf: tar_cmd_split.extend(['--exclude=%s' % c for c in confs]) else: # also include configs from parent directories. for cname in confs: cdir, depth = find_in_directory_tree(real_dir, cname) if depth is not None and depth > 0: relpath = path_join( dir_name, *['..' for _ in range(depth)]) conf_names.append(path_join(relpath, cname)) if conf_names: # replace pathname components ending in ".." with target # directory name so that .confs in parent directories appear # in the target directory in the tar. tar_cmd_split.extend(['--absolute-names', '--transform', 's|.*\\.\\.|%s|' % dir_name]) tar_cmd_split.extend(['-c', '-z', '-f', tmp_file_path, dir_name]) tar_cmd_split.extend(conf_names) tar_p = Popen(tar_cmd_split, cwd=path_join(real_dir, '..')) tar_p.wait() hdrs = [('Content-Type', 'application/octet-stream'), # 'application/x-tgz'), ('Content-Disposition', 'inline; filename=%s' % fname)] with open(tmp_file_path, 'rb') as tmp_file: tar_data = tmp_file.read() raise NoPrintJSONError(hdrs, tar_data) finally: if tmp_file_path is not None: remove(tmp_file_path)
def render_POST(self, req): isXml = 'xml' in req.args and req.args['xml'][0] == 'True' uploaddir = self.default_uploaddir if req.args['path'][0]: if os_path.isdir(req.args['path'][0]): uploaddir = req.args['path'][0] if uploaddir[-1] != "/": uploaddir += "/" else: return self.out_POST( req, False, "path '%s' to upload not existing!" % req.args['path'][0], isXml) data = req.args['file'][0] if not data: return self.out_POST(req, False, "filesize was 0, not uploaded", isXml) # allw to overwrite files (if the user requests it), but not in critical directories overwrite = 'overwrite' in req.args and req.args['overwrite'][ 0] == 'True' if overwrite and uploaddir in self.restricted_paths: overwrite = False try: matches = search('.*?filename="(.*?)"\r\n.*?', req.content.getvalue()) fn = os_path.join(uploaddir, matches.group(1)) except Exception as e: fn = None # NOTE: we only accept the given filename if no such file exists yet or the user requested it AND we think its safe if fn and (overwrite or not os_path.exists(fn)): fd = os_open(fn, O_WRONLY | O_CREAT) else: fd, fn = mkstemp(dir=uploaddir) cnt = os_write(fd, data) os_close(fd) os_chmod(fn, 0o755) if cnt <= 0: # well, actually we should check against len(data) but lets assume we fail big time or not at all try: os_unlink(fn) except OSError as oe: pass return self.out_POST(req, False, "error writing to disk, not uploaded", isXml) else: statetext = fn if isXml else "uploaded to %s" % fn return self.out_POST(req, True, statetext, isXml)
def _handle_execute(execute_file, execute_args, stdin_file, stdout_file, stderr_file, extra_file, cgroup_file): pid = fork() if not pid: chdir('/in/package') if stdin_file: fd = os_open(stdin_file, O_RDONLY) dup2(fd, STDIN_FILENO) os_close(fd) if stdout_file: fd = os_open(stdout_file, O_WRONLY) dup2(fd, STDOUT_FILENO) os_close(fd) if stderr_file: fd = os_open(stderr_file, O_WRONLY) dup2(fd, STDERR_FILENO) os_close(fd) if extra_file: fd = os_open(extra_file, O_RDONLY) if fd == EXTRA_FILENO: set_inheritable(fd, True) else: dup2(fd, EXTRA_FILENO) os_close(fd) if cgroup_file: enter_cgroup(cgroup_file) execve(execute_file, execute_args, SPAWN_ENV) return wait_and_reap_zombies(pid)
def __del__(self): from os import close as os_close, unlink # self.__buffer.close() try: os_close(self.__fd) except OSError: pass try: unlink(PLUGIN_PATH + self.__plugin_name) except OSError: pass
def _handle_compile(compiler_file, compiler_args, output_file, cgroup_file): pid = fork() if not pid: chdir('/out') os_close(STDIN_FILENO) if output_file: fd = os_open(output_file, O_WRONLY) dup2(fd, STDOUT_FILENO) dup2(fd, STDERR_FILENO) os_close(fd) if cgroup_file: enter_cgroup(cgroup_file) execve(compiler_file, compiler_args, SPAWN_ENV) return wait_and_reap_zombies(pid)
def __del__(self): from os import close as os_close, unlink #self.__buffer.close() try: os_close(self.__fd) except OSError: pass try: unlink(PLUGIN_PATH + self.__plugin_name) except OSError: pass
def gpiod_chip_close(chip: gpiod_chip): """ @brief Close a GPIO chip handle and release all allocated resources. @param chip: The GPIO chip object. """ if len(chip.lines) > 0: for i in range(chip.num_lines): line = chip.lines[i] if line is not None: gpiod_line_release(line) os_close(chip.fd) # How to free the chip object? del chip
def loadConfigFile(self): print "[AutomaticVolumeAdjustmentConfig] Loading config file..." self.config = Config() if not os_path.exists(self.CONFIG_FILE): fd = os_open( self.CONFIG_FILE, os_O_RDWR|os_O_CREAT) os_close( fd ) self.config.loadFromFile(self.CONFIG_FILE) self.config.entriescount = ConfigInteger(0) self.config.Entries = ConfigSubList() self.config.enable = ConfigYesNo(default = False) self.config.modus = ConfigSelection(choices = [("0", _("Automatic volume adjust")), ("1", _("Remember service volume value"))], default = "0") self.config.adustvalue = ConfigSelectionNumber(-50, 50, 5, default = 25) self.config.mpeg_max_volume = ConfigSelectionNumber(10, 100, 5, default = 100) self.config.show_volumebar = ConfigYesNo(default = False) self.initConfig()
def getInputDevices(self): devices = listdir("/dev/input") for evdev in devices: try: buffer = "\0"*512 self.fd = os_open("/dev/input/by-id" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] os_close(self.fd) except (IOError,OSError), err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str(err) + ' >' self.name = None if self.name: self.Devices[evdev] = {'name': self.name, 'type': self.getInputDeviceType(self.name),'enabled': False, 'configuredName': None }
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: try: buffer = "\0"*512 self.fd = os_open("/dev/input/" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] os_close(self.fd) except (IOError,OSError), err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str(err) + ' >' self.name = None if self.name: self.Devices[evdev] = {'name': self.name, 'type': self.getInputDeviceType(self.name),'enabled': False, 'configuredName': None }
def lock_dir(path): path = path_join(path, '_-lock') fd = os_open(path, O_WRONLY | O_CREAT, 0o0600) try: for x in xrange(100): try: flock(fd, LOCK_EX | LOCK_NB) break except IOError as err: if err.errno != EAGAIN: raise sleep(0.1) else: raise Exception('Timeout 10s trying to get lock on %r' % path) yield True finally: os_close(fd)
def lock_dir(path): path = path_join(path, '_-lock') fd = os_open(path, O_WRONLY | O_CREAT, 0o0600) try: for x in moves.range(100): try: flock(fd, LOCK_EX | LOCK_NB) break except IOError as err: if err.errno != EAGAIN: raise sleep(0.1) else: raise Exception('Timeout 10s trying to get lock on %r' % path) yield True finally: os_close(fd)
def render_POST(self, req): uploaddir = self.default_uploaddir print "[UploadTextResource] req.args ", req.args if req.args['path'][0]: if os_path.isdir(req.args['path'][0]): uploaddir = req.args['path'][0] if uploaddir[-1] != "/": uploaddir += "/" else: print "[UploadTextResource] not a dir", req.args['path'][0] req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "path '%s' to upload not existing!" % req.args['path'][0] if uploaddir[: 10] == "/etc/opkg/" or uploaddir[: 12] == "/usr/script/": pass else: req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "illegal upload directory: " + req.args['path'][0] data = req.args['text'][0].replace('\r\n', '\n') if not data: req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "filesize was 0, not uploaded" else: print "[UploadTextResource] text:", data filename = req.args['filename'][0] fd, fn = mkstemp(dir=uploaddir) cnt = os_write(fd, data) os_close(fd) os_chmod(fn, 0755) if cnt <= 0: # well, actually we should check against len(data) but lets assume we fail big time or not at all try: os_unlink(fn) except OSError, oe: pass req.setResponseCode(http.OK) req.setHeader('Content-type', 'text/html') return "error writing to disk, not uploaded"
def read_from_file(file): fdno = None try: fdno = os_open(file, O_RDONLY) # Using rpm._RPMVSF_NOSIGNATURES seems like the only way to get to that value #pylint: disable=protected-access ts = rpm.TransactionSet('', rpm._RPMVSF_NOSIGNATURES) h = ts.hdrFromFdno(fdno) return h except FileNotFoundError as e: raise Error("Error reading rpm file [%s]: %s" % (file, e.strerror)) from e except rpm.error as e: raise Error("Error reading rpm file [%s]: %s" % (file, str(e))) from e finally: if fdno: os_close(fdno)
def render_POST(self, req): uploaddir = self.default_uploaddir print "[UploadTextResource] req.args ", req.args if req.args["path"][0]: if os_path.isdir(req.args["path"][0]): uploaddir = req.args["path"][0] if uploaddir[-1] != "/": uploaddir += "/" else: print "[UploadTextResource] not a dir", req.args["path"][0] req.setResponseCode(http.OK) req.setHeader("Content-type", "text/html") return "path '%s' to upload not existing!" % req.args["path"][0] if uploaddir[:10] == "/etc/opkg/" or uploaddir[:12] == "/usr/script/": pass else: req.setResponseCode(http.OK) req.setHeader("Content-type", "text/html") return "illegal upload directory: " + req.args["path"][0] data = req.args["text"][0].replace("\r\n", "\n") if not data: req.setResponseCode(http.OK) req.setHeader("Content-type", "text/html") return "filesize was 0, not uploaded" else: print "[UploadTextResource] text:", data filename = req.args["filename"][0] fd, fn = mkstemp(dir=uploaddir) cnt = os_write(fd, data) os_close(fd) os_chmod(fn, 0755) if cnt <= 0: # well, actually we should check against len(data) but lets assume we fail big time or not at all try: os_unlink(fn) except OSError, oe: pass req.setResponseCode(http.OK) req.setHeader("Content-type", "text/html") return "error writing to disk, not uploaded"
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: try: buffer = "\0"*512 self.fd = os_open("/dev/input/" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] if str(self.name).find("Keyboard") != -1: self.name = 'keyboard' os_close(self.fd) except (IOError,OSError), err: print '[iInputDevices] getInputDevices ' + evdev + ' <ERROR: ioctl(EVIOCGNAME): ' + str(err) + ' >' self.name = None if self.name: self.Devices[evdev] = {'name': self.name, 'type': self.getInputDeviceType(self.name),'enabled': False, 'configuredName': None } if boxtype.startswith('et'): self.setDefaults(evdev) # load default remote control "delay" and "repeat" values for ETxxxx ("QuickFix Scrollspeed Menues" proposed by Xtrend Support)
def process_file(device, owner, i): name = file_name % { 'device': device.code_name, 'num': i } # yes it hits the database twice, but oh well try: req = create_request(owner.user, device, name) except FileExists: # raises RequestExists as well, but we won't get that return t = mkstemp() f = open(t[1], 'wb') f.write(str.encode(req.reference)) f.close() f = open(t[1], 'rb') f = DJFile(f) handle_file_upload(f, req) f.close() os_close(t[0]) remove(t[1])
def getInputDevices(self): devices = listdir("/dev/input") for evdev in devices: try: buffer = "\0" * 512 self.fd = os_open("/dev/input/by-id" + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[: self.name.find("\0")] os_close(self.fd) except (IOError, OSError), err: print "[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): " + str(err) + " >" self.name = None if self.name: self.Devices[evdev] = { "name": self.name, "type": self.getInputDeviceType(self.name), "enabled": False, "configuredName": None, }
def silence(fd: "File descripter"): """ silence(fd) -> Silence any output from fd. """ from os import dup as os_dup from os import pipe as os_pipe from os import dup2 as os_dup2 from os import close as os_close from os import fdopen as os_fdopen # Backup the file old_fd = fd # Flush the file so it can be silenced properly. fd.flush() # Create a duplicate of fd new_fd = os_dup(fd.fileno()) # Create a pipe to write to. read, write = os_pipe() # Set the write to the fd filenumber os_dup2(write, fd.fileno()) # Close the pipe. os_close(write) os_close(read) # Set fd to the new fd fd = os_fdopen(new_fd, "w") try: # Run the commands in the 'with' statement. yield finally: # Return the fd back to its original state. os_dup2(fd.fileno(), old_fd.fileno()) fd = old_fd
def getInputDevices(self): devices = listdir("/dev/input/") for evdev in devices: try: buffer = "\0"*512 fd = os_open("/dev/input/" + evdev, O_RDWR | O_CLOEXEC) self.name = ioctl(fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find("\0")] os_close(fd) except (IOError,OSError), err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str(err) + ' >' self.name = None if self.name: if self.name == 'dreambox front panel': continue if self.name == "dreambox advanced remote control (native)" and config.misc.rcused.value not in (0, 2): continue if self.name == "dreambox remote control (native)" and config.misc.rcused.value in (0, 2): continue self.Devices[evdev] = {'name': self.name, 'type': self.getInputDeviceType(self.name),'enabled': False, 'configuredName': None }
def getInputDevices(self): devices = listdir('/dev/input/') for evdev in devices: try: buffer = '\x00' * 512 self.fd = os_open('/dev/input/' + evdev, O_RDWR | O_NONBLOCK) self.name = ioctl(self.fd, EVIOCGNAME(256), buffer) self.name = self.name[:self.name.find('\x00')] if str(self.name).find('Keyboard') != -1: self.name = 'keyboard' os_close(self.fd) except (IOError, OSError) as err: print '[iInputDevices] getInputDevices <ERROR: ioctl(EVIOCGNAME): ' + str(err) + ' >' self.name = None if self.name: self.Devices[evdev] = {'name': self.name, 'type': self.getInputDeviceType(self.name), 'enabled': False, 'configuredName': None} if boxtype.startswith('et'): self.setDefaults(evdev)
def render_POST(self, req): req.setResponseCode(http.OK) req.setHeader('Content-type', 'application/xhtml+xml;' ) req.setHeader('charset', 'UTF-8') data = req.args['file'][0] if not data: result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <e2simplexmlresult>\n <e2state>False</e2state> <e2statetext>Filesize was 0, not uploaded</e2statetext> </e2simplexmlresult>\n""" return result fd = os_open( self.FILENAME, os_O_WRONLY|os_O_CREAT ) if fd: cnt = os_write(fd, data) os_close(fd) if cnt <= 0: try: os_remove(FILENAME) except OSError, oe: pass result = """<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n
def daemonize(): from os import ( EX_OK, devnull, O_RDWR, fork, open as os_open, close as os_close, ) if fork(): exit(EX_OK) for fd in range(0, 3): try: os_close(fd) except OSError: pass os_open(devnull, O_RDWR) os_open(devnull, O_RDWR) os_open(devnull, O_RDWR)