Handle a 'headers' message.
        NOTE: we request headers in order, so we will expect to receive them in order here.
        Verify that we do so.
337318
def handle_headers( self, message_header, block_headers_message ):
        
        log.debug("handle headers (%s)" % len(block_headers_message.headers))

        block_headers = block_headers_message.headers

        serializer = BlockHeaderSerializer()

        # verify that the local header chain connects to this sequence
        current_height = SPVClient.height( self.path )
        if current_height is None:
            assert USE_TESTNET
            current_height = -1

        assert (current_height >= 0 and USE_MAINNET) or USE_TESTNET, "Invalid height %s" % current_height
    
        last_header = None

        if current_height >= 0:
            last_header = SPVClient.read_header( self.path, current_height )
            log.debug("Receive %s headers (%s to %s)" % (len(block_headers), current_height, current_height + len(block_headers)))

        else:
            # first testnet header
            log.debug("Receive %s testnet headers (%s to %s)" % (len(block_headers), current_height + 1, current_height + len(block_headers)))
            last_header = {
                "version": block_headers[0].version,
                "prev_block_hash": "%064x" % block_headers[0].prev_block,
                "merkle_root": "%064x" % block_headers[0].merkle_root,
                "timestamp": block_headers[0].timestamp,
                "bits": block_headers[0].bits,
                "nonce": block_headers[0].nonce,
                "hash": block_headers[0].calculate_hash()
            }

        if (USE_MAINNET or (USE_TESTNET and current_height >= 0)) and last_header['hash'] != self.hash_to_string(block_headers[0].prev_block):
            raise Exception("Received discontinuous block header at height %s: hash '%s' (expected '%s')" % \
                    (current_height,
                    self.hash_to_string(block_headers[0].prev_block),
                    last_header['hash'] ))

        header_start = 1
        if USE_TESTNET and current_height < 0:
            # save initial header
            header_start = 0

        # verify that this sequence of headers constitutes a hash chain 
        for i in xrange(header_start, len(block_headers)):
            prev_block_hash = self.hash_to_string(block_headers[i].prev_block)
            if i > 0 and prev_block_hash != block_headers[i-1].calculate_hash():
                raise Exception("Block '%s' is not continuous with block '%s'" % \
                        prev_block_hash,
                        block_headers[i-1].calculate_hash())

        if current_height < 0:
            # save the first header 
            if not os.path.exists(self.path):
                with open(self.path, "wb") as f:
                    block_header_serializer = BlockHeaderSerializer()
                    bin_data = block_header_serializer.serialize( block_headers[0] )
                    f.write( bin_data )

            # got all headers, including the first
            current_height = 0

        # insert into to local headers database
        next_block_id = current_height + 1
        for block_header in block_headers:
            with open(self.path, "rb+") as f:

                # omit tx count 
                block_header.txns_count = 0
                bin_data = serializer.serialize( block_header )

                if len(bin_data) != BLOCK_HEADER_SIZE:
                    raise Exception("Block %s (%s) has %s-byte header" % (next_block_id, block_header.calculate_hash(), len(bin_data)))

                # NOTE: the fact that we use seek + write ensures that we can:
                # * restart synchronizing at any point
                # * allow multiple processes to work on the chain safely (even if they're duplicating effort)
                f.seek( BLOCK_HEADER_SIZE * next_block_id, os.SEEK_SET )
                f.write( bin_data )

                if SPVClient.height( self.path ) >= self.last_block_id - 1:
                    break

                next_block_id += 1
            
        current_block_id = SPVClient.height( self.path )
        if current_block_id >= self.last_block_id - 1:
            # got all headers
            self.loop_exit()
            return

        prev_block_header = SPVClient.read_header( self.path, current_block_id )
        prev_block_hash = prev_block_header['hash']
        self.send_getheaders( prev_block_hash )
964251
def handle(handler, msg, sender, &block)
      @session.validate! sender if handler.validate?

      next_state, reply = handler.handle msg, @state, @session, sender

      return if abort_state_change?(next_state, &block)
      @state = next_state

      return unless reply

      sender.reply reply + "\r"
      logger.debug reply
    rescue Session::InvalidSender => e
      sender.reply "?\r"
      logger.warn e.message
    end
709227
def handle_message(self, client_conn, msg):
        
        # log messages received so that no one else has to
        self._logger.debug('received: {0!s}'.format(msg))

        if msg.mtype == msg.REQUEST:
            return self.handle_request(client_conn, msg)
        elif msg.mtype == msg.INFORM:
            return self.handle_inform(client_conn, msg)
        elif msg.mtype == msg.REPLY:
            return self.handle_reply(client_conn, msg)
        else:
            reason = "Unexpected message type received by server ['%s']." \
                     % (msg,)
            client_conn.inform(self.create_log_inform("error", reason, "root"))
776168
async def _process_message(self, message):
        
        self._pending_ack.add(message.msg_id)
        handler = self._handlers.get(message.obj.CONSTRUCTOR_ID,
                                     self._handle_update)
        await handler(message)
