Decode response from client message
196629
def decode_response(client_message, to_object=None):
    
    parameters = dict(read_count=None, items=None)
    parameters['read_count'] = client_message.read_int()
    items_size = client_message.read_int()
    items = []
    for _ in range(0, items_size):
        items_item = client_message.read_data()
        items.append(items_item)
    parameters['items'] = ImmutableLazyDataList(items, to_object)
    return parameters
306248
def DecodeMessages(self, response_comms):
    
    # Have we seen this cipher before?
    cipher_verified = False
    try:
      cipher = self.encrypted_cipher_cache.Get(response_comms.encrypted_cipher)
      stats_collector_instance.Get().IncrementCounter(
          "grr_encrypted_cipher_cache", fields=["hits"])

      # Even though we have seen this encrypted cipher already, we should still
      # make sure that all the other fields are sane and verify the HMAC.
      cipher.VerifyReceivedHMAC(response_comms)
      cipher_verified = True

      # If we have the cipher in the cache, we know the source and
      # should have a corresponding public key.
      source = cipher.GetSource()
      remote_public_key = self._GetRemotePublicKey(source)
    except KeyError:
      stats_collector_instance.Get().IncrementCounter(
          "grr_encrypted_cipher_cache", fields=["misses"])
      cipher = ReceivedCipher(response_comms, self.private_key)

      source = cipher.GetSource()
      try:
        remote_public_key = self._GetRemotePublicKey(source)
        if cipher.VerifyCipherSignature(remote_public_key):
          # At this point we know this cipher is legit, we can cache it.
          self.encrypted_cipher_cache.Put(response_comms.encrypted_cipher,
                                          cipher)
          cipher_verified = True

      except UnknownClientCertError:
        # We don't know who we are talking to.
        remote_public_key = None

    # Decrypt the message with the per packet IV.
    plain = cipher.Decrypt(response_comms.encrypted, response_comms.packet_iv)
    try:
      packed_message_list = rdf_flows.PackedMessageList.FromSerializedString(
          plain)
    except rdfvalue.DecodeError as e:
      raise DecryptionError(e)

    message_list = self.DecompressMessageList(packed_message_list)

    # Are these messages authenticated?
    # pyformat: disable
    auth_state = self.VerifyMessageSignature(
        response_comms,
        packed_message_list,
        cipher,
        cipher_verified,
        response_comms.api_version,
        remote_public_key)
    # pyformat: enable

    # Mark messages as authenticated and where they came from.
    for msg in message_list.job:
      msg.auth_state = auth_state
      msg.source = cipher.cipher_metadata.source

    return (message_list.job, cipher.cipher_metadata.source,
            packed_message_list.timestamp)
172696
def parse_encrypted_response(self, response):
        
        content_type = response.headers['Content-Type']
        if 'protocol="{0}"'.format(self.protocol_string.decode()) in content_type:
            host = urlsplit(response.request.url).hostname
            msg = self._decrypt_response(response, host)
        else:
            msg = response.text

        return msg
898796
def decode_message(self, message, is_key=False):
        

        if message is None:
            return None

        if len(message) <= 5:
            raise SerializerError("message is too small to decode")

        with ContextStringIO(message) as payload:
            magic, schema_id = struct.unpack('>bI', payload.read(5))
            if magic != MAGIC_BYTE:
                raise SerializerError("message does not start with magic byte")
            decoder_func = self._get_decoder_func(schema_id, payload, is_key)
            return decoder_func(payload)
951030
def decode(self, msg):
        """"""
        _check_message_valid(msg)
        cmd = msg[2:4]
        decoder = getattr(self, '_{}_decode'.format(cmd.lower()), None)
        if not decoder:
            cmd = 'unknown'
            decoder = self._unknown_decode
        decoded_msg = decoder(msg)
        for handler in self._handlers.get(cmd, []):
            handler(**decoded_msg)
135664
def decode(self, value, force=False):
        ""
        if (self.decode_responses or force) and isinstance(value, bytes):
            value = value.decode(self.encoding, self.encoding_errors)
        return value
1115093
def response_message(cls, result, request_id):
        ''''''
        if isinstance(result, CodeMessageError):
            payload = cls.error_payload(result, request_id)
        else:
            payload = cls.response_payload(result, request_id)
        return cls.encode_payload(payload)
1292028
def unpack_response(self, cursor_id=None,
                        codec_options=_UNICODE_REPLACE_CODEC_OPTIONS,
                        user_fields=None, legacy_response=False):
        
        # If _OpMsg is in-use, this cannot be a legacy response.
        assert not legacy_response
        return bson._decode_all_selective(
            self.payload_document, codec_options, user_fields)
1201018
def _parse_reply(request):
        
        try:
            return jsonutils.loads(request.content)
        except ValueError:
            raise ib_ex.InfobloxConnectionError(reason=request.content)
