/**
  * Implements module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param int                                                    $hook           The current hook to process logic for
  *
  * @return bool
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     // if false hook is coming do nothing
     if (ModuleHooks::REQUEST_POST !== $hook) {
         return;
     }
     // set req and res object internally
     $this->request = $request;
     $this->response = $response;
     // get server context to local var
     $serverContext = $this->getServerContext();
     // Get the authentications locally so we do not mess with inter-request configuration
     $authenticationSets = array();
     // check if there are some volatile rewrite map definitions so add them
     if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_AUTHENTICATIONS)) {
         $authenticationSets[] = $requestContext->getModuleVar(ModuleVars::VOLATILE_AUTHENTICATIONS);
     }
     // get the global authentications last, as volatile authentications are prefered here as more specific configurations can lessen security
     $authenticationSets[] = $this->authentications;
     // get system logger
     $systemLogger = $serverContext->getLogger(LoggerUtils::SYSTEM);
     // check authentication information if something matches
     foreach ($authenticationSets as $authenticationSet) {
         foreach ($authenticationSet as $uriPattern => $data) {
             // check if pattern matches uri
             if (preg_match('/' . $uriPattern . '/', $requestContext->getServerVar(ServerVars::X_REQUEST_URI))) {
                 try {
                     // append the document root to the authentication params
                     $data['documentRoot'] = $requestContext->getServerVar(ServerVars::DOCUMENT_ROOT);
                     // create a local type instance, initialize and authenticate the request
                     $typeInstance = $this->getAuthenticationInstance($uriPattern, $data);
                     $typeInstance->init($request, $response);
                     $typeInstance->authenticate($response);
                     // set authenticated username as a server var
                     $requestContext->setServerVar(ServerVars::REMOTE_USER, $typeInstance->getUsername());
                     // break out because everything is fine at this point
                     break;
                 } catch (\Exception $e) {
                     // log exception as warning to not end up with a 500 response which is not wanted here
                     $systemLogger->warning($e->getMessage());
                 }
                 // throw exception for auth required
                 throw new ModuleException(null, 401);
             }
         }
     }
 }
Example #2
0
 /**
  * Creates and returns a new FastCGI client instance.
  *
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  *
  * @return \Crunch\FastCGI\Connection The FastCGI connection instance
  */
 protected function getFastCgiClient(RequestContextInterface $requestContext)
 {
     // initialize default host/port
     $host = FastCgiModule::DEFAULT_FAST_CGI_IP;
     $port = FastCgiModule::DEFAULT_FAST_CGI_PORT;
     // set the connection data to be used for the Fast-CGI connection
     $fileHandlerVariables = array();
     // check if we've configured module variables
     if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_FILE_HANDLER_VARIABLES)) {
         // load the volatile file handler variables and set connection data
         $fileHandlerVariables = $requestContext->getModuleVar(ModuleVars::VOLATILE_FILE_HANDLER_VARIABLES);
         if (isset($fileHandlerVariables['host'])) {
             $host = $fileHandlerVariables['host'];
         }
         if (isset($fileHandlerVariables['port'])) {
             $port = $fileHandlerVariables['port'];
         }
     }
     // create and return the FastCGI client
     return new FastCgiClient($host, $port);
 }
 /**
  * Implements module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param int                                                    $hook           The current hook to process logic for
  *
  * @return bool
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     // In php an interface is, by definition, a fixed contract. It is immutable.
     // So we have to declair the right ones afterwards...
     /**
      * @var $request \AppserverIo\Psr\HttpMessage\RequestInterface
      */
     /**
      * @var $response \AppserverIo\Psr\HttpMessage\ResponseInterface
      */
     // if false hook is comming do nothing
     if (ModuleHooks::REQUEST_POST !== $hook) {
         return;
     }
     // set req and res object internally
     $this->request = $request;
     $this->response = $response;
     // get default rewrite maps definitions
     $rewriteMaps = $this->rewriteMaps;
     // check if there are some volatile rewrite map definitions so add them
     if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_REWRITE_MAPS)) {
         $volatileRewriteMaps = $requestContext->getModuleVar(ModuleVars::VOLATILE_REWRITE_MAPS);
         // merge rewrite maps
         $rewriteMaps = array_merge($volatileRewriteMaps, $this->rewriteMaps);
     }
     // check protocol to be either http or https when secure is going on
     $protocol = 'http://';
     if ($requestContext->getServerVar(ServerVars::HTTPS) === ServerVars::VALUE_HTTPS_ON) {
         $protocol = 'https://';
     }
     // get clean request path without query string etc...
     $requestPath = parse_url($requestContext->getServerVar(ServerVars::X_REQUEST_URI), PHP_URL_PATH);
     // init all rewrite mappers by types and do look up
     foreach ($rewriteMaps as $rewriteMapType => $rewriteMapParams) {
         // Include the requested hostname as a param, some mappers might need it
         $rewriteMapParams['headerHost'] = $request->getHeader(Protocol::HEADER_HOST);
         // Same for the protocol
         $rewriteMapParams['protocol'] = $protocol;
         // Get ourselves a rewriteMapper of the right type
         $rewriteMapper = new $rewriteMapType($rewriteMapParams);
         // lookup by request path
         if ($targetUrl = $rewriteMapper->lookup($requestPath)) {
             // set enhance uri to response
             $response->addHeader(Protocol::HEADER_LOCATION, $targetUrl);
             // send redirect status
             $response->setStatusCode(301);
             // add header to be sure that is was us
             $response->addHeader('X-Rewritten-By', __CLASS__);
             // set response state to be dispatched after this without calling other modules process
             $response->setState(HttpResponseStates::DISPATCH);
             // We found something, stop the loop
             break;
         }
     }
     return true;
 }
 /**
  * Implements module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param int                                                    $hook           The current hook to process logic for
  *
  * @return bool
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     /**
      * @var $request \AppserverIo\Psr\HttpMessage\RequestInterface
      */
     /**
      * @var $response \AppserverIo\Psr\HttpMessage\ResponseInterface
      */
     // if false hook is comming do nothing
     if (ModuleHooks::REQUEST_POST !== $hook) {
         return;
     }
     // load the locations
     $locations = $this->locations;
     // check if there are some volatile location definitions so use them and override global locations
     if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_LOCATIONS)) {
         $locations = $requestContext->getModuleVar(ModuleVars::VOLATILE_LOCATIONS);
     }
     // query whether we've locations configured or not
     if (sizeof($locations) === 0) {
         return;
     }
     // initialize the array for the handlers
     $handlers = array();
     // initialize the array for the headers
     $headers = array();
     // load the actual request URI without query string
     $uriWithoutQueryString = $requestContext->getServerVar(ServerVars::X_REQUEST_URI);
     // process the all locations found for this request
     foreach ($locations as $location) {
         // query whether the location matches the acutal request URI
         if (preg_match('/' . $location['condition'] . '/', $uriWithoutQueryString)) {
             // query whether the location has file handlers configured for the actual URI
             if (isset($location['params'])) {
                 // iterate over all params and try to set as server var via mapping
                 foreach ($location['params'] as $paramName => $paramValue) {
                     // check if server var mapping exists
                     if (isset($this->paramServerVarsMap[$paramName])) {
                         // check if documentRoot is changed
                         if ($this->paramServerVarsMap[$paramName] === ServerVars::DOCUMENT_ROOT) {
                             // check if relative path is given and make is absolute by using cwd as prefix
                             if (substr($paramValue, 0, 1) !== "/") {
                                 $paramValue = getcwd() . DIRECTORY_SEPARATOR . $paramValue;
                             }
                         }
                         // set server var
                         $requestContext->setServerVar($this->paramServerVarsMap[$paramName], $paramValue);
                     }
                 }
             }
             // query whether the location has file handlers configured for the actual URI
             if (isset($location['handlers'])) {
                 $handlers = array_merge($handlers, $location['handlers']);
             }
             // merge headers information to volatile headers if exists
             if (isset($location['headers']) && is_array($location['headers'])) {
                 $volatileHeaders = array();
                 if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_HEADERS)) {
                     $volatileHeaders = $requestContext->getModuleVar(ModuleVars::VOLATILE_HEADERS);
                 }
                 $headers = array_merge_recursive($volatileHeaders, $location['headers']);
             }
         }
     }
     // add the handlers we have (if any)
     if (sizeof($handlers) !== 0) {
         $requestContext->setModuleVar(ModuleVars::VOLATILE_HANDLERS, $handlers);
     }
     // add the headers we have (if any)
     if (sizeof($headers) !== 0) {
         $requestContext->setModuleVar(ModuleVars::VOLATILE_HEADERS, $headers);
     }
 }
