def attempt_loop(function, max_attempts, try_all=False): attempt_count = 0 success_count = 0 last_error = None while attempt_count < max_attempts: try: if try_all: function() else: return function() success_count += 1 log.i('Success of attempt {} of {}'.format( attempt_count + 1, max_attempts)) except Exception as e: last_error = e log.e('Failure of attempt {} of {}: {}'.format( attempt_count + 1, max_attempts, e)) attempt_count += 1 time.sleep(0.5) # to increase robustness if success_count == 0: log.e( 'No successful attempt in any of the {} attempts. Last error:' .format(max_attempts)) raise last_error
def check(self): steamvr_running = self.is_steamvr_running() # log.d('Stage: {} steamvr_running {}'.format(self.current_stage, steamvr_running)) if self.current_stage == self.Stages.BEFORE_STEAMVR: if steamvr_running: self.update_stage(self.Stages.DURING_STEAMVR) elif self.start_of_current_stage + 60 <= time.time(): log.e("SteamVR never started, exiting. Looking for a process with this name: {}".format( self.config.daemon_watch_process_name())) self.steamvr_utils.turn_off() log.i("Exiting...") return False elif self.current_stage == self.Stages.DURING_STEAMVR: if not steamvr_running: self.update_stage(self.Stages.AFTER_STEAMVR) elif self.current_stage == self.Stages.AFTER_STEAMVR: if steamvr_running: self.update_stage(self.Stages.DURING_STEAMVR) elif self.start_of_current_stage + self.config.daemon_wait_after_quit() <= time.time(): self.steamvr_utils.turn_off() log.i("Exiting...") return False return True
def switch_handler(s, conn, addr): ucon = upconnection.load(s, conn, addr) alternative_args = { 'socket' : s, 'addr' : s.getsockname()[0], 'port' : s.getsockname()[1], 'conn' : conn, 'ucon' : ucon, } while 1: ucon.recv() suc_match = False for tup in handler_list: match = re.match(tup[0], ucon.rfile) if match: suc_match = True args = [] for key in tup[2]: if key in alternative_args: args.append(alternative_args[key]) elif key == 'regex': args += match.groups() else: log.e("Unknown key {}".format(key)) sdata = tup[1](*args) if sdata: ucon.send(sdata) break if not ucon.alive or not suc_match: ucon.close() break
def read(args): """ Read configuration (possibly pointed by args) """ if debug: log.w("DEBUGGING ENABLED! YOUR DATA MAY BE EXPOSED!") v = vars(args) global verbose if 'verbose' in v: verbose = v['verbose'] user_config_parser = ConfigParser.ConfigParser() try: if 'config' in v and v['config'] != None: f = open(v['config']) user_config_parser.readfp(f) else: try: f = open('.cryptoboxrc') user_config_parser.readfp(f) except: try: f = open('~/.cryptoboxrc') user_config_parser.readfp(f) except: pass except Exception as e: log.e("Could not load user config!") log.e(str(e)) sys.exit(1) return read_user_config(user_config_parser)
def rescan_all_cards(): arguments = ['pactl', 'load-module', 'module-detect'] return_code, stdout, stderr = utlis.run(arguments) if return_code != 0: log.e('\'{}\' () failed, stderr:\n{}'.format( " ".join(arguments), stderr))
def recv(self): self.raw_recv() if not '\r\n\r\n' in self.data: log.e('Unable to parse the data:{}.'.format(self.data)) self.alive = False return proto_headers, self.body = self.data.split('\r\n\r\n', 1) proto, headers = proto_headers.split('\r\n', 1) result = re.match(r'(GET|POST)\s+(\S+)\s+HTTP/1.1', proto) if not result: log.e('unsupported protocol') exit(1) self.method, res = result.groups() if res[0] == '/': res = res[1:] lis = res.split('?') lis.append('') self.rfile, query_string = lis[0:2] self.params = [tuple((param+'=').split('=')[0:2]) for param in query_string.split('&')] ma_headers = re.findall(r'^\s*(.*?)\s*:\s*(.*?)\s*\r?$', headers, re.M) self.headers = {item[0]:item[1] for item in ma_headers} #log.d("rfile : {}\nparams : {}\nheaders : {}\nbody : {}".format(self.rfile, str(self.params), str(self.headers), self.body)) if not self.headers.get('connection') \ or 'keep-alive' != self.headers['connection'].lower(): self.alive = False
def local_type(self, filename): if filename: f = open(filename, 'r') lines = f.read() f.close() log.i(lines) else: log.e('Missing filename')
def receive_file(self, filename): mode = self.config['mode'].value if mode == C['mode']['timeout']: self.receive_file_timeout(filename) elif mode == C['mode']['watchars']: self.receive_file_watchars(filename) else: log.e('Invalid mode {}'.format(mode))
def write_packet(self, pkt): if not pkt: log.e('No packet to write') return False lst = pkt.to_list() if self.config['debug'].value: log.i('Sending {}'.format(lst)) self.transport.write_bytes(bytearray(lst)) return True
def main( p_port ) : if p_port == 0 : print 'port could not be set as 0' log.e( 'port could not be set as 0' ) exit( 1 ) log.c( 'www listening on port : %s' % p_port ) app = Application() app.listen( p_port ) tornado.ioloop.IOLoop.instance().start()
def _send_bytes(self, name, bytes): try: packets = self._bytes_to_packets(name, bytes) self._send_packets(packets) return True except KeyboardInterrupt as ki: log.e('Aborting') self.send_abort() return False
def read_data(self, dbg, addr, size, ignore_limit=False): addr = self.get_value(addr) size = self.get_value(size) try: buf = self.read_process_memory(dbg, addr, size, ignore_limit) return buf except Exception, e: log.e("Error in read_data(). " + e.message) return "Error in read_data()" + e.message
def read_data(self, dbg, addr , size, ignore_limit = False): addr = self.get_value(addr) size = self.get_value(size) try: buf = self.read_process_memory(dbg, addr, size, ignore_limit) return buf except Exception,e: log.e("Error in read_data(). "+ e.message) return "Error in read_data()" + e.message
def main(connection=None): client = get_client(connection) try: while client.IsConnected(): if client.GetFrame(): logger.info(get_data(client, 'test')) except ViconDataStream.DataStreamException as e: log.e(f'Error: {e}')
def set(self, line): cmd, tail = util.parse_cmdline2(line, self.config, log) if not cmd: log.e('Name not found: {}'.format(line)) return if cmd == 'receive': log.i('Cannot set receive') return util.set_config(line, self.config, kprotocol.C, log)
def local_push(self): shell = self.config['shell'].value if shell: os.system(shell) elif os.name == 'posix': os.system('bash') elif os.name == 'nt': os.system('command.com') else: log.e("Unknown shell. (Set the 'shell' config value)")
def main(): actions = { SteamvrUtils.Action.ON: ['on', '1'], SteamvrUtils.Action.OFF: ['off', '0'], SteamvrUtils.Action.DAEMON: ['daemon', 'd'], SteamvrUtils.Action.CONFIG_HELP: ['config-help', 'c'] } parser = argparse.ArgumentParser() parser.add_argument('action', choices=[ keyword for _, keywords in actions.items() for keyword in keywords ], help='action to perform on the Base Stations') parser.add_argument( '--dry-run', help= 'Do not modify anything (bluetooth connections are still made, but never used to write).', action='store_true') parser.add_argument('--config', default=None, help='Path to a config file.') parser.add_argument( '--version', action='version', version='steamvr_utils {version}'.format(version=__version__)) args = parser.parse_args() config = Config(config_path=args.config, dry_run_overwrite=args.dry_run) log.initialise(config) # noinspection PyBroadException try: selected_action = None for action in SteamvrUtils.Action: if args.action in actions[action]: selected_action = action if selected_action == SteamvrUtils.Action.CONFIG_HELP: config_helper = ConfigHelper(config) config_helper.print_help() return log.i('steamvr_utils version: {}'.format(__version__)) log.d('dry_run: {}'.format(config.dry_run())) steamvr_utils = SteamvrUtils(config=config) steamvr_utils.action(selected_action) except Exception: log.e('', exc_info=True) exit(1)
def set_profile(self, config, profile): if config.dry_run(): log.w('Skipping because of dry run') return arguments = ['pactl', 'set-card-profile', self.name, profile.name] return_code, stdout, stderr = utlis.run(arguments) if return_code != 0: log.e('\'{}\' () failed, stderr:\n{}'.format( " ".join(arguments), stderr))
def hook(self, dbg): if self.__active: return self.address = self.get_address(dbg) if self.address is None or self.address == 0x0: log.e("[!] Fail to hook %s: invalid address %#x"%(self.func, self.address)) return False try: dbg.bp_set(self.address, restore=True, handler=self.__proxy_on_entry) except Exception,e: log.e("[!] Fail to hook %s: %s" % (self.func,e.message)) return False
def find_matching_sink(sinks, regex, name): vr_matches = [sink for sink in sinks if re.match(regex, sink.name)] if len(vr_matches) == 1: return vr_matches[0] elif len(vr_matches) == 0: log.e( 'No {} audio sink for the normal device was found. Tried to find a match for: {}' .format(name, regex)) else: raise RuntimeError( 'Multiple matches for the {} audio sink found. Tried to find a match for: {}' .format(name, regex))
def set_stream_for_all_stream_connections(self, stream): if self.config.dry_run(): log.w('Skipping because of dry run') return # verify stream name exists before proceeding streams = self.get_all_streams() found = False for s in streams: if s.name == stream.name: found = True if not found: log.w('Skipping {} since the {} name does not exist'.format( self.get_move_stream_connection_command(), self.get_stream_type_name())) return stream_connections = self.get_all_stream_connections() pactl_interface.Client.get_client_names(stream_connections) stream_connections = self.filter_by_client_name(stream_connections) for stream_connection in stream_connections: failure = \ ([failure for failure in self.failed_stream_connections if failure.stream_connection_id == stream_connection.id] + [ None])[0] if failure is not None and not failure.try_again(): continue arguments = [ 'pactl', self.get_move_stream_connection_command(), str(stream_connection.id), stream.name ] log.w("move {}".format(" ".join(arguments))) return_code, stdout, stderr = pactl_interface.utlis.run( arguments, assert_success=False) if return_code != 0: if failure is None: failure = self.Failure(stream_connection.id) self.failed_stream_connections.append(failure) else: failure.add_attempt() log.e( '\'{}\' (client_name: {}) failed (count: {}), stderr:\n{}'. format(" ".join(arguments), stream_connection.client_name, failure.failure_count, stderr)) self.output_logger.log_all()
def find_matching_stream(self, streams, regex, name): matches = [ stream for stream in streams if re.match(regex, stream.name) ] if len(matches) == 1: return matches[0] elif len(matches) == 0: log.e('No {} audio {} was found. Tried to find a match for: {}'. format(name, self.stream_type, regex)) else: raise RuntimeError( 'Multiple matches for the {} audio {} found. Tried to find a match for: {}' .format(name, self.stream_type, regex))
def _init_api(connection=None, host="127.0.0.1", port="5000"): try: client = get_client(connection) except Exception as e: log.e("Failed to connect to client") log.e(e.message) client = None app = Flask("vicon-ds") api = Api(app) try: sensor = setup_phidget() except Exception as e: log.e("Failed to connect to sensor") log.e(e) sensor = None class ViconMarkerStream(Resource): def get(self, data_type, subject_name): if client is not None and client.IsConnected() and client.GetFrame( ): return get_data(client, data_type, subject_name) return "restart: client didn't connect", 404 api.add_resource(ViconMarkerStream, '/<string:data_type>/<string:subject_name>') try: app.run(host=host, port=int(port)) finally: if sensor is not None: sensor.close()
def hook(self, dbg): if self.__active: return self.address = self.get_address(dbg) if self.address is None or self.address == 0x0: log.e("[!] Fail to hook %s: invalid address %#x" % (self.func, self.address)) return False try: dbg.bp_set(self.address, restore=True, handler=self.__proxy_on_entry) except Exception, e: log.e("[!] Fail to hook %s: %s" % (self.func, e.message)) return False
def _write_file(self, filename, bufdat): try: if len(bufdat) == 0: return while bufdat[-1] == 0x00: # HP pads with 0x00 del bufdat[-1] bufdat.append(0x00) # HP objects must end with null. log.i('Received ' + str(len(bufdat)) + ' bytes') log.i('Saving to file ' + filename) f = open(filename, 'wb') f.write(bytearray(bufdat)) f.close() except IOError as err: log.e('Failed to write file ' + filename) return False return True
def __getContent(url, requestHeaders=None): if requestHeaders == None: requestHeaders = headers try: log.d("GET - {0} [{1}]".format(url, requestHeaders)) response = urllib2.urlopen(urllib2.Request(url, headers=requestHeaders)) result = response.read() # log.d("RESPONSE - {0}".format(result)) return result except urllib2.URLError as error: log.e(str(error)) return None
def set_suspend_state(self, config, state): if config.dry_run(): log.w('Skipping because of dry run') return if state: state = "true" else: state = "false" arguments = ['pactl', 'suspend-sink', self.name, state] log.d('set_suspend_state {}'.format(' '.join(arguments))) return_code, stdout, stderr = utlis.run(arguments) if return_code != 0: log.e('\'{}\' () failed, stderr:\n{}'.format(" ".join(arguments), stderr))
def handle_data(dataFromClient): data_valid = True try: obj = json.loads(dataFromClient) except: data_valid = False if not data_valid or not obj.get('header'): log.e('ws get invalid data (len={}):{}'.format(len(dataFromClient), ','.join('%x'%(ord(i)) for i in dataFromClient))) return {"header":"unknown"} switcher = { 'init':responseInit, 'update':responseUpdate, } retObj = switcher[obj['header']](obj) if not 'header' in retObj: retObj['header'] = obj['header'] return retObj
def _send_then_receive(self, pkt, max_retries=5): # Difficult because initial write_packet() may not be received # correctly and, per Kermit protocol, we do not get an ACK (but might # get a NACK). # # For 'receive_initiate' (R): # "...the only two valid responses to a successfully received R packet # are an S packet or an E packet. The R packet is not ACK'd." p. 26 self.transport.clear_buffer() retries = 0 while retries < max_retries: pkt_in = self._write_verify(pkt) if pkt_in and pkt_in.type != 'N': self._receive(pkt_in) return retries += 1 log.e('Failed to send command {}'.format(pkt.payload))
def parse_args(): args = ''.join(sys.argv[1:]) regexs = [ (r'^(\d+\.\d+\.\d+\.\d+):(\d+)$', lambda x:(x.group(1),x.group(2))), (r'^(\d+)$', lambda x:('127.0.0.1', x.group(1))), (r'^(\d+\.\d+\.\d+\.\d+)$', lambda x:(x.group(1), '8080')) ] for regex in regexs: result = re.match(regex[0], args) if result: addr, port = regex[1](result) return addr, int(port) log.e('Invalid IP address or port !!!') exit(0)
def set_sink_for_all_sink_inputs(self, sink): if self.config.dry_run(): log.w('Skipping because of dry run') return # verify sink name exists before proceeding sinks = pactl_interface.Sink.get_all_sinks(self) found = False for s in sinks: if s.name == sink.name: found = True if not found: log.w( 'Skipping move-sink-input since the sink name does not exist') return sink_inputs = pactl_interface.SinkInput.get_all_sink_inputs(self) pactl_interface.Client.get_client_names(sink_inputs) sink_inputs = self.filter_by_client_name(sink_inputs) for sink_input in sink_inputs: failure = \ ([failure for failure in self.failed_sink_inputs if failure.sink_input_id == sink_input.id] + [None])[0] if failure is not None and not failure.try_again(): continue arguments = [ 'pactl', 'move-sink-input', str(sink_input.id), sink.name ] return_code, stdout, stderr = pactl_interface.utlis.run(arguments) if return_code != 0: if failure is None: failure = self.Failure(sink_input.id) self.failed_sink_inputs.append(failure) else: failure.add_attempt() log.e( '\'{}\' (client_name: {}) failed (count: {}), stderr:\n{}'. format(" ".join(arguments), sink_input.client_name, failure.failure_count, stderr)) self.log_state()
def on_exit(self, dbg): # Fill context. self.ret_value = dbg.context.Eax # Save hook context to info_man.hook_infos, before calling # user-defined handler. # This will be submited to InfoManager earlier before # user-defined DbgInfo does. self.save() # Call user-defined handler. if self.func.exit_hook: try: global_exit_hook(self, dbg) self.func.exit_hook(self, dbg) except Exception, e: log.e("Exception %s in exit_hook of %s:\n %s" % (e, self.func, traceback.format_exc()))
def local_directory(self, line=''): DIR_HEADER = '\x01' dir = os.getcwd() filenames = [] if os.path.isdir(line) or not line: if line: dir = line filenames = os.listdir(dir) else: specs = shlex.split(line) for spec in specs: filenames.extend(glob.glob(spec)) entries = [] for filename in filenames: abspath = os.path.join(dir, filename) if os.path.isdir(abspath): filename = '{}[{}]'.format(DIR_HEADER, filename) s = os.stat(abspath) filesize = s.st_size lastmodified = s.st_mtime entries.append((lastmodified, filesize, filename)) # Sort is stable. order_by = util.key_for_val(kprotocol.C['order-by'], self.config['order-by'].value) for ch in order_by[::-1]: if ch == 'd': entries.sort(key=lambda tup: tup[0]) elif ch == 's': entries.sort(key=lambda tup: tup[1]) elif ch == 'n': entries.sort(key=lambda tup: tup[2]) else: log.e('Bad field char {}'.format(ch)) oslope = self.config['oslope'].value for entry in entries[::oslope]: dt = datetime.datetime.fromtimestamp( entry[0]).strftime('%Y-%m-%d %H:%M') sz = util.format_si(entry[1]) nm = entry[2] if nm.startswith(DIR_HEADER): nm = nm[1:] log.i(' {} {} {}'.format(dt, sz, nm))
def requestSearch(self, keyword): log.d("search keyword: " + getDecodedString(keyword)) self.origin_search = keyword self.search = getUtf8String(keyword) count = config.getSearchCount() request_string = "/v2/movie/search?count=" + str( count) + "&q=" + self.search log.d("req: http://api.douban.com" + request_string) conn = httplib.HTTPConnection("api.douban.com") conn.request("GET", request_string) res = conn.getresponse() ret = res.read() if (res.status == 200): log.d("res: " + str(res.status) + ", " + str(res.reason) + ", " + ret) return ret else: log.e("res: " + str(res.status) + ", " + str(res.reason) + ", " + ret)
def _unescape_payload(self, payload): buf = [] pos = 0 while pos < len(payload): byte = payload[pos] if byte == self.config['receive']['ctl-prefix'].value: pos += 1 if pos < len(payload): byte2 = payload[pos] n = ord(byte2) & 0x7F if ctl(n) < 32 or ctl(n) == 127: buf.append(chr(ctl(ord(byte2)))) else: buf.append(byte2) else: log.e('Bad payload length') else: buf.append(byte) pos += 1 return buf
def __init__(self, args=default_args): self.prompt = PROMPTER self.scripts = [] self.arg_cmds = [] self.arg_flag = True self.cmd_proc = None self.done = False self.config = { 'exit-on-error': CV(C['exit-on-error']['false'], bool, 'Exit on error'), 'trace-on-error': CV(C['trace-on-error']['true'], bool, 'Print stack trace on error'), 'local-echo': CV(C['local-echo']['true'], bool, 'Echo command line locally'), 'log-level': CV(5, int, 'Set log level'), 'wav-prefix': CV('', str, 'Set wav prefix'), } self.transport = transport.Transport(args.showinit, args.wavprefix, args.framerate, args.sensitivity) self.kermit_cmd_proc = KermitCmds(self.transport) self.serial_cmd_proc = SerialCmds(self.transport) self.xmodem_cmd_proc = XmodemCmds(self.transport) init_file = args.init if init_file and (init_file != DEFAULT_INI_FILE or os.path.exists(init_file)): log.i('Reading init script {}'.format(init_file)) try: self.scripts = read_scripts(init_file) except IOError: log.e('Error reading {}'.format(init_file)) self.arg_cmds = self.proc_args(args)
def act(self, game): if Robot._turn != game.turn: Robot._gs = GameState(game) Robot._turn = game.turn Robot._ai.compute_commands(Robot._gs) for bot in Robot._gs.friends: if bot.robot_id == self.robot_id: cmd = bot.get_command() if cmd != None: if cmd == CMD_SUICIDE: return ['suicide'] elif cmd == CMD_GUARD: return ['guard'] elif IS_MOVE[cmd]: r = CELL_R[CELL_MOVE[cmd]] c = CELL_C[CELL_MOVE[cmd]] return ['move', (c, r)] elif IS_ATTACK[cmd]: r = CELL_R[CELL_ATTACK[cmd]] c = CELL_C[CELL_ATTACK[cmd]] return ['attack', (c, r)] else: log.e('Unrecognized command! Suiciding... Bot: ' + str(bot)) return ['suicide'] else: log.e('No command found! Suiciding... Bot: ' + str(bot)) return ['suicide'] log.e('Bot was not found! Something has gone horribly wrong. Suiciding... robot_id: ' + str(self.robot_id)) return ['suicide']
def on_entry(self, dbg): # Fill context. This may be used in self.func.exit_hook(). self.tid = dbg.dbg.dwThreadId self.pid = dbg.dbg.dwProcessId self.ret_addr = dbg.get_arg(0) self.args = self.get_args(dbg) if not self.module: module = dbg.addr_to_module(self.ret_addr) if module: self.module = module.szModule.lower() else: self.module = "UNKNOWN" # Call user-defined handler. if self.func.entry_hook: try: global_entry_hook(self, dbg) self.func.entry_hook(self, dbg) except Exception, e: log.e("Exception %s in entry_hook of %s:\n %s" % (e, self.func, traceback.format_exc()))
def looper(self, args): except_count = 0 history_file = '.hpirhist' exit_val = EXIT_OK d = None try: log.set_log_level(args.log) read_history_file(history_file) d = dispatcher.Dispatcher(args) d.start_transport() while not d.is_done(): try: d.read_and_exec() except_count = 0 except: except_count += 1 log.i('') # Ensure the following error message starts on a new line. log.e('{} : {}'.format(sys.argv[0], sys.exc_info()[1])) if d.is_trace_on_error(): print traceback.format_exc() if (except_count >= 2) or d.is_exit_on_error(): exit_val = EXIT_ERR d.force_done() write_history_file(history_file) except: exit_val = EXIT_ERR print traceback.format_exc() finally: if d: d.stop_transport() return exit_val
def handler_rip(dbg): log.e("RIP Event:", dbg) log.e("Error code:%#x" % dbg.u.RipInfo.dwError, dbg) log.e("Error type:%#x" % dbg.u.RipInfo.dwType, dbg.dwProcessId,dbg.tid) return DBG_CONTINUE
] tornado.web.ErrorHandler = guest.PageNotFoundHandler tornado.web.Application.__init__( self, handlers, **settings ) def main( p_port ) : if p_port == 0 : print 'port could not be set as 0' log.e( 'port could not be set as 0' ) exit( 1 ) log.c( 'www listening on port : %s' % p_port ) app = Application() app.listen( p_port ) tornado.ioloop.IOLoop.instance().start() #define("port", default=8888, help="run on the given port", type=int) port = 0 try : port = int( sys.argv[1].split('=')[1] ) except : print 'need port params' log.e( 'need port params' ) exit( 1 ) if __name__ == "__main__" : main( port )