def hello_handler(self, message): """ Handles a HELLO message. Adds the peer to the peer list if enough room. Sends it back our peer list. :param message: The received message. :type message: Message :rtype: None """ new_host = message.data[0] new_port = int(message.data[1]) if self.max_peers_reached(): sorted_peers = self.get_sorted_peers() if sorted_peers is not None: first_peer = sorted_peers[0] self.remove_peer(first_peer['host'], first_peer['port']) self.add_peer(new_host, new_port) with self.peer_lock: m = Message(1, 'PEERS', list(self.peers.keys())) send_message(m, new_host, new_port)
async def get_messages(self, msg: Message) -> Message: their_did = msg['with'] search_handle = await non_secrets.open_wallet_search( self.agent.wallet_handle, "basicmessage", json.dumps({"their_did": their_did}), json.dumps({})) results = await non_secrets.fetch_wallet_search_next_records( self.agent.wallet_handle, search_handle, 100) messages = [] for r in json.loads( results)["records"] or []: # records is None if empty d = json.loads(r['value']) d["_id"] = r["id"] # include record id for further reference. messages.append(d) #TODO: fetch in loop till all records are processed await non_secrets.close_wallet_search(search_handle) messages = sorted(messages, key=lambda n: n['timestamp'], reverse=True) await self.agent.send_admin_message( Message({ '@type': AdminBasicMessage.MESSAGES, 'with': their_did, 'messages': messages }))
def _get_pose(self): msg = Message() msg.id = CommunicationProtocolIDs.GET_POSE response = self._send_command(msg) self.x = struct.unpack_from('f', response.params, 0)[0] self.y = struct.unpack_from('f', response.params, 4)[0] self.z = struct.unpack_from('f', response.params, 8)[0] self.r = struct.unpack_from('f', response.params, 12)[0] self.j1 = struct.unpack_from('f', response.params, 16)[0] self.j2 = struct.unpack_from('f', response.params, 20)[0] self.j3 = struct.unpack_from('f', response.params, 24)[0] self.j4 = struct.unpack_from('f', response.params, 28)[0] if self.verbose: print("pydobot: x:%03.1f \ y:%03.1f \ z:%03.1f \ r:%03.1f \ j1:%03.1f \ j2:%03.1f \ j3:%03.1f \ j4:%03.1f" % (self.x, self.y, self.z, self.r, self.j1, self.j2, self.j3, self.j4)) return response
def _async_request(self, fileobj, t, *arg): # this method may be called from other threads (prefetch) self._lock.acquire() try: msg = Message() msg.add_int(self.request_number) for item in arg: if isinstance(item, long): msg.add_int64(item) elif isinstance(item, int): msg.add_int(item) elif isinstance(item, SFTPAttributes): item._pack(msg) else: # For all other types, rely on as_string() to either coerce # to bytes before writing or raise a suitable exception. msg.add_string(item) num = self.request_number self._expecting[num] = fileobj self.request_number += 1 finally: self._lock.release() self._send_packet(t, msg) return num
def _read_response(self, waitfor=None): while True: try: t, data = self._read_packet() except EOFError as e: raise SSHException('Server connection dropped: {}'.format(e)) msg = Message(data) num = msg.get_int() self._lock.acquire() try: if num not in self._expecting: # might be response for a file that was closed before # responses came back self._log(DEBUG, 'Unexpected response #{}'.format(num)) if waitfor is None: # just doing a single check break continue fileobj = self._expecting[num] del self._expecting[num] finally: self._lock.release() if num == waitfor: # synchronous if t == CMD_STATUS: self._convert_status(msg) return t, msg # can not rewrite this to deal with E721, either as a None check # nor as not an instance of None or NoneType if fileobj is not type(None): # noqa fileobj._async_response(t, msg, num) if waitfor is None: # just doing a single check break return None, None
def invoke_subsystem(self, subsystem): """ Request a subsystem on the server (for example, ``sftp``). If the server allows it, the channel will then be directly connected to the requested subsystem. When the subsystem finishes, the channel will be closed and can't be reused. :param str subsystem: name of the subsystem being requested. :raises: `.SSHException` -- if the request was rejected or the channel was closed """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('subsystem') m.add_boolean(True) m.add_string(subsystem) self._event_pending() self.transport._send_user_message(m) self._wait_for_event()
def signup(self, message): response = Message('SIGNUPREPLY') try: username = message.params['user'] password = message.params['pass'] if not self.context.server.find_user(username): response.status = 200 response.params[ 'res'] = 'User Registered! You are now Authenticated!' self.context.client = Client() self.context.client.username = username self.context.client.password = password self.context.client.wallet = Wallet(username) self.context.server.clients[username] = self.context.client self.context.transition_to(Authenticated()) else: response.status = 400 response.params['res'] = 'This username already exists!' except Exception as e: response.status = 500 response.params['res'] = 'Internal Server Error!' self.context.socket.send(pickle.dumps(response))
def handler_14(self): mess = Message(self) keyboard = VkKeyboard(one_time=False, inline=False) if success(20): keyboard.add_button(button_success14, color=VkKeyboardColor.POSITIVE) mess.set_keyboard(keyboard) mess.set_text(message_success14) self.player.money += 4.1 message_level = self.player.level.add_exp(1) mess.add_text(message_level) self.status = '15' return mess.get_message() else: keyboard.add_button(button_lost, color=VkKeyboardColor.POSITIVE) mess.set_keyboard(keyboard) mess.set_text(message_lost) return mess.get_message()
def threads(self, prefetch=False, **kwargs): emails = [] response, data = self.gmail.imap.uid('SEARCH', 'ALL') if response == 'OK': uids = data[0].split(' ') for uid in uids: if not self.messages.get(uid): self.messages[uid] = Message(self, uid) emails.append(self.messages[uid]) if prefetch: fetch_str = ','.join(uids) response, results = self.gmail.imap.uid( 'FETCH', fetch_str, '(BODY.PEEK[] FLAGS X-GM-THRID X-GM-MSGID X-GM-LABELS)') for index in xrange(len(results) - 1): raw_message = results[index] if re.search(r'UID (\d+)', raw_message[0]): uid = re.search(r'UID (\d+)', raw_message[0]).groups(1)[0] self.messages[uid].parse(raw_message) return emails
def on_response_received(self, message): if not message.data["response"]: self._nextIndexes[message.sender] -= 1 previousIndex = self._nextIndexes[message._sender] - 1 previous = self._server._log[previousIndex] current = self._server._log[self._nextIndexes[message._sender]:] self._numofMessages[message._sender] = len(current) appendEntry = Message( self._server._name, message._sender, self._server._currentTerm, { "leaderId": self._server._name, "prevLogIndex": previousIndex, "prevLogTerm": previous["term"], "entries": current, "leaderCommit": self._server._commitIndex, }, Message.AppendEntries) self._server.send_message_response(appendEntry) else: index = self._nextIndexes[message._sender] lastIndex = index + self._numofMessages[message._sender] - 1 self._nextIndexes[message._sender] += self._numofMessages[message._sender] for i in range(lastIndex, index-1, -1): self._ackCount[i] += 1 if self._ackCount[i] == (self._server._total_nodes + 1) / 2: if i > self._server._commitIndex: for j in range(self._server._commitIndex+1, i+1): self._server._x += int(self._server._log[j]["value"]) self._server._commitIndex = i print "Leader committed entries upto", self._server._commitIndex break return self, None
def receiveMessage(self): """ Receive a DNS message and return a tuple of a Message object and the IP address of the sender. @return: (Message object, IP address of the sender (str)) """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(("129.21.122.121", 53)) # interface's IP address data, addr = s.recvfrom(512) d = DNSRecord.parse(data) message = Message() message.rid = d.header.id for question in d.questions: message.questions.append( ResourceRecord( str(question.qname)[:-1], question.qtype, question.qclass)) for answer in d.rr: message.answers.append( ResourceRecord( str(answer.rname)[:-1], answer.rtype, answer.rclass, answer.ttl, answer.rdlength, answer.rdata)) for a in d.auth: message.authorities.append( ResourceRecord( str(a.rname)[:-1], a.rtype, a.rclass, a.ttl, a.rdlength, a.rdata)) for a in d.ar: message.additionalRecords.append( ResourceRecord( str(a.rname)[:-1], a.rtype, a.rclass, a.ttl, a.rdlength, a.rdata)) print("Received a message from {0}.".format(addr[0])) print(message) return message, addr
async def run(message, matches, chat_id, step): if is_mod(message): if matches[0] == 'music': show_keyboard = [] i = 0 user_steps[chat_id] = {"name": "Soundcloud", "step": 0, "data": {}, "cover": {}, "title": {}} for song in await search(matches[1]): title, link, cover = song[0], song[1], song[2] cover_music = '' if cover: cover_music = cover.replace('large', 't500x500') else: cover_music = 'https://www.apple.com/v/apple-music/e/images/shared/og_image.png?201802090801' user_steps[chat_id]['cover'][i] = cover_music user_steps[chat_id]['data'][i] = link user_steps[chat_id]['title'][i] = title show_keyboard.append([InlineKeyboardButton(text=title, callback_data='music {}'.format(i))]) i += 1 if i == 20: break if len(show_keyboard) in [0, 1]: return [Message(chat_id).set_text('چیزی پیدا نکردم :(')] markup = InlineKeyboardMarkup(inline_keyboard=show_keyboard) bot.sendMessage(chat_id, "یکی از اینارو انتخاب کن 🙃👇🏻", reply_markup=markup)
def _parse_kexdh_gex_request_old(self, m): # same as above, but without min_bits or max_bits (used by older clients like putty) self.preferred_bits = m.get_int() # smoosh the user's preferred size into our own limits if self.preferred_bits > self.max_bits: self.preferred_bits = self.max_bits if self.preferred_bits < self.min_bits: self.preferred_bits = self.min_bits # generate prime pack = self.transport._get_modulus_pack() if pack is None: raise SSHException( 'Can\'t do server-side gex with no modulus pack') self.transport._log(DEBUG, 'Picking p (~ %d bits)' % (self.preferred_bits, )) self.g, self.p = pack.get_modulus(self.min_bits, self.preferred_bits, self.max_bits) m = Message() m.add_byte(chr(_MSG_KEXDH_GEX_GROUP)) m.add_mpint(self.p) m.add_mpint(self.g) self.transport._send_message(m) self.transport._expect_packet(_MSG_KEXDH_GEX_INIT) self.old_style = True
async def invite_received(self, msg: Message) -> Message: conn_name = msg['content']['name'] their_endpoint = msg['content']['endpoint'] their_connection_key = msg['content']['connection_key'] # store invite in the wallet await non_secrets.add_wallet_record( self.agent.wallet_handle, "invitation", uuid.uuid4().hex, json.dumps({ 'name': conn_name, 'endpoint': their_endpoint, 'connection_key': their_connection_key }), json.dumps({})) return Message({ '@type': ADMIN_CONNECTIONS.INVITE_RECEIVED, 'content': { 'name': conn_name, 'endpoint': their_endpoint, 'connection_key': their_connection_key, 'history': msg } })
def __init__(self, flowBasedSequences, performFullAnalysis=True): if flowBasedSequences == None: print "FATAL: No sequences loaded yet" return False self.cluster_collection = ClusterCollection() for directionTuple in flowBasedSequences: flowDirection = directionTuple[1] #print directionTuple[0]['zRF1otvQJQ5'] for seqs in directionTuple[0]: flowInfo = directionTuple[0][seqs] for seq in flowInfo.sequences: #=========================================================== # myseq = seq.sequence # if myseq[0] == 0xd: # if myseq[1] == 0xa: # print "Found 0D0A in seq ", myseq, " in flowInfo ", flowInfo #=========================================================== newMessage = Message(seq.sequence, seq.connIdent, seq.mNumber, seq.flowNumber, flowDirection, performFullAnalysis) self.cluster_collection.add_message_to_cluster(newMessage)
def run(self): for i in range(self.n): if (i + 1) != self.pid: self.send_message(i + 1) pending_msgs = 0 snapshot = list(self.q.queue) for msg in snapshot: if (int(msg.msg_type.split(':')[1]) < self.roundNumber): pending_msgs += 1 print(f'{self.pid} pending msgs: {pending_msgs}') while (pending_msgs != 0): threadLock.acquire() tmp = self.q.get() threadLock.release() if (int(tmp.msg_type.split(':')[1]) < self.roundNumber): if 'x' not in tmp.msg_type: print(f'{self.pid}: Receiving msg {tmp}') self.receive_message(tmp.senderID, tmp) pending_msgs -= 1 self.comm_channel[int(self.pid)] = self.q done_msg = { 'decision': self.decision, 'key': self.key, 'value': self.value_v, 'level': self.level_v, 'r': self.roundNumber + 1, 'total_rounds': self.totalRounds } done_config = {} done_config['done_msg'] = done_msg done_config['comm'] = self.comm_channel threadLock.acquire() self.master_q.put( Message(self.pid, 'Master', done_config, self.level_v, self.value_v, self.key)) threadLock.release()
def request_forward_agent(self, handler): """ Request for a forward SSH Agent on this channel. This is only valid for an ssh-agent from openssh !!! @param handler: a required handler to use for incoming SSH Agent connections @type handler: function @return: if we are ok or not (at that time we always return ok) @rtype: boolean @raise: SSHException in case of channel problem. """ if self.closed or self.eof_received or self.eof_sent or not self.active: raise SSHException('Channel is not open') m = Message() m.add_byte(chr(MSG_CHANNEL_REQUEST)) m.add_int(self.remote_chanid) m.add_string('*****@*****.**') m.add_boolean(False) self.transport._send_user_message(m) self.transport._set_forward_agent_handler(handler) return True
def __init__(self, column, log=False, log_write_mode="a", use_xymon=True, debug=False): """ Constructor of the Xymon Client. :param column: str :param log: bool :param log_write_mode: str :param use_xymon: bool :param debug: bool """ self.debug = debug self.sender = None self._analyze_environment(use_xymon) self.msg = Message(column=column) if log: self.log_file_path = os.path.join(self.client_logs_path, self.msg.column + ".log") self.log_file = open(self.log_file_path, log_write_mode) else: self.log_file = None
def resize_pty(self, width=80, height=24, width_pixels=0, height_pixels=0): """ Resize the pseudo-terminal. This can be used to change the width and height of the terminal emulation created in a previous `get_pty` call. :param int width: new width (in characters) of the terminal screen :param int height: new height (in characters) of the terminal screen :param int width_pixels: new width (in pixels) of the terminal screen :param int height_pixels: new height (in pixels) of the terminal screen :raises: `.SSHException` -- if the request was rejected or the channel was closed """ m = Message() m.add_byte(cMSG_CHANNEL_REQUEST) m.add_int(self.remote_chanid) m.add_string('window-change') m.add_boolean(False) m.add_int(width) m.add_int(height) m.add_int(width_pixels) m.add_int(height_pixels) self.transport._send_user_message(m)
def __init__(self, peername, logfile): self.peername = peername # discovery module self.bcaster = Broadcaster(setting.UDP_BROADCAST, setting.CTR_MASTER_BCAST_PORT) # message module self.message = Message(setting.CTR_HOST, setting.CTR_MASTER_PORT, setting.CTR_SLAVE_PORT, self) # slaves self.slaves = {} self.peers = {} # logging self.logfile = logfile if logfile else '%s-%s' % ( time.strftime("%m-%d"), str(int(time.time()) % 100).zfill(3)) self.logfile = os.path.join(setting.LOG_DIR, self.logfile) self.logger = logging.getLogger() self.logger.setLevel(logging.INFO) fhandler = logging.FileHandler(self.logfile + '.log') formatter = logging.Formatter('%(asctime)s - %(message)s') fhandler.setFormatter(formatter) self.logger.addHandler(fhandler) 'Plot module' import plot self.plot = plot
class MOTD(HasTraits): """ The 'Message of the Day' implementation! """ # The default message is used when there are no other messages! DEFAULT_MESSAGE = Message(author='Anon', text='Work hard and be good to your Mother') # The list of possible messages. messages = List(IMessage) ########################################################################### # 'IMOTD' interface. ########################################################################### def motd(self): """ Prints a random message. """ if len(self.messages) > 0: message = choice(self.messages) else: message = self.DEFAULT_MESSAGE return message
def execute(self): if self.trigger_id is not None: if self.type == 'tag': savedTeam = self.dao.get_saved_team(team_id=self.idx) mObj = Message(blocks=self.get_tag_modal(savedTeam), trigger_id=self.trigger_id) elif self.type == 'link': savedTeam = self.dao.get_saved_team(team_id=self.idx) mObj = Message(blocks=self.get_link_modal(savedTeam), trigger_id=self.trigger_id) elif self.type == 'text': savedTeam = self.dao.get_saved_team(team_id=self.idx) mObj = Message(blocks=self.get_text_modal(savedTeam), trigger_id=self.trigger_id) elif self.type == 'email': savedTeam = self.dao.get_saved_team(team_id=self.idx) mObj = Message(blocks=self.get_email_modal(savedTeam), trigger_id=self.trigger_id) elif self.type == 'userteam': savedUser = self.dao.get_saved_user(user=self.idx) mObj = Message(blocks=self.get_userteam_modal(savedUser), trigger_id=self.trigger_id) elif self.type == 'usertag': savedUser = self.dao.get_saved_user(user=self.idx) mObj = Message(blocks=self.get_usertag_modal(savedUser), trigger_id=self.trigger_id) return mObj
async def run(message, matches, chat_id, step): from_id = message['from']['id'] if step == 0: await sender( Message(chat_id).set_text("*Please Wait*\n_I'm Searching all Music with this name_", parse_mode="markdown")) user_steps[from_id] = {"name": "Soundcloud", "step": 1, "data": {}} i = 0 show_keyboard = {'keyboard': [], "selective": True} matches = matches.replace(" ", "+") for song in await search(matches): title, link = song[0], song[1] user_steps[from_id]['data'][title] = link show_keyboard['keyboard'].append([title]) i += 1 if i == 20: break if len(show_keyboard['keyboard']) in [0, 1]: hide_keyboard = {'hide_keyboard': True, 'selective': True} del user_steps[from_id] return [Message(chat_id).set_text("*Not Found*", reply_to_message_id=message['message_id'], reply_markup=hide_keyboard, parse_mode="markdown")] return [Message(chat_id).set_text("Select One Of these :", reply_to_message_id=message['message_id'], reply_markup=show_keyboard)] elif step == 1: try: hide_keyboard = {'hide_keyboard': True, "selective": True} await sender(Message(chat_id).set_text("*Please Wait*\n_Let me Save this Music For You_", reply_to_message_id=message['message_id'], reply_markup=hide_keyboard, parse_mode="markdown")) await downloader(await getfile(user_steps[from_id]['data'][message['text']]), "tmp/{}.mp3".format(message['text'])) del user_steps[from_id] return [Message(chat_id).set_audio("tmp/{}.mp3".format(message['text']), title=message['text'], performer="@SrcMusicBot")] except Exception as e: del user_steps[from_id] return [Message(chat_id).set_text("*Wrong Input*\n_Try Again_", parse_mode="markdown")]
def recvmsg(self): msg_length = self.readall(2) msg = Message(msg_length) msg = self.readall(msg.read_eunit16()) return Message(msg)
def dataReceived(self, data): msg = Message() datapack = DataPack(msg) msglen, msgid, msgdata = datapack.unpack(data) print('[Client] receive data %r from server, len:%r , id:%r' % (msgdata,msglen, msgid))
def listen_handler(): handle_message(Message(request.get_json())) return setting.machine_name + ' HANDLED'
def read_message_from_stdin(): return Message(sys.stdin.buffer.read())
def iter_file_messages(filename): mbox = mailbox.mbox(filename) for message in mbox: yield Message(message.as_bytes())
def iter_dir_messages(directory_name): for item in pathlib.Path(directory_name).iterdir(): yield Message(open(item, mode="rb").read())
def process_outgoing_message(self, msg_raw, originates_from_console=False, setup_message=False): if not setup_message: ''' Process an outgoing message before Base64 encoding :param msg_raw: raw message :return: message to be sent to the server ''' # first initialize N = random and ctr = 0 # then put timestamp and associated data we don't want to encrypt in blocks A1...m nonce = get_random_bytes(8) keystring = self.conversation_key # if the message has been typed into the console, record it, so it is never printed again during chatting if originates_from_console == True: # message is already seen on the console m = Message( owner_name=self.manager.user_name, content=msg_raw ) self.printed_messages.append(m) msg = msg_raw # Generate random message id msg_id = get_random_bytes(11) # Get current timestamp timestamp = str(datetime.datetime.now()) header = str(timestamp) + msg_id # Data being encrypted: (A|X) total_data = header + msg # Pad the information being encyrpted in CBC mode for the MAC p_length = AES.block_size - (len(total_data)) % AES.block_size if p_length >= 1: total_data = total_data + chr(1) p_length -= 1 while p_length > 0: total_data = total_data + chr(0) p_length -= 1 # append message blocks X1...n and compute the MAC (as last block of CBC encryption of A|X) # create AES CBC cipher object cbc_cipher = AES.new(keystring, AES.MODE_CBC, "0" * AES.block_size) # Encrypt (A|X) in AEC CBC mode total_encrypted_data = cbc_cipher.encrypt(total_data) # Obtain the MAC from the last block of the encrypted data mac = total_encrypted_data[-1 * AES.block_size:] # this should be further encrypted by XORing E_K(N|Ctr0) to it # (where E_K() is ECB encryption of the single block N|ctr(0) ecb_cipher = AES.new(keystring, AES.MODE_ECB) enc_nonce = ecb_cipher.encrypt(nonce + chr(0)*8) mac = self.xor_two_str(mac, enc_nonce) # Pad length of message into a 16 bit block len_msg = str(len(msg)) while len(len_msg) < 16: len_msg = "0" + len_msg # Finally encrypt in CTR mode the blocks X1...n and append the encrypted MAC to get the final output # initialize CTR mode, encrypt message ctr = Counter.new(64, prefix=nonce, initial_value=0) ctr_cipher = AES.new(keystring, AES.MODE_CTR, counter=ctr) # Encrypt the message blocks encrypted = ctr_cipher.encrypt(msg) # Get final message (00 | length of message | nonce | Enc(msg) | MAC) encoded_msg = NORMAL + len_msg + header + nonce + encrypted + mac msg_to_send = encoded_msg else: # append "11" to setup messages msg_to_send = SETUP + msg_raw # post the message to the conversation self.manager.post_message_to_conversation(msg_to_send) return msg_to_send