Example #5
0
 /**
  * Implement's module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param int                                                    $hook           The current hook to process logic for
  *
  * @return bool
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     // if false hook is comming do nothing
     if (ModuleHooks::RESPONSE_PRE !== $hook) {
         return;
     }
     // set req and res object internally
     $this->request = $request;
     $this->response = $response;
     // get server context ref to local func
     $serverContext = $this->getServerContext();
     // init volatile headers array
     $volatileHeaders = array();
     // apply possible volatile headers
     if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_HEADERS)) {
         $volatileHeaders = $requestContext->getModuleVar(ModuleVars::VOLATILE_HEADERS);
     }
     // apply server headers first and then volatile headers
     $this->applyHeaders(array_merge_recursive($serverContext->getServerConfig()->getHeaders(), $volatileHeaders));
     // signal good processing state
     return true;
 }
 /**
  * Implement's module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param int                                                    $hook           The current hook to process logic for
  *
  * @return bool
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     // In php an interface is, by definition, a fixed contract. It is immutable.
     // So we have to declair the right ones afterwards...
     /**
      * @var $request \AppserverIo\Psr\HttpMessage\RequestInterface
      */
     /**
      * @var $response \AppserverIo\Psr\HttpMessage\ResponseInterface
      */
     // if false hook is coming do nothing
     if (ModuleHooks::REQUEST_POST !== $hook) {
         return;
     }
     // We have to throw a ModuleException on failure, so surround the body with a try...catch block
     try {
         // set request context as member property for further usage
         $this->requestContext = $requestContext;
         // Reset the $serverBackreferences array to avoid mixups of different requests
         $this->serverBackreferences = array();
         // Resolve all used backreferences which are NOT linked to the query string.
         // We will resolve query string related backreferences separately as we are not able to cache them
         // as easily as, say, the URI
         // We also have to resolve all the changes rules in front of us made, so build up the backreferences
         // IN the loop.
         // TODO switch to backreference request not prefill as it might be faster
         $this->fillContextBackreferences();
         $this->fillHeaderBackreferences($request);
         $this->fillSslEnvironmentBackreferences();
         // Get the environment variables as the array they are within the config.
         // We have to also collect any volative rules which might be set on request base.
         // We might not even get anything, so prepare our rules accordingly
         $volatileEnvironmentVariables = array();
         if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_ENVIRONMENT_VARIABLES)) {
             $volatileEnvironmentVariables = $requestContext->getModuleVar(ModuleVars::VOLATILE_ENVIRONMENT_VARIABLES);
         }
         // Build up the complete ruleset, volatile rules up front
         $variables = array_merge($volatileEnvironmentVariables, $this->configuredVariables);
         // Only act if we got something
         if (is_array($variables)) {
             // Convert the rules to our internally used objects
             foreach ($variables as $variable) {
                 // Make that condition handling only if there even are conditions
                 if (!empty($variable['condition'])) {
                     // Get the operand
                     $condition = $variable['condition'] . $this->getDefaultOperand();
                     if (strpos($condition, '@') !== false) {
                         // Get the pieces of the condition
                         $conditionPieces = array();
                         preg_match_all('`(.*?)@(\\$[0-9a-zA-Z_\\-]+)`', $condition, $conditionPieces);
                         // Check the condition and continue for the next variable if we do not match
                         if (!isset($this->serverBackreferences[$conditionPieces[2][0]])) {
                             continue;
                         }
                         // Do we have a match? Get the potential backreferences
                         $conditionBackreferences = array();
                         if (preg_match('`' . $conditionPieces[1][0] . '`', $this->serverBackreferences[$conditionPieces[2][0]], $conditionBackreferences) !== 1) {
                             continue;
                         }
                     }
                 }
                 // We have to split up the definition string, if we do not find a equal character we have to fail
                 if (!strpos($variable['definition'], '=')) {
                     throw new ModuleException('Invalid definition ' . $variable['definition'] . 'missing "=".');
                 }
                 // Get the variable name and its value from the definition string
                 $varName = $this->filterVariableName(strstr($variable['definition'], '=', true));
                 $value = substr(strstr($variable['definition'], '='), 1);
                 // We also have to resolve backreferences for the value part of the definition, as people might want
                 // to pass OS environment vars to the server vars
                 if (strpos($value, '$') !== false) {
                     // Get the possible backreference (might as well be something else) and resolve it if needed
                     // TODO tell them if we do not find a backreference to resolve, might be a problem
                     $possibleBackreferences = array();
                     preg_match('`\\$.+?`', $value, $possibleBackreferences);
                     foreach ($possibleBackreferences as $possibleBackreference) {
                         if ($backrefValue = getenv($possibleBackreference)) {
                             // Do we have a backreference which is a server or env var?
                             $value = str_replace($possibleBackreference, $backrefValue, $value);
                         } elseif (isset($conditionBackreferences[(int) substr($possibleBackreference, 1)])) {
                             // We got no backreference from any of the server or env vars, so maybe we got
                             // something from the preg_match
                             $value = str_replace($possibleBackreference, $conditionBackreferences[(int) substr($possibleBackreference, 1)], $value);
                         }
                     }
                 }
                 // If the value is "null" we will unset the variable
                 if ($value === 'null') {
                     // Unset the variable and continue with the next environment variable
                     if ($requestContext->hasEnvVar($varName)) {
                         $requestContext->unsetEnvVar($varName);
                     }
                     continue;
                 }
                 // Take action according to the needed definition
                 $requestContext->setEnvVar($varName, $value);
             }
         }
     } catch (\Exception $e) {
         // Re-throw as a ModuleException
         throw new ModuleException($e);
     }
 }
