Validate a message sent by a client.
        :param wrappedMsg: a message from a client
        :return: Tuple of clientMessage and client address
186214
def validateClientMsg(self, wrappedMsg):
        
        msg, frm = wrappedMsg
        if self.isClientBlacklisted(frm):
            self.discard(str(msg)[:256], "received from blacklisted client {}".format(frm), logger.display)
            return None

        needStaticValidation = False
        if all([msg.get(OPERATION), msg.get(f.REQ_ID.nm),
                idr_from_req_data(msg)]):
            cls = self.client_request_class
            needStaticValidation = True
        elif OP_FIELD_NAME in msg:
            op = msg[OP_FIELD_NAME]
            cls = node_message_factory.get_type(op)
            if cls not in (Batch, LedgerStatus, CatchupReq):
                raise InvalidClientMsgType(cls, msg.get(f.REQ_ID.nm))
        else:
            raise InvalidClientRequest(msg.get(f.IDENTIFIER.nm),
                                       msg.get(f.REQ_ID.nm))
        try:
            cMsg = cls(**msg)
        except TypeError as ex:
            raise InvalidClientRequest(msg.get(f.IDENTIFIER.nm),
                                       msg.get(f.REQ_ID.nm),
                                       str(ex))
        except Exception as ex:
            raise InvalidClientRequest(msg.get(f.IDENTIFIER.nm),
                                       msg.get(f.REQ_ID.nm)) from ex

        if needStaticValidation:
            self.doStaticValidation(cMsg)

        self.execute_hook(NodeHooks.PRE_SIG_VERIFICATION, cMsg)
        self.verifySignature(cMsg)
        self.execute_hook(NodeHooks.POST_SIG_VERIFICATION, cMsg)
        # Suspicions should only be raised when lot of sig failures are
        # observed
        # try:
        #     self.verifySignature(cMsg)
        # except UnknownIdentifier as ex:
        #     raise
        # except Exception as ex:
        #     raise SuspiciousClient from ex
        logger.trace("{} received CLIENT message: {}".
                     format(self.clientstack.name, cMsg))
        return cMsg, frm
390703
def validate(message, gpg_home=None, **config):
    
    if gpg_home is None:
        raise ValueError("You must set the gpg_home keyword argument.")
    try:
        _ctx.verify(
            fedmsg.encoding.dumps(message['msg']),
            b64decode(message['signature']),
            homedir=gpg_home
        )
        return True
    except GpgBinaryError:
        log.warn("Failed validation. {0}".format(six.text_type(message)))
        return False
527929
def _validate_message_type(self):
        
        if self._unsupported_message_type():
            self.logger.warning(
                'Received unsupported message type: %s', self.message_type)
            if self._drop_invalid:
                if self._drop_exchange:
                    self._republish_dropped_message('invalid type')
                raise DropMessage
            raise MessageException
679976
def handle_message(self, msg):
        
        # log messages received so that no one else has to
        if self._logger.isEnabledFor(logging.DEBUG):
            self._logger.debug(
                "received from {}: {}"
                .format(self.bind_address_string, repr(str(msg))))

        if msg.mtype == Message.INFORM:
            return self.handle_inform(msg)
        elif msg.mtype == Message.REPLY:
            return self.handle_reply(msg)
        elif msg.mtype == Message.REQUEST:
            return self.handle_request(msg)
        else:
            self._logger.error("Unexpected message type from server ['%s']."
                               % (msg,))
870743
def iscomplete(rawmessage):
    """"""
    if len(rawmessage) < 2:
        return False

    if rawmessage[0] != 0x02:
        raise ValueError('message does not start with 0x02')

    messageBuffer = bytearray()
    filler = bytearray(30)
    messageBuffer.extend(rawmessage)
    messageBuffer.extend(filler)

    msg = _get_msg_class(rawmessage[1])

    if hasattr(msg, 'receivedSize') and msg.receivedSize:
        expectedSize = msg.receivedSize
    else:
        _LOGGER.error('Unable to find a receivedSize for code 0x%x',
                      rawmessage[1])
        return ValueError

    is_expected_size = False
    if len(rawmessage) >= expectedSize:
        is_expected_size = True

    return is_expected_size
1158860
async def on_raw_privmsg(self, message):
        
        nick, metadata = self._parse_user(message.source)
        target, msg = message.params

        if is_ctcp(msg):
            self._sync_user(nick, metadata)
            type, contents = parse_ctcp(msg)

            # Find dedicated handler if it exists.
            attr = 'on_ctcp_' + pydle.protocol.identifierify(type)
            if hasattr(self, attr):
                await getattr(self, attr)(nick, target, contents)
            # Invoke global handler.
            await self.on_ctcp(nick, target, type, contents)
        else:
            await super().on_raw_privmsg(message)
1284235
def from_raw_message(cls, rawmessage):
        """"""
        if (rawmessage[5] &
                MESSAGE_FLAG_EXTENDED_0X10) == MESSAGE_FLAG_EXTENDED_0X10:
            if len(rawmessage) >= ExtendedSend.receivedSize:
                msg = ExtendedSend.from_raw_message(rawmessage)
            else:
                msg = None
        else:
            msg = StandardSend(rawmessage[2:5],
                               {'cmd1': rawmessage[6],
                                'cmd2': rawmessage[7]},
                               flags=rawmessage[5],
                               acknak=rawmessage[8:9])
        return msg
