Handles given HTTP request.
764604
def HandleRequest(self, request):
    """"""
    impersonated_username = config.CONFIG["AdminUI.debug_impersonate_user"]
    if impersonated_username:
      logging.info("Overriding user as %s", impersonated_username)
      request.user = config.CONFIG["AdminUI.debug_impersonate_user"]

    if not aff4_users.GRRUser.IsValidUsername(request.user):
      return self._BuildResponse(
          403, dict(message="Invalid username: %s" % request.user))

    try:
      router, method_metadata, args = self._router_matcher.MatchRouter(request)
    except access_control.UnauthorizedAccess as e:
      error_message = str(e)
      logging.exception("Access denied to %s (%s): %s", request.path,
                        request.method, e)

      additional_headers = {
          "X-GRR-Unauthorized-Access-Reason": error_message.replace("\n", ""),
          "X-GRR-Unauthorized-Access-Subject": utils.SmartStr(e.subject)
      }
      return self._BuildResponse(
          403,
          dict(
              message="Access denied by ACL: %s" % error_message,
              subject=utils.SmartStr(e.subject)),
          headers=additional_headers)

    except ApiCallRouterNotFoundError as e:
      error_message = str(e)
      return self._BuildResponse(404, dict(message=error_message))
    except werkzeug_exceptions.MethodNotAllowed as e:
      error_message = str(e)
      return self._BuildResponse(405, dict(message=error_message))
    except Error as e:
      logging.exception("Can't match URL to router/method: %s", e)

      return self._BuildResponse(
          500, dict(message=str(e), traceBack=traceback.format_exc()))

    request.method_metadata = method_metadata
    request.parsed_args = args

    # SetUID() is called here so that ACL checks done by the router do not
    # clash with datastore ACL checks.
    # TODO(user): increase token expiry time.
    token = self.BuildToken(request, 60).SetUID()

    if data_store.AFF4Enabled():
      # TODO:
      # AFF4 edge case: if a user is issuing a request, before they are created
      # using CreateGRRUser (e.g. in E2E tests or with single sign-on),
      # AFF4's ReadGRRUsers will NEVER contain the user, because the creation
      # done in the following lines does not add the user to the /users/
      # collection. Furthermore, subsequent CreateGrrUserHandler calls fail,
      # because the user technically already exists.

      # We send a blind-write request to ensure that the user object is created
      # for a user specified by the username.
      user_urn = rdfvalue.RDFURN("aff4:/users/").Add(request.user)
      # We can't use conventional AFF4 interface, since aff4.FACTORY.Create will
      # create a new version of the object for every call.
      with data_store.DB.GetMutationPool() as pool:
        pool.MultiSet(
            user_urn, {
                aff4_users.GRRUser.SchemaCls.TYPE:
                    [aff4_users.GRRUser.__name__],
                aff4_users.GRRUser.SchemaCls.LAST:
                    [rdfvalue.RDFDatetime.Now().SerializeToDataStore()]
            },
            replace=True)

    if data_store.RelationalDBEnabled():
      data_store.REL_DB.WriteGRRUser(request.user)

    handler = None
    try:
      # ACL checks are done here by the router. If this method succeeds (i.e.
      # does not raise), then handlers run without further ACL checks (they're
      # free to do some in their own implementations, though).
      handler = getattr(router, method_metadata.name)(args, token=token)

      if handler.args_type != method_metadata.args_type:
        raise RuntimeError("Handler args type doesn't match "
                           "method args type: %s vs %s" %
                           (handler.args_type, method_metadata.args_type))

      binary_result_type = (
          api_call_router.RouterMethodMetadata.BINARY_STREAM_RESULT_TYPE)

      if (handler.result_type != method_metadata.result_type and
          not (handler.result_type is None and
               method_metadata.result_type == binary_result_type)):
        raise RuntimeError("Handler result type doesn't match "
                           "method result type: %s vs %s" %
                           (handler.result_type, method_metadata.result_type))

      # HEAD method is only used for checking the ACLs for particular API
      # methods.
      if request.method == "HEAD":
        # If the request would return a stream, we add the Content-Length
        # header to the response.
        if (method_metadata.result_type ==
            method_metadata.BINARY_STREAM_RESULT_TYPE):
          binary_stream = handler.Handle(args, token=token)
          return self._BuildResponse(
              200, {"status": "OK"},
              method_name=method_metadata.name,
              no_audit_log=method_metadata.no_audit_log_required,
              content_length=binary_stream.content_length,
              token=token)
        else:
          return self._BuildResponse(
              200, {"status": "OK"},
              method_name=method_metadata.name,
              no_audit_log=method_metadata.no_audit_log_required,
              token=token)

      if (method_metadata.result_type ==
          method_metadata.BINARY_STREAM_RESULT_TYPE):
        binary_stream = handler.Handle(args, token=token)
        return self._BuildStreamingResponse(
            binary_stream, method_name=method_metadata.name)
      else:
        format_mode = GetRequestFormatMode(request, method_metadata)
        result = self.CallApiHandler(handler, args, token=token)
        rendered_data = self._FormatResultAsJson(
            result, format_mode=format_mode)

        return self._BuildResponse(
            200,
            rendered_data,
            method_name=method_metadata.name,
            no_audit_log=method_metadata.no_audit_log_required,
            token=token)
    except access_control.UnauthorizedAccess as e:
      error_message = str(e)
      logging.warning("Access denied for %s (HTTP %s %s): %s",
                      method_metadata.name, request.method, request.path,
                      error_message)

      additional_headers = {
          "X-GRR-Unauthorized-Access-Reason": error_message.replace("\n", ""),
          "X-GRR-Unauthorized-Access-Subject": utils.SmartStr(e.subject)
      }
      return self._BuildResponse(
          403,
          dict(
              message="Access denied by ACL: %s" % error_message,
              subject=utils.SmartStr(e.subject)),
          headers=additional_headers,
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
    except api_call_handler_base.ResourceNotFoundError as e:
      error_message = str(e)
      return self._BuildResponse(
          404,
          dict(message=error_message),
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
    except NotImplementedError as e:
      error_message = str(e)
      return self._BuildResponse(
          501,
          dict(message=error_message),
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
    except Exception as e:  # pylint: disable=broad-except
      error_message = str(e)
      logging.exception("Error while processing %s (%s) with %s: %s",
                        request.path, request.method,
                        handler.__class__.__name__, e)
      return self._BuildResponse(
          500,
          dict(message=error_message, traceBack=traceback.format_exc()),
          method_name=method_metadata.name,
          no_audit_log=method_metadata.no_audit_log_required,
          token=token)
1148066
private HttpResponse executeCurrentRequest(HttpRequest request) throws IOException {
    // enable GZip encoding if necessary
    if (!disableGZipContent && !(request.getContent() instanceof EmptyContent)) {
      request.setEncoding(new GZipEncoding());
    }
    // execute request
    HttpResponse response = executeCurrentRequestWithoutGZip(request);
    return response;
  }
330284
def ProcessHttpResponse(self, method_config, http_response, request=None):
        """"""
        return self.__client.ProcessResponse(
            method_config,
            self.__ProcessHttpResponse(method_config, http_response, request))
405981
public function handleRequest()
    {
        // Create the request very early so the ResourceManagement has a chance to grab it:
        $request = Request::createFromEnvironment();
        $response = new Response();
        $this->componentContext = new ComponentContext($request, $response);

        $this->boot();
        $this->resolveDependencies();
        $response = $this->addPoweredByHeader($response);
        $this->componentContext->replaceHttpResponse($response);
        $baseUriSetting = $this->bootstrap->getObjectManager()->get(ConfigurationManager::class)->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_SETTINGS, 'Neos.Flow.http.baseUri');
        if (!empty($baseUriSetting)) {
            $baseUri = new Uri($baseUriSetting);
            $request = $request->withAttribute(Request::ATTRIBUTE_BASE_URI, $baseUri);
            $this->componentContext->replaceHttpRequest($request);
        }

        $this->baseComponentChain->handle($this->componentContext);
        $response = $this->baseComponentChain->getResponse();

        $response->send();

        $this->bootstrap->shutdown(Bootstrap::RUNLEVEL_RUNTIME);
        $this->exit->__invoke();
    }
710253
def handle_get(self):
        

        code = 400
        message, explain = BaseHTTPRequestHandler.responses[code]

        response = http_server.DEFAULT_ERROR_MESSAGE % \
            {
             'code' : code,
             'message' : message,
             'explain' : explain
            }
        response = response.encode('utf-8')
        print('Status: %d %s' % (code, message))
        print('Content-Type: %s' % http_server.DEFAULT_ERROR_CONTENT_TYPE)
        print('Content-Length: %d' % len(response))
        print()
        sys.stdout.flush()
        sys.stdout.buffer.write(response)
        sys.stdout.buffer.flush()
614943
public void handle(String pathInContext,
                       String pathParams,
                       HttpRequest httpRequest,
                       HttpResponse httpResponse)
         throws IOException
    {
        if (!isStarted())
            return;
        
        // Handle TRACE
        if (HttpRequest.__TRACE.equals(httpRequest.getMethod()))
        {
            handleTrace(httpRequest,httpResponse);
            return;
        }

        // Look for existing request/response objects (from enterScope call)
        ServletHttpRequest request = (ServletHttpRequest) httpRequest.getWrapper();
        ServletHttpResponse response = (ServletHttpResponse) httpResponse.getWrapper();
        if (request==null)
        {
            // Not in ServletHttpContext, but bumble on anyway
            request = new ServletHttpRequest(this,pathInContext,httpRequest);
            response = new ServletHttpResponse(request,httpResponse);
            httpRequest.setWrapper(request);
            httpResponse.setWrapper(response);
        }
        else
        {
            request.recycle(this,pathInContext);
            response.recycle();
        }
        
        // Look for the servlet
        Map.Entry servlet=getHolderEntry(pathInContext);
        ServletHolder servletHolder=servlet==null?null:(ServletHolder)servlet.getValue();
        if(log.isDebugEnabled())log.debug("servlet="+servlet);
            
        try
        {
            // Adjust request paths
            if (servlet!=null)
            {
                String servletPathSpec=(String)servlet.getKey(); 
                request.setServletPaths(PathMap.pathMatch(servletPathSpec,pathInContext),
                                        PathMap.pathInfo(servletPathSpec,pathInContext),
                                        servletHolder);
            }
            
            // Handle the session ID
            request.setRequestedSessionId(pathParams);
            HttpSession session=request.getSession(false);
            if (session!=null)
                ((SessionManager.Session)session).access();
            if(log.isDebugEnabled())log.debug("session="+session);
            
            // Do that funky filter and servlet thang!
            if (servletHolder!=null)
                dispatch(pathInContext,request,response,servletHolder, Dispatcher.__REQUEST);
        }
        catch(Exception e)
        {
            log.debug(LogSupport.EXCEPTION,e);
            
            Throwable th=e;
            while (th instanceof ServletException)
            {
                log.warn(LogSupport.EXCEPTION, th);
                Throwable cause=((ServletException)th).getRootCause();
                if (cause==th || cause==null)
                    break;
                th=cause;
            }
            
            if (th instanceof HttpException)
                throw (HttpException)th;
            if (th instanceof EOFException)
                throw (IOException)th;
            else if (log.isDebugEnabled() || !( th instanceof java.io.IOException))
            {
                if (_contextLog!=null)
                {
                    if (th instanceof RuntimeException) 
                        _contextLog.error(httpRequest.getURI()+": ",th);
                    else
                        _contextLog.warn(httpRequest.getURI()+": ",th);
                }
                
                if(log.isDebugEnabled())
                {
                    if (th instanceof RuntimeException) 
                        log.error(httpRequest.getURI()+": ",th);
                    else
                        log.warn(httpRequest.getURI()+": ",th);
                    log.debug(httpRequest);
                }
            }
            
            httpResponse.getHttpConnection().forceClose();
            if (!httpResponse.isCommitted())
            {
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,th.getClass());
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,th);
                if (th instanceof UnavailableException)
                {
                    UnavailableException ue = (UnavailableException)th;
                    if (ue.isPermanent())
                        response.sendError(HttpResponse.__404_Not_Found,e.getMessage());
                    else
                        response.sendError(HttpResponse.__503_Service_Unavailable,e.getMessage());
                }
                else
                    response.sendError(HttpResponse.__500_Internal_Server_Error,e.getMessage());
            }
            else
                if(log.isDebugEnabled())log.debug("Response already committed for handling "+th);
        }
        catch(Error e)
        {   
            log.warn("Error for "+httpRequest.getURI(),e);
            if(log.isDebugEnabled())log.debug(httpRequest);
            
            httpResponse.getHttpConnection().forceClose();
            if (!httpResponse.isCommitted())
            {
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION_TYPE,e.getClass());
                request.setAttribute(ServletHandler.__J_S_ERROR_EXCEPTION,e);
                response.sendError(HttpResponse.__500_Internal_Server_Error,
                                   e.getMessage());
            }
            else
                if(log.isDebugEnabled())log.debug("Response already committed for handling ",e);
        }
        finally
        {
            if (servletHolder!=null && response!=null)
            {
                response.complete();
            }
        }
    }