433713
private String readResponseStream(InputStream responseStream, HttpURLConnection connection)
            throws IOException {
        LOGGER.debug("Reading response stream");
        InputStream decodedStream = responseStream;
        if (compression == Compression.LZF && "lzf".equals(connection.getHeaderField("Content-Encoding"))) {
            LOGGER.debug("Decoding lzf");
            decodedStream = new LZFInputStream(responseStream);
        }

        int contentLength = connection.getContentLength();

        if (contentLength == 0) {
            return "";
        } else {
            return new String(ByteStreams.toByteArray(decodedStream), UTF_8);
        }
    }
439360
function decode(callback) {
    if (typeof callback == 'function') {
      return callback;
    } else {
      var split = callback.split('::');
      var action = split[0];
      var method = split[1] || 'index';
      return {
        action: action,
        method: method,
        arguments: []
      };
    }
  }
1224341
async def _get_response(self, msg):
        """"""
        try:
            protocol = await self._get_protocol()
            pr = protocol.request(msg)
            r = await pr.response
            return pr, r
        except ConstructionRenderableError as e:
            raise ClientError("There was an error with the request.", e)
        except RequestTimedOut as e:
            await self._reset_protocol(e)
            raise RequestTimeout('Request timed out.', e)
        except (OSError, socket.gaierror, Error) as e:
            # aiocoap sometimes raises an OSError/socket.gaierror too.
            # aiocoap issue #124
            await self._reset_protocol(e)
            raise ServerError("There was an error with the request.", e)
        except asyncio.CancelledError as e:
            await self._reset_protocol(e)
            raise e
1211188
def decode(self, envelope, session, **kwargs):
		
		return WMessengerBytesEnvelope(bytes(WUnHex(envelope.message())), meta=envelope)
492083
def _decode(rawstr):
    
    # Check for the magick word.
    try:
        rawstr = rawstr.decode('utf-8')
    except (AttributeError, UnicodeEncodeError):
        pass
    except (UnicodeDecodeError):
        try:
            rawstr = rawstr.decode('iso-8859-1')
        except (UnicodeDecodeError):
            rawstr = rawstr.decode('utf-8', 'ignore')
    if not rawstr.startswith(_MAGICK):
        raise MessageError("This is not a '%s' message (wrong magick word)"
                           % _MAGICK)
    rawstr = rawstr[len(_MAGICK):]

    # Check for element count and version
    raw = re.split(r"\s+", rawstr, maxsplit=6)
    if len(raw) < 5:
        raise MessageError("Could node decode raw string: '%s ...'"
                           % str(rawstr[:36]))
    version = raw[4][:len(_VERSION)]
    if not _is_valid_version(version):
        raise MessageError("Invalid Message version: '%s'" % str(version))

    # Start to build message
    msg = dict((('subject', raw[0].strip()),
                ('type', raw[1].strip()),
                ('sender', raw[2].strip()),
                ('time', strp_isoformat(raw[3].strip())),
                ('version', version)))

    # Data part
    try:
        mimetype = raw[5].lower()
        data = raw[6]
    except IndexError:
        mimetype = None

    if mimetype is None:
        msg['data'] = ''
        msg['binary'] = False
    elif mimetype == 'application/json':
        try:
            msg['data'] = json.loads(raw[6], object_hook=datetime_decoder)
            msg['binary'] = False
        except ValueError:
            raise MessageError("JSON decode failed on '%s ...'" % raw[6][:36])
    elif mimetype == 'text/ascii':
        msg['data'] = str(data)
        msg['binary'] = False
    elif mimetype == 'binary/octet-stream':
        msg['data'] = data
        msg['binary'] = True
    else:
        raise MessageError("Unknown mime-type '%s'" % mimetype)

    return msg
478556
def decode(self, envelope, session, **kwargs):
		
		return WMessengerBytesEnvelope(b64decode(envelope.message()), meta=envelope)
1168130
def decode_response(client_message, to_object=None):
    
    parameters = dict(response=None)
    if not client_message.read_bool():
        parameters['response'] = EntryViewCodec.decode(client_message, to_object)
    return parameters
774765
def _decode_header(auth_header, client_id, client_secret):
    
    try:
        token = auth_header.split()[1]
        payload = jwt.decode(
            token,
            client_secret,
            audience=client_id)
    except jwt.ExpiredSignature:
        raise exceptions.NotAuthorizedException(
            'Token has expired, please log in again.')
    # is valid client
    except jwt.InvalidAudienceError:
        message = 'Incorrect audience, expected: {}'.format(
            client_id)
        raise exceptions.NotAuthorizedException(message)
    # is valid token
    except jwt.DecodeError:
        raise exceptions.NotAuthorizedException(
            'Token signature could not be validated.')
    except Exception as e:
        raise exceptions.NotAuthorizedException(
            'Token signature was malformed. {}'.format(e.message))
    return token, payload