116306
def send_headers(self):
        
        self.events.sync_emit('headers')
        self._set_default_headers()
        header_str = self.status_line + self.EOL + str(self.headers)
        self.stream.write(header_str.encode())
        self.events.sync_emit('after_headers')
906880
def _build_message_headers(self):
        
        basic_deliver = self._inbound.pop(0)
        if not isinstance(basic_deliver, specification.Basic.Deliver):
            LOGGER.warning(
                'Received an out-of-order frame: %s was '
                'expecting a Basic.Deliver frame',
                type(basic_deliver)
            )
            return None
        content_header = self._inbound.pop(0)
        if not isinstance(content_header, ContentHeader):
            LOGGER.warning(
                'Received an out-of-order frame: %s was '
                'expecting a ContentHeader frame',
                type(content_header)
            )
            return None

        return basic_deliver, content_header
74005
def handle_get_request(self):
        
        self.objects = self.get_objects()
        self.response = self.get_response_handler()

        self.response.process(self.objects)

        return self.list_response()
925601
async def handler(self, request: Request) -> Tuple[int, str, List[Tuple[str, str]], bytes]:
        
        response: 'Response' = Response()

        handler: Callable = empty
        chain_reverse = self.middleware[::-1]
        for middleware in chain_reverse:
            handler = map_context_to_middleware(middleware, self, request, response, handler)

        try:
            await handler()

        except HttpException as e:
            response.code = e.code
            response.content = e.body

        return response.code, response.status, response.header_as_list, response.output
497534
def respond(response, headers_or_body = {}, body = nil)
      raise StateError, "not in header state" if @response_state != :headers

      if headers_or_body.is_a? Hash
        headers = headers_or_body
      else
        headers = {}
        body = headers_or_body
      end

      if @keepalive
        headers[CONNECTION] = KEEP_ALIVE
      else
        headers[CONNECTION] = CLOSE
      end

      case response
      when Symbol, Fixnum, Integer
        response = Response.new(response, headers, body)
      when Response
      else raise TypeError, "invalid response: #{response.inspect}"
      end

      if current_request
        current_request.handle_response(response)
      else
        raise RequestError
      end

      # Enable streaming mode
      if response.chunked? and response.body.nil?
        @response_state = :chunked_body
      elsif @keepalive
        reset_request
      else
        @current_request = nil
        @parser.reset
        @request_fsm.transition :closed
      end
    rescue IOError, SystemCallError, RequestError
      # The client disconnected early, or there is no request
      @keepalive = false
      @request_fsm.transition :closed
      @parser.reset
      @current_request = nil
    end
80144
protected <T, A> void handleMessage(final Channel channel, final DataInput message, final ManagementRequestHeader header, ManagementRequestHandler<T, A> handler) throws IOException {
        final ActiveOperation<T, A> support = getActiveOperation(header);
        if(support == null) {
            throw ProtocolLogger.ROOT_LOGGER.responseHandlerNotFound(header.getBatchId());
        }
        handleMessage(channel, message, header, support, handler);
    }
460101
def _handle_headers(self):
        
        origin = self.request.headers.get('Origin')
        if not settings.DEBUG:
            if origin in settings.ALLOWED_ORIGINS or not origin:
                self.set_header('Access-Control-Allow-Origin', origin)
            else:
                log.debug("CORS ERROR: %s not allowed, allowed hosts: %s" % (origin,
                                                                             settings.ALLOWED_ORIGINS))
                raise HTTPError(403, "Origin not in ALLOWED_ORIGINS: %s" % origin)
        else:
            self.set_header('Access-Control-Allow-Origin', origin or '*')
        self.set_header('Access-Control-Allow-Credentials', "true")
        self.set_header('Access-Control-Allow-Headers', 'Content-Type')
        self.set_header('Access-Control-Allow-Methods', 'OPTIONS')
        self.set_header('Content-Type', 'application/json')
1202697
def header(self, headers):
        
        if isinstance(headers, list):
            for h in headers:
                self.add_header(h)
        else:
            self.add_header(headers)
434073
def handle_message(message, &block)
      Timeout.timeout(timeout) do
        block.call(message.body, message.topic.name)
      end
    rescue => e
      logger.error("Error handling message #{message.id}: #{e}")
      raise e
    end
1201611
function handleResponse(ctx, response) {
  ctx.body = response.body;
  ctx.status = response.status;
  ctx.set(response.headers);
}
165421
def _do_request(self, method, *args, **kwargs):
        
        log('Doing HTTP [{3}] request: {0} - headers: {1} - payload: {2}'.format(
            args[0], kwargs.get('headers'), kwargs.get('json'), method,),
            level=logging.DEBUG,)
        requests_method = getattr(requests, method)
        return self._handle_response(requests_method(*args, **kwargs))
796614
def handle_POST(self):
        
        self.send_response(404)
        self.end_headers()
        self.wfile.write('not found'.encode('utf8'))
568796
def required_header(header):
    
    if header in IGNORE_HEADERS:
        return False

    if header.startswith('HTTP_') or header == 'CONTENT_TYPE':
        return True

    return False