1317897
def http_method(self, data):
        """"""
        data = data.upper()
        if data in ['DELETE', 'GET', 'POST', 'PUT']:
            self._request.http_method = data
            self._http_method = data
1167733
public void handle(Request request, Response response) throws Exception {
		if (Environment.isDevelopment()) {
			this.middlewares = this.middlewareFactory.create();
		}
		
		try {
			handle(request, response, new ArrayList<Middleware>(Arrays.asList(middlewares)));
		} catch (Exception e) {
			if (exceptionHandler != null) {
				exceptionHandler.handle(e, request, response);
			} else {
				throw e;
			}
		}
	}
642887
def handle_one_request(self):
        """"""
        self.raw_requestline = self.rfile.readline()
        if not self.raw_requestline:
            self.close_connection = 1
        elif self.parse_request():
            return self.run_wsgi()
432962
public void handle(
        String pathInContext,
        String pathParams,
        HttpRequest request,
        HttpResponse response)
        throws HttpException, IOException
    {
        String userAgent = request.getField(HttpFields.__UserAgent);
        
        if(userAgent != null &&  
           userAgent.indexOf( userAgentSubString)>=0 &&
           HttpRequest.__SSL_SCHEME.equalsIgnoreCase(request.getScheme()))
        {
            if (log.isDebugEnabled())
                log.debug("Force close");
            response.setField(HttpFields.__Connection, HttpFields.__Close);
            request.getHttpConnection().forceClose();
        }
    }