80574
def __validate_decode_msg(self, message):  # noqa (complexity) pylint: disable=too-many-return-statements,too-many-branches
        """"""
        try:
            if not _CONTENT_TYPE_PATTERN.match(message.content_type):
                logger.debug('Message with unexpected content type %s from container, ignoring', message.content_type)
                return None
        except AttributeError:
            logger.debug('Message without content type from container, ignoring')
            return None

        # Decode & check message wrapper
        try:
            body = ubjloadb(message.body)
        except:
            logger.warning('Failed to decode message wrapper, ignoring', exc_info=DEBUG_ENABLED)
            return None
        if not self.__valid_msg_wrapper(body):
            logger.warning('Invalid message wrapper, ignoring')
            return None

        # currently only warn although maybe this should be an error
        if self.__cnt_seqnum != -1 and not self.__valid_seqnum(body[W_SEQ], self.__cnt_seqnum):
            logger.warning('Unexpected seqnum from container: %d (last seen: %d)', body[W_SEQ],
                           self.__cnt_seqnum)
        self.__cnt_seqnum = body[W_SEQ]

        # Check message hash
        if not self.__check_hash(body):
            logger.warning('Message has invalid hash, ignoring')
            return None

        # Decompress inner message
        try:
            msg = COMPRESSORS[body[W_COMPRESSION]].decompress(body[W_MESSAGE])
        except KeyError:
            logger.warning('Received message with unknown compression: %s', body[W_COMPRESSION])
            return None
        except OversizeException as ex:
            logger.warning('Uncompressed message exceeds %d bytes, ignoring', ex.size, exc_info=DEBUG_ENABLED)
            return None
        except:
            logger.warning('Decompression failed, ignoring message', exc_info=DEBUG_ENABLED)
            return None

        # Decode inner message
        try:
            msg = ubjloadb(msg, object_pairs_hook=OrderedDict)
        except:
            logger.warning('Failed to decode message, ignoring', exc_info=DEBUG_ENABLED)
            return None

        if self.__valid_msg_body(msg):
            return (msg, body[W_SEQ])
        else:
            logger.warning('Message with invalid body, ignoring: %s', msg)
            return None
1123735
def ack_message(self, message):
        
        if message.channel.is_closed:
            LOGGER.warning('Can not ack message, channel is closed')
            self.counters[self.CLOSED_ON_COMPLETE] += 1
            return
        message.channel.basic_ack(delivery_tag=message.delivery_tag)
        self.counters[self.ACKED] += 1
        self.measurement.set_tag(self.ACKED, True)
749604
def parse_message(msg)
      msg = msg.to_s
      re = /([A-Z_]+) ({.*})$/
      msg_split = re.match(msg)
      if msg_split.nil?
        re = /^([A-Z_]+)$/
        msg_split = re.match(msg)
        raise "Error: Malformed Message" if not msg_split
        type = msg_split[1]
        data = {}
      else
        type = msg_split[1]
        data = JSON.parse(msg_split[2])
      end
      {type: type, data: data}
    end
1042780
def privmsg(self, target, message, nowait=False):
        """"""
        if message:
            messages = utils.split_message(message, self.config.max_length)
            if isinstance(target, DCCChat):
                for message in messages:
                    target.send_line(message)
            elif target:
                f = None
                for message in messages:
                    f = self.send_line('PRIVMSG %s :%s' % (target, message),
                                       nowait=nowait)
                return f
1190451
async def dump_message(self, msg, msg_type=None):
        
        mtype = msg.__class__ if msg_type is None else msg_type
        fields = mtype.f_specs()
        for field in fields:
            await self.message_field(msg=msg, field=field)
1349156
def capture_message(self, message=None, param_message=None, **kwargs):
        
        return self.capture("Message", message=message, param_message=param_message, **kwargs)
784343
def from_raw_message(cls, rawmessage):
        """"""
        userdata_dict = Userdata(rawmessage[8:22])
        return ExtendedSend(rawmessage[2:5],
                            {'cmd1': rawmessage[6],
                             'cmd2': rawmessage[7]},
                            userdata_dict,
                            flags=rawmessage[5],
                            acknak=rawmessage[22:23])
518440
def verifymessage(self, address, signature, message):
        """"""
        return self.req("verifymessage", [address, signature, message])
1052644
def gut_message(message: Message) -> Message:
    
    wrapper = Message()
    wrapper.add_header('Content-Type', 'message/external-body',
                       access_type='x-spam-deleted',
                       expiration=time.strftime("%a, %d %b %Y %H:%M:%S %z"),
                       size=str(len(message.get_payload())))

    message.set_payload('')
    wrapper.set_payload([message])

    return wrapper
417091
def _validate(self, msg):
    
    if not isinstance(msg, self._message_type):
      raise TypeError('Expected a %s instance for %s property',
                      self._message_type.__name__,
                      self._code_name or self._name)