Example #7
0
 /**
  * Expands request context on given request constellation (uri) based on file handler configuration
  *
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext The request context instance
  *
  * @return void
  */
 public function populateRequestContext(RequestContextInterface $requestContext)
 {
     // get local refs
     $serverContext = $this->getServerContext();
     // get document root
     $documentRoot = $requestContext->getServerVar(ServerVars::DOCUMENT_ROOT);
     // load the default handlers
     $handlers = $serverContext->getServerConfig()->getHandlers();
     // check if there are some volatile location definitions so use them and merge with global locations
     if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_HANDLERS)) {
         $handlers = array_merge($handlers, $requestContext->getModuleVar(ModuleVars::VOLATILE_HANDLERS));
     }
     // get uri without querystring
     // Just make sure that you check for the existence of the query string first, as it might not be set
     $uriWithoutQueryString = parse_url($requestContext->getServerVar(ServerVars::X_REQUEST_URI), PHP_URL_PATH);
     // check if uri without query string is just "/"
     if ($uriWithoutQueryString === '/' && $requestContext->hasServerVar(ServerVars::SERVER_WELCOME_PAGE_TEMPLATE_PATH)) {
         // in this case we will set welcome page template to be errors template
         if ($welcomePageTemplate = $requestContext->getServerVar(ServerVars::SERVER_WELCOME_PAGE_TEMPLATE_PATH)) {
             $requestContext->setServerVar(ServerVars::SERVER_ERRORS_PAGE_TEMPLATE_PATH, $welcomePageTemplate);
         }
     }
     // split all path parts got from uri without query string
     $pathParts = explode('/', $uriWithoutQueryString);
     // init vars for path parsing
     $possibleValidPathExtension = '';
     $possibleValidPath = '';
     $pathInfo = '';
     $validDir = null;
     $scriptName = null;
     $scriptFilename = null;
     // note: only if file extension hits a filehandle info it will be possible to set path info etc...
     // iterate through all dirs beginning at 1 because 0 is always empty in this case
     for ($i = 1; $i < count($pathParts); ++$i) {
         // check if no script name was found yet
         if (!$scriptName) {
             // append valid path
             $possibleValidPath .= DIRECTORY_SEPARATOR . $pathParts[$i];
             // get possible extension
             $possibleValidPathExtension = pathinfo($possibleValidPath, PATHINFO_EXTENSION);
             // check if dir does not exists
             if (!is_dir($documentRoot . $possibleValidPath)) {
                 // check if its not a existing file
                 if (!is_file($documentRoot . $possibleValidPath)) {
                     // check if file handler is defined for that virtual file
                     if (isset($handlers['.' . $possibleValidPathExtension])) {
                         // set script name for further processing as script aspect
                         $scriptName = $possibleValidPath;
                     }
                 } else {
                     // set script name
                     $scriptName = $possibleValidPath;
                     // set script filename
                     $scriptFilename = $documentRoot . $scriptName;
                 }
             } else {
                 // save valid dir for indexed surfing later on
                 $validDir = $possibleValidPath;
             }
         } else {
             // else build up path info
             $pathInfo .= DIRECTORY_SEPARATOR . $pathParts[$i];
         }
     }
     // set special server var for requested file
     $requestContext->setServerVar(ServerVars::REQUEST_FILENAME, $documentRoot . $possibleValidPath);
     // set specific script name server var if exists
     if ($scriptName) {
         $requestContext->setServerVar(ServerVars::SCRIPT_NAME, $scriptName);
     }
     // check if requested file is on filesystem and set it to be valid script filename
     if ($scriptFilename) {
         $requestContext->setServerVar(ServerVars::SCRIPT_FILENAME, $scriptFilename);
     }
     // if path info is set put it into server vars
     if (strlen($pathInfo) > 0) {
         // set path info vars
         $requestContext->setServerVar(ServerVars::PATH_INFO, $pathInfo);
         $requestContext->setServerVar(ServerVars::PATH_TRANSLATED, $documentRoot . $pathInfo);
     }
     // first check if wildcard file handler was registered
     if (isset($handlers['.*'])) {
         // set wildcard filehandler which will overload all specific filehandlers at this point
         $possibleValidPathExtension = '*';
     }
     // check if file handler is defined for that script and expand request context
     if (isset($handlers['.' . $possibleValidPathExtension])) {
         // set the file handler to use for modules being able to react on this setting
         $requestContext->setServerVar(ServerVars::SERVER_HANDLER, $handlers['.' . $possibleValidPathExtension]['name']);
         // if file handler params are given, set them as module var
         if (isset($handlers['.' . $possibleValidPathExtension]['params'])) {
             $requestContext->setModuleVar(ModuleVars::VOLATILE_FILE_HANDLER_VARIABLES, $handlers['.' . $possibleValidPathExtension]['params']);
         }
     }
 }
