def handle_read(self): message = self.recv(1000) message_list = message.split("\t") # self.fh_flow.write(str(message_list) + "\n") for message in message_list: # if self.name == "WSUb": #print "request" if message == self.name: self.self_reqs += 1 # print self.name + " : " + str(self.self_reqs) if len(self.current_flows) > 0: self.say(self.current_flows[0]) if self.current_flows[0] == "close": sleep(2) self.close() raise asyncore.ExitNow() del self.current_flows[0] else: while len(self.current_flows) == 0: sleep(1) self.say(self.current_flows[0]) if self.current_flows[0] == "close": sleep(2) self.close() raise asyncore.ExitNow() del self.current_flows[0] """
def handle_messages(self, msgs): _LOGGER.debug("%s - %s", self.state, msgs) if self.state == 'ERROR': _LOGGER.error("got messages in error state:", msgs) elif self.state == 'INITIAL': if msgs[-1] == messages.ACK: self.send_data(messages.EVENT_SESSION) self.state = 'EVENT_SESSION_REQUESTED' else: self.state = 'ERROR' raise asyncore.ExitNow('Server did not send ACK on connect') elif self.state == 'EVENT_SESSION_REQUESTED': if msgs[-1] == messages.NACK: self.state = 'ERROR' nonce = messages.extract_single(msgs[0]) password = calculate_password(self._password, nonce) self.dispatcher.write(messages.generate_single(password)) self.state = 'PASSWORD_SENT' elif self.state == 'PASSWORD_SENT': if msgs[-1] == messages.ACK: self.connect_listener() self.state = 'EVENT_SESSION_ACTIVE' else: raise asyncore.ExitNow( 'Server did not reply with ACK after sending password') self.state = 'ERROR' elif self.state == 'EVENT_SESSION_ACTIVE': self.event_listener(msgs)
def handle_read(self): """Process data available for reading.""" try: data = self.socket.recv(1024) except OSError, err: if err[0] != errno.EAGAIN and err[0] != errno.EINTR: if self.source.close_tty and err[0] == errno.EIO: raise asyncore.ExitNow( "[slave pseudo terminal closed," " pseudo tty management is terminated]") raise asyncore.ExitNow(err)
def runTest(self): ''' Tests basic functionality. ''' t = threading.Thread(target=self.helper) t.setDaemon(True) t.start() self.assertEqual(self.queue.get(.1), 'ready') time.sleep(.1) try: From = "*****@*****.**" To = ["*****@*****.**", "*****@*****.**"] mailer_inst = mailer.Mailer('127.0.0.1', 1025) msg = mailer.Message(From=From, To=To, charset="utf-8") mailer_inst.send(msg) peer, mailfrom, rcpttos, data = self.queue.get(.1) self.assertEqual(mailfrom, From) self.assertEqual(rcpttos, To) print data finally: try: raise asyncore.ExitNow() except asyncore.ExitNow: pass
def writable(self): if not self.shd["loop"]: raise asyncore.ExitNow('Connector is quitting!') if self.is_writable and not self.ciao_queue.empty( ) and not self.write_pending: return True return False
def handle_read(self): data, addr = self.recvfrom(1024) # 特定のデータが飛んできたら終了 if data == False: raise asyncore.ExitNow('Server is quitting!') return
def writable(self): """ is there data to write to MCU (asyncore func) """ if not self.shd["loop"]: raise asyncore.ExitNow('Connector is quitting!') if not self.ciao_queue.empty() and not self.write_pending: return True return False
def handle_read(self): data = self.socket.recv(4096).strip() words = data.split() if len(words) == 0: # Ignore empty (whitespace-only) commands. return command, args = words[0], words[1:] if command == 'exit': print('Exiting.', file=sys.stderr) raise asyncore.ExitNow() elif command == 'purge': self.handlePurge(command, args) elif command == 'echo': print(data[len(command):].lstrip()) elif command == 'count': print(len(self._jsonQueue), file=sys.stderr) elif command == 'debug': self.handleDebug(command, args) else: print("I don't understand your " 'admin command: "{}"'.format(command), file=sys.stderr)
def all_close(self): global stats, heap, current_data, current_timestamp, all_data, closed_clients, reports_count, new_start, hour_count print "all close" self.remote_clients = set() self.reader_init_flag = False self.message_resend_flag = False self.resend_count = 0 if self.file_write_flag: self.attack_fh.close() hour_count += 1 self.attack_fh = open("attacks-" + str(hour_count), "a", buffering=0) self.file_write_flag = False # Initialize global variables heap = [] stats = dict() current_data = {} current_timestamp = 0 all_data = {} closed_clients = [] reports_count = 29 new_start = False self.close() raise asyncore.ExitNow()
def stop(self): for item in self.conn_list: if item.remote: item.remote.handle_close() else: item.handle_close() self.handle_close() raise asyncore.ExitNow('TCPLocal.stop()')
def dispatch_write(self, buf): """Augment the buffer with stuff to write when possible""" assert self.allow_write self.write_buffer += buf if len(self.write_buffer) > buffered_dispatcher.MAX_BUFFER_SIZE: console_output('Buffer too big (%d) for %s\n' % (len(self.write_buffer), str(self))) raise asyncore.ExitNow(1)
def handle_write(self): """Write the content of the 'source' buffer.""" buf = self.source.buf try: count = os.write(self.socket.fd, buf) except OSError, err: if err[0] != errno.EAGAIN and err[0] != errno.EINTR: raise asyncore.ExitNow(err)
def process_message(self, peer, mailfrom, rcpttos, data): print '2nd stage: got mail', peer, mailfrom, "to:", rcpttos key = re.search("(https?://.*&key=([^\s]+))", message_from_string(data).get_payload(decode=True), re.MULTILINE) if key is not None: raise asyncore.ExitNow(key.group(2)) return
def dispatch_write(self, buf): """Augment the buffer with stuff to write when possible""" self.write_buffer += buf if len(self.write_buffer) > self.MAX_BUFFER_SIZE: console_output('Buffer too big ({:d}) for {}\n'.format( len(self.write_buffer), str(self)).encode()) raise asyncore.ExitNow(1) return True
def handle_read(self): data = self.recv(8192) if data: data.decode("utf-8") message = str(data) print("Message: ", message) sig.collect_signals(message) if str(data) == "close": raise asyncore.ExitNow('Disconnecting')
def removePlayer(playerId): removeIndex = -1 for i, p in enumerate(players): if p.playerId == playerId: removeIndex = i if removeIndex >= 0: print('removePlayer ' + str(removeIndex)) players.pop(removeIndex) if len(players) <= 0: raise asyncore.ExitNow('Server is quitting!')
def log(msg): if options.log_file: fd = options.log_file.fileno() while msg: try: written = os.write(fd, msg) except OSError, e: print 'Exception while writing log:', options.log_file.name print e raise asyncore.ExitNow(1) msg = msg[written:]
def handle_read(self): #self.log('reading...') self.payload += self.recv(1024) #self.log(self.payload) first = self.payload.find(b'{') last = self.payload.find(b'}') if first != -1 and last != -1: data = self.payload[first + 1:last] self.payload = self.payload[last + 1:] self.result_queue.put(data) raise asyncore.ExitNow()
def log(msg: bytes) -> None: if options.log_file: fd = options.log_file.fileno() while msg: try: written = os.write(fd, msg) except OSError as e: print('Exception while writing log:', options.log_file.name) print(e) raise asyncore.ExitNow(1) msg = msg[written:]
def found_terminator(self): msg = ''.join(self.buffer) self.buffer = [] # DBG('@S %s' % _ipc_room) ; for handler in _ipc_room.itervalues(): if handler == self: # Skip a push operation in case oneself. continue if hasattr(handler, 'push'): handler.push(msg + IPC_TERMINATOR) if msg == IPC_QUIT: self.push(msg + IPC_TERMINATOR) raise asyncore.ExitNow('IPC Server is quitting')
def handle_read(self): # Reads data from the socket until a complete message is received try: string_key = repr(self._addr_orig) + repr(self._sock_orig) message = None data = self.recv(1024) self._strings_received[string_key] += data message = self.getMessage(string_key) logger.debug('Message for parent %s from:%s, character received:%s', self._list_args['Id'], string_key, str(len(self._strings_received[string_key])) ) # We need to do a while because more than one message could arrive almost at the same time for the agent. while (message is not None): logger.debug('Message for parent %s message: %d',self._list_args['Id'], len(message.__str__()) ) self.do_processing(message) message = self.getMessage(string_key) except Exception as e: raise asyncore.ExitNow('Server is quitting!')
def disconnect(self): """We are no more interested in this remote process""" try: os.kill(-self.pid, signal.SIGKILL) except OSError: # The process was already dead, no problem pass self.read_buffer = b'' self.write_buffer = b'' self.set_enabled(False) if self.read_in_state_not_started: self.print_lines(self.read_in_state_not_started) self.read_in_state_not_started = b'' if options.abort_error and self.state is STATE_NOT_STARTED: raise asyncore.ExitNow(1) self.change_state(STATE_DEAD)
def loop(interactive): histfile = os.path.expanduser("~/.polysh_history") init_history(histfile) next_signal = None last_status = None while True: try: if next_signal: current_signal = next_signal next_signal = None sig2chr = {signal.SIGINT: 'C', signal.SIGTSTP: 'Z'} ctrl = sig2chr[current_signal] remote_dispatcher.log('> ^{}\n'.format(ctrl).encode()) control_commands.do_send_ctrl(ctrl) console_output(b'') stdin.the_stdin_thread.prepend_text = None while dispatchers.count_awaited_processes()[0] and \ remote_dispatcher.main_loop_iteration(timeout=0.2): pass # Now it's quiet for r in dispatchers.all_instances(): r.print_unfinished_line() current_status = dispatchers.count_awaited_processes() if current_status != last_status: console_output(b'') if remote_dispatcher.options.interactive: stdin.the_stdin_thread.want_raw_input() last_status = current_status if dispatchers.all_terminated(): # Clear the prompt console_output(b'') raise asyncore.ExitNow(remote_dispatcher.options.exit_code) if not next_signal: # possible race here with the signal handler remote_dispatcher.main_loop_iteration() except KeyboardInterrupt: if interactive: next_signal = signal.SIGINT else: kill_all() os.kill(0, signal.SIGINT) except asyncore.ExitNow as e: console_output(b'') save_history(histfile) sys.exit(e.args[0])
def main_loop(): global next_signal last_status = None while True: try: if next_signal: current_signal = next_signal next_signal = None sig2chr = {signal.SIGINT: 'c', signal.SIGTSTP: 'z'} ctrl = sig2chr[current_signal] remote_dispatcher.log('> ^%c\n' % ctrl.upper()) control_commands.do_send_ctrl(ctrl) console_output('') the_stdin_thread.prepend_text = None while dispatchers.count_awaited_processes()[0] and \ remote_dispatcher.main_loop_iteration(timeout=0.2): pass # Now it's quiet for r in dispatchers.all_instances(): r.print_unfinished_line() current_status = dispatchers.count_awaited_processes() if current_status != last_status: console_output('') if remote_dispatcher.options.interactive: the_stdin_thread.want_raw_input() last_status = current_status if dispatchers.all_terminated(): # Clear the prompt console_output('') raise asyncore.ExitNow(remote_dispatcher.options.exit_code) if not next_signal: # possible race here with the signal handler remote_dispatcher.main_loop_iteration() except asyncore.ExitNow, e: console_output('') sys.exit(e.args[0])
def handle_read_event(self): raise asyncore.ExitNow()
def do_quit(command: str) -> None: raise asyncore.ExitNow(0)
def handle_close(self): print('Admin command pipe is closed. Exiting.', file=sys.stderr) self.close() raise asyncore.ExitNow()
def handle_read(self): self.recv(64) self.handle_close() raise asyncore.ExitNow("Signal asyncore loop to exit")
def shutdown_handler(signum, frame): global s s.cleanup() del s raise asyncore.ExitNow()
lines = thestring.split("\n") for line in lines: line_array=line.split("=",1) if line_array[0] == 'client_address': self.client_address = line_array[1] elif line_array[0] == 'sasl_username': self.sasl_username=line_array[1] elif line_array[0] == 'sender': self.sender = line_array[1] action=self.check_record(); self.send(action) self.close() def shutdown_handler(signum, frame): global s s.cleanup() del s raise asyncore.ExitNow() signal.signal(signal.SIGHUP, shutdown_handler) s = PolicyServer(bind_ip, port) try: asyncore.loop() except: # graceful exit s.cleanup() del s raise asyncore.ExitNow()