844070
public void handle(ServerHttpRequest request, ServerHttpResponse response)
			throws IOException {
		try {
			Assert.state(request.getHeaders().getContentLength() > 0, "No content");
			ObjectInputStream objectInputStream = new ObjectInputStream(
					request.getBody());
			ClassLoaderFiles files = (ClassLoaderFiles) objectInputStream.readObject();
			objectInputStream.close();
			this.server.updateAndRestart(files);
			response.setStatusCode(HttpStatus.OK);
		}
		catch (Exception ex) {
			logger.warn("Unable to handler restart server HTTP request", ex);
			response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
		}
	}
576193
private void handleNewRequest() {

        // if this is an http/2 request, skip to discrimination
        if (!isAlpnHttp2Link(this.vc)) {
            final HttpInboundServiceContextImpl sc = getHTTPContext();
            // save the request info that was parsed in case somebody changes it
            sc.setRequestVersion(sc.getRequest().getVersionValue());
            sc.setRequestMethod(sc.getRequest().getMethodValue());

            // get the response message initialized. Note: in the proxy env, this
            // response message will be overwritten; however, this is the only
            // spot to init() it correctly for all other cases.
            sc.getResponseImpl().init(sc);

            this.numRequestsProcessed++;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Received request number " + this.numRequestsProcessed + " on link " + this);
            }

            // check for the 100-continue scenario
            if (!sc.check100Continue()) {
                return;
            }
        }
        handleDiscrimination();
    }