Example #8
0
 /**
  * Implements module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param int                                                    $hook           The current hook to process logic for
  *
  * @return bool
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     // get server context to local ref
     $serverContext = $this->getServerContext();
     // check if response post is is comming
     if (ModuleHooks::RESPONSE_POST === $hook) {
         $this->checkShouldDisconnect();
         return;
     }
     // if wrong hook is coming do nothing
     if (ModuleHooks::REQUEST_POST !== $hook) {
         return;
     }
     try {
         // init upstreamname and transport
         $upstreamName = null;
         $transport = 'tcp';
         // check if we've configured module variables
         if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_FILE_HANDLER_VARIABLES)) {
             // load the volatile file handler variables and set connection data
             $fileHandlerVariables = $requestContext->getModuleVar(ModuleVars::VOLATILE_FILE_HANDLER_VARIABLES);
             // check if upstream is set for proxy function
             if (isset($fileHandlerVariables['upstream'])) {
                 $upstreamName = $fileHandlerVariables['upstream'];
             }
             if (isset($fileHandlerVariables['transport'])) {
                 $transport = $fileHandlerVariables['transport'];
             }
         }
         // if there was no upstream defined
         if (is_null($upstreamName)) {
             throw new ModuleException('No upstream configured for proxy filehandler');
         }
         // get upstream instance by configured upstream name
         $upstream = $serverContext->getUpstream($upstreamName);
         // find next proxy server by given upstream type
         $remoteAddr = $requestContext->getServerVar(ServerVars::REMOTE_ADDR);
         $proxyServer = $upstream->findServer(md5($remoteAddr));
         // build proxy socket address for connection
         $proxySocketAddress = sprintf('%s://%s:%s', $transport, $proxyServer->getAddress(), $proxyServer->getPort());
         // check if should reconnect
         $this->checkShouldDisconnect();
         // check if proxy connection object was initialised but connection resource is not ready
         if ($this->connection && $this->connection->getStatus() === false) {
             // unset connection if corrupt
             $this->connection = null;
         }
         // check if connection should be established
         if ($this->connection === null) {
             // create and connect to defined backend
             $this->connection = StreamSocket::getClientInstance($proxySocketAddress);
             // set proxy connection resource as stream source for body stream directly
             // that avoids huge memory consumtion when transferring big files via proxy connections
             $response->setBodyStream($this->connection->getConnectionResource());
         }
         // get connection to local var
         $connection = $this->connection;
         // build up raw request start line
         $rawRequestString = sprintf('%s %s %s' . "\r\n", $request->getMethod(), $request->getUri(), HttpProtocol::VERSION_1_1);
         // populate request headers
         $headers = $request->getHeaders();
         foreach ($headers as $headerName => $headerValue) {
             // @todo: make keep-alive available for proxy connections
             if ($headerName === HttpProtocol::HEADER_CONNECTION) {
                 $headerValue = HttpProtocol::HEADER_CONNECTION_VALUE_CLOSE;
             }
             $rawRequestString .= $headerName . HttpProtocol::HEADER_SEPARATOR . $headerValue . "\r\n";
         }
         // get current protocol
         $reqProto = $requestContext->getServerVar(ServerVars::REQUEST_SCHEME);
         // add proxy depending headers
         $rawRequestString .= HttpProtocol::HEADER_X_FORWARD_FOR . HttpProtocol::HEADER_SEPARATOR . $remoteAddr . "\r\n";
         $rawRequestString .= HttpProtocol::HEADER_X_FORWARDED_PROTO . HttpProtocol::HEADER_SEPARATOR . $reqProto . "\r\n";
         $rawRequestString .= "\r\n";
         // write headers to proxy connection
         $connection->write($rawRequestString);
         // copy raw request body stream to proxy connection
         $connection->copyStream($request->getBodyStream());
         // read status line from proxy connection
         $statusLine = $connection->readLine(1024, 5);
         // parse start line
         list(, $responseStatusCode) = explode(' ', $statusLine);
         // map everything from proxy response to our response object
         $response->setStatusCode($responseStatusCode);
         $line = '';
         $messageHeaders = '';
         while (!in_array($line, array("\r\n", "\n"))) {
             // read next line
             $line = $connection->readLine();
             // enhance headers
             $messageHeaders .= $line;
         }
         // remove ending CRLF's before parsing
         $messageHeaders = trim($messageHeaders);
         // check if headers are empty
         if (strlen($messageHeaders) === 0) {
             throw new HttpException('Missing headers');
         }
         // delimit headers by CRLF
         $headerLines = explode("\r\n", $messageHeaders);
         // iterate all headers
         foreach ($headerLines as $headerLine) {
             // extract header info
             $extractedHeaderInfo = explode(HttpProtocol::HEADER_SEPARATOR, trim($headerLine));
             if (!$extractedHeaderInfo || $extractedHeaderInfo[0] === $headerLine) {
                 throw new HttpException('Wrong header format');
             }
             // split name and value
             list($headerName, $headerValue) = $extractedHeaderInfo;
             // check header name for server
             // @todo: make this configurable
             if ($headerName === HttpProtocol::HEADER_SERVER) {
                 continue;
             }
             // add header
             $response->addHeader(trim($headerName), trim($headerValue));
         }
         // set flag false by default
         $this->shouldDisconnect = false;
         // check if connection should be closed as given in connection header
         if ($response->getHeader(HttpProtocol::HEADER_CONNECTION) === HttpProtocol::HEADER_CONNECTION_VALUE_CLOSE) {
             $this->shouldDisconnect = true;
         }
     } catch (\AppserverIo\Psr\Socket\SocketReadException $e) {
         // close and unset connection and try to process the request again to
         // not let a white page get delivered to the client
         $this->shouldDisconnect = true;
         return $this->process($request, $response, $requestContext, $hook);
     } catch (\AppserverIo\Psr\Socket\SocketReadTimeoutException $e) {
         // close and unset connection and try to process the request again to
         // not let a white page get delivered to the client
         $this->shouldDisconnect = true;
         return $this->process($request, $response, $requestContext, $hook);
     }
     // set response to be dispatched at this point
     $response->setState(HttpResponseStates::DISPATCH);
 }
 /**
  * Implements module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param int                                                    $hook           The current hook to process logic for
  *
  * @return bool
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     // if false hook is coming do nothing
     if (ModuleHooks::REQUEST_POST !== $hook) {
         return;
     }
     // set req and res object internally
     $this->request = $request;
     $this->response = $response;
     // get server context to local var
     $serverContext = $this->getServerContext();
     // Get the authentications locally so we do not mess with inter-request configuration
     $authenticationSets = array();
     // check if there are some volatile rewrite map definitions so add them
     if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_AUTHENTICATIONS)) {
         $authenticationSets[] = $requestContext->getModuleVar(ModuleVars::VOLATILE_AUTHENTICATIONS);
     }
     // get the global authentications last, as volatile authentications are prefered here as more specific configurations can lessen security
     $authenticationSets[] = $this->authentications;
     // get system logger
     $systemLogger = $serverContext->getLogger(LoggerUtils::SYSTEM);
     // check authentication information if something matches
     foreach ($authenticationSets as $authenticationSet) {
         foreach ($authenticationSet as $uriPattern => $data) {
             // check if pattern matches uri
             if (preg_match('/' . $uriPattern . '/', $requestContext->getServerVar(ServerVars::X_REQUEST_URI))) {
                 // set type Instance to local ref
                 $typeInstance = $this->getAuthenticationInstance($uriPattern, $data);
                 // check if auth header is not set in coming request headers
                 if (!$request->hasHeader(Protocol::HEADER_AUTHORIZATION)) {
                     // send header for challenge authentication against client
                     $response->addHeader(Protocol::HEADER_WWW_AUTHENTICATE, $typeInstance->getAuthenticateHeader());
                     // throw exception for auth required
                     throw new ModuleException(null, 401);
                 }
                 // init type instance by request
                 $typeInstance->init($request->getHeader(Protocol::HEADER_AUTHORIZATION), $request->getMethod());
                 try {
                     // check if auth works
                     if ($typeInstance->authenticate()) {
                         // set server vars
                         $requestContext->setServerVar(ServerVars::REMOTE_USER, $typeInstance->getUsername());
                         // break out because everything is fine at this point
                         break;
                     }
                 } catch (\Exception $e) {
                     // log exception as warning to not end up with a 500 response which is not wanted here
                     $systemLogger->warning($e->getMessage());
                 }
                 // send header for challenge authentication against client
                 $response->addHeader(Protocol::HEADER_WWW_AUTHENTICATE, $typeInstance->getAuthenticateHeader());
                 // throw exception for auth required
                 throw new ModuleException(null, 401);
             }
         }
     }
 }
 /**
  * Implement's module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param int                                                    $hook           The current hook to process logic for
  *
  * @return boolean
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     try {
         // if false hook is coming do nothing
         if (ModuleHooks::RESPONSE_POST !== $hook) {
             return;
         }
         // get default analytics definitions
         $analytics = $this->analytics;
         // check if there are some volatile access definitions so use them and override global accesses
         if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_ANALYTICS)) {
             // reset by volatile accesses
             $analytics = array_merge($analytics, $requestContext->getModuleVar(ModuleVars::VOLATILE_ANALYTICS));
         }
         // check all analytics and check if the uri matches
         foreach ($analytics as $analytic) {
             // run through our connectors if the if the URI matches
             $matches = array();
             if (preg_match('/' . $analytic['uri'] . '/', $requestContext->getServerVar(ServerVars::X_REQUEST_URI), $matches)) {
                 // we only need the matching parts of the URI
                 unset($matches[0]);
                 // prepare the matches for later usage
                 $backreferenceKeys = array();
                 foreach ($matches as $key => $match) {
                     $backreferenceKeys[] = '$' . $key;
                 }
                 // iterate over all connectors and call their services
                 foreach ($analytic['connectors'] as $connector) {
                     // iterate all params and fill in the regex backreferences
                     foreach ($connector['params'] as $key => $param) {
                         // if the param might contain backreferences we will replace them
                         if (strpos($param, '$') !== false) {
                             $connector['params'][$key] = str_replace($backreferenceKeys, $matches, $param);
                         }
                     }
                     // make a new connector instance, initialize it and make the call to its service
                     $connectorClass = str_replace('\\\\', '\\', $connector['type']);
                     if (class_exists($connectorClass)) {
                         // create the connector an make the call through it
                         $connectorInstance = new $connectorClass($this->serverContext);
                         $connectorInstance->init($connector['params']);
                         $connectorInstance->call($request, $response, $requestContext);
                     }
                 }
             }
         }
     } catch (\Exception $e) {
         // Re-throw as a ModuleException
         throw new ModuleException($e);
     }
 }
Example #11
0
 /**
  * Implements module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param int                                                    $hook           The current hook to process logic for
  *
  * @return bool
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     // In php an interface is, by definition, a fixed contract. It is immutable.
     // So we have to declare the right ones afterwards...
     /**
      * @var $request \AppserverIo\Psr\HttpMessage\RequestInterface
      */
     /**
      * @var $request \AppserverIo\Psr\HttpMessage\ResponseInterface
      */
     // if false hook is coming do nothing
     if (ModuleHooks::REQUEST_POST !== $hook) {
         return;
     }
     // set member ref for request context
     $this->requestContext = $requestContext;
     // We have to throw a ModuleException on failure, so surround the body with a try...catch block
     try {
         $requestUrl = $requestContext->getServerVar(ServerVars::HTTP_HOST) . $requestContext->getServerVar(ServerVars::X_REQUEST_URI);
         if (!isset($this->rules[$requestUrl])) {
             // Reset the $serverBackreferences array to avoid mixups of different requests
             $this->serverBackreferences = array();
             // Resolve all used backreferences which are NOT linked to the query string.
             // We will resolve query string related backreferences separately as we are not able to cache them
             // as easily as, say, the URI
             // We also have to resolve all the changes rules in front of us made, so build up the backreferences
             // IN the loop.
             $this->fillContextBackreferences();
             $this->fillHeaderBackreferences($request);
             // Get the rules as the array they are within the config.
             // We have to also collect any volatile rules which might be set on request base.
             // We might not even get anything, so prepare our rules accordingly
             $volatileRewrites = array();
             if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_REWRITES)) {
                 $volatileRewrites = $requestContext->getModuleVar(ModuleVars::VOLATILE_REWRITES);
             }
             // Build up the complete ruleset, volatile rules up front
             $rules = array_merge($volatileRewrites, $this->configuredRules);
             $this->rules[$requestUrl] = array();
             // Only act if we got something
             if (is_array($rules)) {
                 // Convert the rules to our internally used objects
                 foreach ($rules as $rule) {
                     // Add the rule as a Rule object
                     $rule = new Rule($rule['condition'], $rule['target'], $rule['flag']);
                     $rule->resolve($this->serverBackreferences);
                     $this->rules[$requestUrl][] = $rule;
                 }
             }
         }
         // Iterate over all rules, resolve vars and apply the rule (if needed)
         foreach ($this->rules[$requestUrl] as $rule) {
             // Check if the rule matches, and if, apply the rule
             if ($rule->matches()) {
                 // Apply the rule. If apply() returns false this means this was the last rule to process
                 if ($rule->apply($requestContext, $response, $this->serverBackreferences) === false) {
                     break;
                 }
             }
         }
     } catch (\Exception $e) {
         // Re-throw as a ModuleException
         throw new ModuleException($e);
     }
 }