25771
def _handle_request(self, request):
        """"""

        # Check if this is a persistent connection.
        if request['version'] == 'HTTP/1.1':
            self.keepalive = not request.get('Connection') == 'close'
        elif request['version'] == 'HTTP/1.0':
            self.keepalive = request.get('Connection') == 'Keep-Alive'

        # Check if we're getting a sane request
        if request['method'] not in ('GET'):
            raise InvalidRequestError(501, 'Method not implemented')
        if request['version'] not in ('HTTP/1.0', 'HTTP/1.1'):
            raise InvalidRequestError(
                505, 'Version not supported. Supported versions are: {}, {}'
                .format('HTTP/1.0', 'HTTP/1.1'))

        host, location = self._get_request_uri(request)

        # We must ignore the Host header if a host is specified in GET
        if host is None:
            host = request.get('Host')

        # Check if this request is intended for this webserver
        if host is not None and not host == self.host:
            self.logger.info('Got a request for unknown host %s', host)
            raise InvalidRequestError(404, "We don't serve this host")

        filename = os.path.join(self.folder, unquote(location))
        self.logger.debug('trying to serve %s', filename)

        if os.path.isdir(filename):
            filename = os.path.join(filename, 'index.html')

        if not os.path.isfile(filename):
            raise InvalidRequestError(404, 'Not Found')

        # Start response with version
        response = _get_response(version=request['version'])

        # timeout negotiation
        match = re.match(r'timeout=(\d+)', request.get('Keep-Alive', ''))
        if match is not None:
            requested_timeout = int(match.group(1))
            if requested_timeout < self._timeout:
                self._timeout = requested_timeout

        # tell the client our timeout
        if self.keepalive:
            response['headers'][
                'Keep-Alive'] = 'timeout={}'.format(self._timeout)

        # Set Content-Type
        response['headers']['Content-Type'] = mimetypes.guess_type(
            filename)[0] or 'text/plain'

        # Generate E-tag
        sha1 = hashlib.sha1()
        with open(filename, 'rb') as fp:
            response['body'] = fp.read()
            sha1.update(response['body'])
        etag = sha1.hexdigest()

        # Create 304 response if if-none-match matches etag
        if request.get('If-None-Match') == '"{}"'.format(etag):
            # 304 responses shouldn't contain many headers we might already
            # have added.
            response = _get_response(code=304)

        response['headers']['Etag'] = '"{}"'.format(etag)

        self._write_response(response)
1294770
def handle_request(self, msgtype, msgid, method, args, kwargs):
        """"""
        response = None
        error = None
        exception = None

        try:
            response = self.dispatch.call(method, args, kwargs)
        except Exception as e:
            error = (e.__class__.__name__, str(e))
            exception = e

        if isinstance(response, Deferred):
            response.add_callback(self.send_response, msgid)
            response.add_errback(self.send_error, msgid)
        else:
            if exception is None:
                self.send_response(msgid, response)
            else:
                self.send_error(msgid, exception)
277981
public void handleOptions(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
        // Handle OPTIONS request for entire server
        // 9.2
        response.setIntHeader(HttpFields.__ContentLength, 0);
        response.setHeader(HttpFields.__Allow, _AllowString);
        response.flushBuffer();
    }
780062
protected void handleOptions(HttpServletRequest request,
                              HttpServletResponse response)
        throws IOException
    {
        // Handle OPTIONS request for entire server
        if ("*".equals(request.getRequestURI()))
        {
            // 9.2
            response.setIntHeader(HttpFields.__ContentLength,0);
            response.setHeader(HttpFields.__Allow,__AllowString);                
            response.flushBuffer();
        }
        else
            response.sendError(HttpResponse.__404_Not_Found);
    }
448072
def handle_request(self):
        """"""
        try:
            request, client_address = self.get_request()
        except socket.error:
            return

        if self.verify_request(request, client_address):
            self.requests.put((request, client_address))