Example #12
0
 /**
  * Implements module logic for given hook
  *
  * @param \AppserverIo\Psr\HttpMessage\RequestInterface          $request        A request object
  * @param \AppserverIo\Psr\HttpMessage\ResponseInterface         $response       A response object
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param integer                                                $hook           The current hook to process logic for
  *
  * @return boolean
  * @throws \AppserverIo\Server\Exceptions\ModuleException
  */
 public function process(RequestInterface $request, ResponseInterface $response, RequestContextInterface $requestContext, $hook)
 {
     // In php an interface is, by definition, a fixed contract. It is immutable.
     // So we have to declair the right ones afterwards...
     /**
      * @var $request \AppserverIo\Psr\HttpMessage\RequestInterface
      */
     /**
      * @var $response \AppserverIo\Psr\HttpMessage\ResponseInterface
      */
     // if false hook is comming do nothing
     if (ModuleHooks::REQUEST_POST !== $hook) {
         return;
     }
     // set req and res object internally
     $this->request = $request;
     $this->response = $response;
     // get default access definitions
     $accesses = $this->accesses;
     // check if there are some volatile access definitions so use them and override global accesses
     if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_ACCESSES)) {
         // reset by volatile accesses
         $accesses = $requestContext->getModuleVar(ModuleVars::VOLATILE_ACCESSES);
     }
     // generally everything is not allowed
     $allowed = false;
     if (isset($accesses['allow'])) {
         // check allow accesses information if something matches
         foreach ($accesses['allow'] as $accessData) {
             // we are optimistic an initial say data will match
             $matchAllow = true;
             // check if accessData matches server vars
             foreach ($accessData as $serverVar => $varPattern) {
                 // check if server var exists
                 if ($requestContext->hasServerVar($serverVar)) {
                     // check if pattern matches
                     if (!preg_match('/' . $varPattern . '/', $requestContext->getServerVar($serverVar))) {
                         $matchAllow = false;
                         // break here if anything not matches
                         break;
                     }
                 }
             }
             if ($matchAllow) {
                 // set allowed flag true
                 $allowed = true;
                 // break here cause' we found an allowed access
                 break;
             }
         }
     }
     if (isset($accesses['deny'])) {
         // check deny accesses information if something matches
         foreach ($accesses['deny'] as $accessData) {
             // initial nothing denies the request
             $matchDeny = false;
             // check if accessData matches server vars
             foreach ($accessData as $serverVar => $varPattern) {
                 // check if server var exists
                 if ($requestContext->hasServerVar($serverVar)) {
                     // check if pattern matches
                     if (preg_match('/' . $varPattern . '/', $requestContext->getServerVar($serverVar))) {
                         $matchDeny = true;
                         // break here if anything matches
                         break;
                     }
                 }
             }
             if ($matchDeny) {
                 // set allowed flag false
                 $allowed = false;
                 // break here cause' we found an allowed access
                 break;
             }
         }
     }
     // check if it's finally not allowed
     if (!$allowed) {
         throw new ModuleException('This request is forbidden', 403);
     }
 }
Example #13
0
 /**
  * Creates and returns a new FastCGI client instance.
  *
  * @param \AppserverIo\Server\Interfaces\RequestContextInterface $requestContext A requests context instance
  * @param \React\EventLoop\LoopInterface                         $loop           The event loop instance
  *
  * @return \Crunch\FastCGI\Connection The FastCGI connection instance
  */
 protected function getFastCgiClient(RequestContextInterface $requestContext, LoopInterface $loop)
 {
     // initialize default host/port/DNS server
     $host = FcgiModule::DEFAULT_FAST_CGI_IP;
     $port = FcgiModule::DEFAULT_FAST_CGI_PORT;
     $dnsServer = FcgiModule::DEFAULT_DNS_SERVER;
     // set the connection data to be used for the Fast-CGI connection
     $fileHandlerVariables = array();
     // check if we've configured module variables
     if ($requestContext->hasModuleVar(ModuleVars::VOLATILE_FILE_HANDLER_VARIABLES)) {
         // load the volatile file handler variables and set connection data
         $fileHandlerVariables = $requestContext->getModuleVar(ModuleVars::VOLATILE_FILE_HANDLER_VARIABLES);
         if (isset($fileHandlerVariables[FcgiModule::PARAM_HOST])) {
             $host = $fileHandlerVariables[FcgiModule::PARAM_HOST];
         }
         if (isset($fileHandlerVariables[FcgiModule::PARAM_PORT])) {
             $port = $fileHandlerVariables[FcgiModule::PARAM_PORT];
         }
         if (isset($fileHandlerVariables[FcgiModule::PARAM_DNS_SERVER])) {
             $dnsServer = $fileHandlerVariables[FcgiModule::PARAM_DNS_SERVER];
         }
     }
     // initialize the socket connector with the DNS resolver
     $dnsResolverFactory = new DnsResolverFactory();
     $dns = $dnsResolverFactory->createCached($dnsServer, $loop);
     // initialize the FastCGI factory with the connector
     $connector = new SocketConnector($loop, $dns);
     $factory = new FcgiClientFactory($loop, $connector);
     // initialize the FastCGI client with the FastCGI server IP and port
     return $factory->createClient($host, $port);
 }