File manager - Edit - /home/jardides/www/Jardi-design/images/administrator/AppFramework.tar
Back
Http.php 0000604 00000014215 15247165065 0006206 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Thomas Tanghus <thomas@tanghus.net> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework; use OCP\AppFramework\Http as BaseHttp; class Http extends BaseHttp { private $server; private $protocolVersion; protected $headers; /** * @param array $server $_SERVER * @param string $protocolVersion the http version to use defaults to HTTP/1.1 */ public function __construct($server, $protocolVersion='HTTP/1.1') { $this->server = $server; $this->protocolVersion = $protocolVersion; $this->headers = array( self::STATUS_CONTINUE => 'Continue', self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols', self::STATUS_PROCESSING => 'Processing', self::STATUS_OK => 'OK', self::STATUS_CREATED => 'Created', self::STATUS_ACCEPTED => 'Accepted', self::STATUS_NON_AUTHORATIVE_INFORMATION => 'Non-Authorative Information', self::STATUS_NO_CONTENT => 'No Content', self::STATUS_RESET_CONTENT => 'Reset Content', self::STATUS_PARTIAL_CONTENT => 'Partial Content', self::STATUS_MULTI_STATUS => 'Multi-Status', // RFC 4918 self::STATUS_ALREADY_REPORTED => 'Already Reported', // RFC 5842 self::STATUS_IM_USED => 'IM Used', // RFC 3229 self::STATUS_MULTIPLE_CHOICES => 'Multiple Choices', self::STATUS_MOVED_PERMANENTLY => 'Moved Permanently', self::STATUS_FOUND => 'Found', self::STATUS_SEE_OTHER => 'See Other', self::STATUS_NOT_MODIFIED => 'Not Modified', self::STATUS_USE_PROXY => 'Use Proxy', self::STATUS_RESERVED => 'Reserved', self::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect', self::STATUS_BAD_REQUEST => 'Bad request', self::STATUS_UNAUTHORIZED => 'Unauthorized', self::STATUS_PAYMENT_REQUIRED => 'Payment Required', self::STATUS_FORBIDDEN => 'Forbidden', self::STATUS_NOT_FOUND => 'Not Found', self::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed', self::STATUS_NOT_ACCEPTABLE => 'Not Acceptable', self::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required', self::STATUS_REQUEST_TIMEOUT => 'Request Timeout', self::STATUS_CONFLICT => 'Conflict', self::STATUS_GONE => 'Gone', self::STATUS_LENGTH_REQUIRED => 'Length Required', self::STATUS_PRECONDITION_FAILED => 'Precondition failed', self::STATUS_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large', self::STATUS_REQUEST_URI_TOO_LONG => 'Request-URI Too Long', self::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type', self::STATUS_REQUEST_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable', self::STATUS_EXPECTATION_FAILED => 'Expectation Failed', self::STATUS_IM_A_TEAPOT => 'I\'m a teapot', // RFC 2324 self::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', // RFC 4918 self::STATUS_LOCKED => 'Locked', // RFC 4918 self::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', // RFC 4918 self::STATUS_UPGRADE_REQUIRED => 'Upgrade required', self::STATUS_PRECONDITION_REQUIRED => 'Precondition required', // draft-nottingham-http-new-status self::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', // draft-nottingham-http-new-status self::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', // draft-nottingham-http-new-status self::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error', self::STATUS_NOT_IMPLEMENTED => 'Not Implemented', self::STATUS_BAD_GATEWAY => 'Bad Gateway', self::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable', self::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout', self::STATUS_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported', self::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates', self::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', // RFC 4918 self::STATUS_LOOP_DETECTED => 'Loop Detected', // RFC 5842 self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard self::STATUS_NOT_EXTENDED => 'Not extended', self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status ); } /** * Gets the correct header * @param Http::CONSTANT $status the constant from the Http class * @param \DateTime $lastModified formatted last modified date * @param string $ETag the etag * @return string */ public function getStatusHeader($status, \DateTime $lastModified=null, $ETag=null) { if(!is_null($lastModified)) { $lastModified = $lastModified->format(\DateTime::RFC2822); } // if etag or lastmodified have not changed, return a not modified if ((isset($this->server['HTTP_IF_NONE_MATCH']) && trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag) || (isset($this->server['HTTP_IF_MODIFIED_SINCE']) && trim($this->server['HTTP_IF_MODIFIED_SINCE']) === $lastModified)) { $status = self::STATUS_NOT_MODIFIED; } // we have one change currently for the http 1.0 header that differs // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND // if this differs any more, we want to create childclasses for this if($status === self::STATUS_TEMPORARY_REDIRECT && $this->protocolVersion === 'HTTP/1.0') { $status = self::STATUS_FOUND; } return $this->protocolVersion . ' ' . $status . ' ' . $this->headers[$status]; } } Http/Request.php 0000604 00000061134 15247165065 0007640 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bart Visscher <bartv@thisnet.nl> * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Lukas Reschke <lukas@statuscode.ch> * @author Mitar <mitar.git@tnode.com> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Thomas Tanghus <thomas@tanghus.net> * @author Vincent Petry <pvince81@owncloud.com> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Http; use OC\Security\CSRF\CsrfToken; use OC\Security\CSRF\CsrfTokenManager; use OC\Security\TrustedDomainHelper; use OCP\IConfig; use OCP\IRequest; use OCP\Security\ICrypto; use OCP\Security\ISecureRandom; /** * Class for accessing variables in the request. * This class provides an immutable object with request variables. * * @property mixed[] cookies * @property mixed[] env * @property mixed[] files * @property string method * @property mixed[] parameters * @property mixed[] server */ class Request implements \ArrayAccess, \Countable, IRequest { const USER_AGENT_IE = '/(MSIE)|(Trident)/'; // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge\/[0-9.]+$/'; // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/'; // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+$/'; // Safari User Agent from http://www.useragentstring.com/pages/Safari/ const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/'; // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#'; const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#'; const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/'; /** * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead */ const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/'; /** * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead */ const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/'; /** * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead */ const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/'; protected $inputStream; protected $content; protected $items = array(); protected $allowedKeys = array( 'get', 'post', 'files', 'server', 'env', 'cookies', 'urlParams', 'parameters', 'method', 'requesttoken', ); /** @var ISecureRandom */ protected $secureRandom; /** @var IConfig */ protected $config; /** @var string */ protected $requestId = ''; /** @var ICrypto */ protected $crypto; /** @var CsrfTokenManager|null */ protected $csrfTokenManager; /** @var bool */ protected $contentDecoded = false; /** * @param array $vars An associative array with the following optional values: * - array 'urlParams' the parameters which were matched from the URL * - array 'get' the $_GET array * - array|string 'post' the $_POST array or JSON string * - array 'files' the $_FILES array * - array 'server' the $_SERVER array * - array 'env' the $_ENV array * - array 'cookies' the $_COOKIE array * - string 'method' the request method (GET, POST etc) * - string|false 'requesttoken' the requesttoken or false when not available * @param ISecureRandom $secureRandom * @param IConfig $config * @param CsrfTokenManager|null $csrfTokenManager * @param string $stream * @see http://www.php.net/manual/en/reserved.variables.php */ public function __construct(array $vars=array(), ISecureRandom $secureRandom = null, IConfig $config, CsrfTokenManager $csrfTokenManager = null, $stream = 'php://input') { $this->inputStream = $stream; $this->items['params'] = array(); $this->secureRandom = $secureRandom; $this->config = $config; $this->csrfTokenManager = $csrfTokenManager; if(!array_key_exists('method', $vars)) { $vars['method'] = 'GET'; } foreach($this->allowedKeys as $name) { $this->items[$name] = isset($vars[$name]) ? $vars[$name] : array(); } $this->items['parameters'] = array_merge( $this->items['get'], $this->items['post'], $this->items['urlParams'], $this->items['params'] ); } /** * @param array $parameters */ public function setUrlParameters(array $parameters) { $this->items['urlParams'] = $parameters; $this->items['parameters'] = array_merge( $this->items['parameters'], $this->items['urlParams'] ); } /** * Countable method * @return int */ public function count() { return count(array_keys($this->items['parameters'])); } /** * ArrayAccess methods * * Gives access to the combined GET, POST and urlParams arrays * * Examples: * * $var = $request['myvar']; * * or * * if(!isset($request['myvar']) { * // Do something * } * * $request['myvar'] = 'something'; // This throws an exception. * * @param string $offset The key to lookup * @return boolean */ public function offsetExists($offset) { return isset($this->items['parameters'][$offset]); } /** * @see offsetExists */ public function offsetGet($offset) { return isset($this->items['parameters'][$offset]) ? $this->items['parameters'][$offset] : null; } /** * @see offsetExists */ public function offsetSet($offset, $value) { throw new \RuntimeException('You cannot change the contents of the request object'); } /** * @see offsetExists */ public function offsetUnset($offset) { throw new \RuntimeException('You cannot change the contents of the request object'); } /** * Magic property accessors * @param string $name * @param mixed $value */ public function __set($name, $value) { throw new \RuntimeException('You cannot change the contents of the request object'); } /** * Access request variables by method and name. * Examples: * * $request->post['myvar']; // Only look for POST variables * $request->myvar; or $request->{'myvar'}; or $request->{$myvar} * Looks in the combined GET, POST and urlParams array. * * If you access e.g. ->post but the current HTTP request method * is GET a \LogicException will be thrown. * * @param string $name The key to look for. * @throws \LogicException * @return mixed|null */ public function __get($name) { switch($name) { case 'put': case 'patch': case 'get': case 'post': if($this->method !== strtoupper($name)) { throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method)); } return $this->getContent(); case 'files': case 'server': case 'env': case 'cookies': case 'urlParams': case 'method': return isset($this->items[$name]) ? $this->items[$name] : null; case 'parameters': case 'params': return $this->getContent(); default; return isset($this[$name]) ? $this[$name] : null; } } /** * @param string $name * @return bool */ public function __isset($name) { if (in_array($name, $this->allowedKeys, true)) { return true; } return isset($this->items['parameters'][$name]); } /** * @param string $id */ public function __unset($id) { throw new \RuntimeException('You cannot change the contents of the request object'); } /** * Returns the value for a specific http header. * * This method returns null if the header did not exist. * * @param string $name * @return string */ public function getHeader($name) { $name = strtoupper(str_replace(array('-'),array('_'),$name)); if (isset($this->server['HTTP_' . $name])) { return $this->server['HTTP_' . $name]; } // There's a few headers that seem to end up in the top-level // server array. switch($name) { case 'CONTENT_TYPE' : case 'CONTENT_LENGTH' : if (isset($this->server[$name])) { return $this->server[$name]; } break; } return null; } /** * Lets you access post and get parameters by the index * In case of json requests the encoded json body is accessed * * @param string $key the key which you want to access in the URL Parameter * placeholder, $_POST or $_GET array. * The priority how they're returned is the following: * 1. URL parameters * 2. POST parameters * 3. GET parameters * @param mixed $default If the key is not found, this value will be returned * @return mixed the content of the array */ public function getParam($key, $default = null) { return isset($this->parameters[$key]) ? $this->parameters[$key] : $default; } /** * Returns all params that were received, be it from the request * (as GET or POST) or throuh the URL by the route * @return array the array with all parameters */ public function getParams() { return $this->parameters; } /** * Returns the method of the request * @return string the method of the request (POST, GET, etc) */ public function getMethod() { return $this->method; } /** * Shortcut for accessing an uploaded file through the $_FILES array * @param string $key the key that will be taken from the $_FILES array * @return array the file in the $_FILES element */ public function getUploadedFile($key) { return isset($this->files[$key]) ? $this->files[$key] : null; } /** * Shortcut for getting env variables * @param string $key the key that will be taken from the $_ENV array * @return array the value in the $_ENV element */ public function getEnv($key) { return isset($this->env[$key]) ? $this->env[$key] : null; } /** * Shortcut for getting cookie variables * @param string $key the key that will be taken from the $_COOKIE array * @return string the value in the $_COOKIE element */ public function getCookie($key) { return isset($this->cookies[$key]) ? $this->cookies[$key] : null; } /** * Returns the request body content. * * If the HTTP request method is PUT and the body * not application/x-www-form-urlencoded or application/json a stream * resource is returned, otherwise an array. * * @return array|string|resource The request body content or a resource to read the body stream. * * @throws \LogicException */ protected function getContent() { // If the content can't be parsed into an array then return a stream resource. if ($this->method === 'PUT' && $this->getHeader('Content-Length') !== 0 && $this->getHeader('Content-Length') !== null && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false && strpos($this->getHeader('Content-Type'), 'application/json') === false ) { if ($this->content === false) { throw new \LogicException( '"put" can only be accessed once if not ' . 'application/x-www-form-urlencoded or application/json.' ); } $this->content = false; return fopen($this->inputStream, 'rb'); } else { $this->decodeContent(); return $this->items['parameters']; } } /** * Attempt to decode the content and populate parameters */ protected function decodeContent() { if ($this->contentDecoded) { return; } $params = []; // 'application/json' must be decoded manually. if (strpos($this->getHeader('Content-Type'), 'application/json') !== false) { $params = json_decode(file_get_contents($this->inputStream), true); if(count($params) > 0) { $this->items['params'] = $params; if($this->method === 'POST') { $this->items['post'] = $params; } } // Handle application/x-www-form-urlencoded for methods other than GET // or post correctly } elseif($this->method !== 'GET' && $this->method !== 'POST' && strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) { parse_str(file_get_contents($this->inputStream), $params); if(is_array($params)) { $this->items['params'] = $params; } } if (is_array($params)) { $this->items['parameters'] = array_merge($this->items['parameters'], $params); } $this->contentDecoded = true; } /** * Checks if the CSRF check was correct * @return bool true if CSRF check passed */ public function passesCSRFCheck() { if($this->csrfTokenManager === null) { return false; } if(!$this->passesStrictCookieCheck()) { return false; } if (isset($this->items['get']['requesttoken'])) { $token = $this->items['get']['requesttoken']; } elseif (isset($this->items['post']['requesttoken'])) { $token = $this->items['post']['requesttoken']; } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) { $token = $this->items['server']['HTTP_REQUESTTOKEN']; } else { //no token found. return false; } $token = new CsrfToken($token); return $this->csrfTokenManager->isTokenValid($token); } /** * Whether the cookie checks are required * * @return bool */ private function cookieCheckRequired() { if ($this->getHeader('OCS-APIREQUEST')) { return false; } if($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) { return false; } return true; } /** * Wrapper around session_get_cookie_params * * @return array */ protected function getCookieParams() { return session_get_cookie_params(); } /** * Appends the __Host- prefix to the cookie if applicable * * @param string $name * @return string */ protected function getProtectedCookieName($name) { $cookieParams = $this->getCookieParams(); $prefix = ''; if($cookieParams['secure'] === true && $cookieParams['path'] === '/') { $prefix = '__Host-'; } return $prefix.$name; } /** * Checks if the strict cookie has been sent with the request if the request * is including any cookies. * * @return bool * @since 9.1.0 */ public function passesStrictCookieCheck() { if(!$this->cookieCheckRequired()) { return true; } $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict'); if($this->getCookie($cookieName) === 'true' && $this->passesLaxCookieCheck()) { return true; } return false; } /** * Checks if the lax cookie has been sent with the request if the request * is including any cookies. * * @return bool * @since 9.1.0 */ public function passesLaxCookieCheck() { if(!$this->cookieCheckRequired()) { return true; } $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax'); if($this->getCookie($cookieName) === 'true') { return true; } return false; } /** * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging * If `mod_unique_id` is installed this value will be taken. * @return string */ public function getId() { if(isset($this->server['UNIQUE_ID'])) { return $this->server['UNIQUE_ID']; } if(empty($this->requestId)) { $validChars = ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_DIGITS; $this->requestId = $this->secureRandom->generate(20, $validChars); } return $this->requestId; } /** * Returns the remote address, if the connection came from a trusted proxy * and `forwarded_for_headers` has been configured then the IP address * specified in this header will be returned instead. * Do always use this instead of $_SERVER['REMOTE_ADDR'] * @return string IP address */ public function getRemoteAddress() { $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : ''; $trustedProxies = $this->config->getSystemValue('trusted_proxies', []); if(is_array($trustedProxies) && in_array($remoteAddress, $trustedProxies)) { $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [ 'HTTP_X_FORWARDED_FOR' // only have one default, so we cannot ship an insecure product out of the box ]); foreach($forwardedForHeaders as $header) { if(isset($this->server[$header])) { foreach(explode(',', $this->server[$header]) as $IP) { $IP = trim($IP); if (filter_var($IP, FILTER_VALIDATE_IP) !== false) { return $IP; } } } } } return $remoteAddress; } /** * Check overwrite condition * @param string $type * @return bool */ private function isOverwriteCondition($type = '') { $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '') . '/'; $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : ''; return $regex === '//' || preg_match($regex, $remoteAddr) === 1 || $type !== 'protocol'; } /** * Returns the server protocol. It respects one or more reverse proxies servers * and load balancers * @return string Server protocol (http or https) */ public function getServerProtocol() { if($this->config->getSystemValue('overwriteprotocol') !== '' && $this->isOverwriteCondition('protocol')) { return $this->config->getSystemValue('overwriteprotocol'); } if (isset($this->server['HTTP_X_FORWARDED_PROTO'])) { if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) { $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']); $proto = strtolower(trim($parts[0])); } else { $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']); } // Verify that the protocol is always HTTP or HTTPS // default to http if an invalid value is provided return $proto === 'https' ? 'https' : 'http'; } if (isset($this->server['HTTPS']) && $this->server['HTTPS'] !== null && $this->server['HTTPS'] !== 'off' && $this->server['HTTPS'] !== '') { return 'https'; } return 'http'; } /** * Returns the used HTTP protocol. * * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0. */ public function getHttpProtocol() { $claimedProtocol = strtoupper($this->server['SERVER_PROTOCOL']); $validProtocols = [ 'HTTP/1.0', 'HTTP/1.1', 'HTTP/2', ]; if(in_array($claimedProtocol, $validProtocols, true)) { return $claimedProtocol; } return 'HTTP/1.1'; } /** * Returns the request uri, even if the website uses one or more * reverse proxies * @return string */ public function getRequestUri() { $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : ''; if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) { $uri = $this->getScriptName() . substr($uri, strlen($this->server['SCRIPT_NAME'])); } return $uri; } /** * Get raw PathInfo from request (not urldecoded) * @throws \Exception * @return string Path info */ public function getRawPathInfo() { $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : ''; // remove too many leading slashes - can be caused by reverse proxy configuration if (strpos($requestUri, '/') === 0) { $requestUri = '/' . ltrim($requestUri, '/'); } $requestUri = preg_replace('%/{2,}%', '/', $requestUri); // Remove the query string from REQUEST_URI if ($pos = strpos($requestUri, '?')) { $requestUri = substr($requestUri, 0, $pos); } $scriptName = $this->server['SCRIPT_NAME']; $pathInfo = $requestUri; // strip off the script name's dir and file name // FIXME: Sabre does not really belong here list($path, $name) = \Sabre\HTTP\URLUtil::splitPath($scriptName); if (!empty($path)) { if($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) { $pathInfo = substr($pathInfo, strlen($path)); } else { throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')"); } } if (strpos($pathInfo, '/'.$name) === 0) { $pathInfo = substr($pathInfo, strlen($name) + 1); } if (strpos($pathInfo, $name) === 0) { $pathInfo = substr($pathInfo, strlen($name)); } if($pathInfo === false || $pathInfo === '/'){ return ''; } else { return $pathInfo; } } /** * Get PathInfo from request * @throws \Exception * @return string|false Path info or false when not found */ public function getPathInfo() { $pathInfo = $this->getRawPathInfo(); // following is taken from \Sabre\HTTP\URLUtil::decodePathSegment $pathInfo = rawurldecode($pathInfo); $encoding = mb_detect_encoding($pathInfo, ['UTF-8', 'ISO-8859-1']); switch($encoding) { case 'ISO-8859-1' : $pathInfo = utf8_encode($pathInfo); } // end copy return $pathInfo; } /** * Returns the script name, even if the website uses one or more * reverse proxies * @return string the script name */ public function getScriptName() { $name = $this->server['SCRIPT_NAME']; $overwriteWebRoot = $this->config->getSystemValue('overwritewebroot'); if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) { // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -strlen('lib/private/appframework/http/'))); $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), strlen($serverRoot))); $name = '/' . ltrim($overwriteWebRoot . $suburi, '/'); } return $name; } /** * Checks whether the user agent matches a given regex * @param array $agent array of agent names * @return bool true if at least one of the given agent matches, false otherwise */ public function isUserAgent(array $agent) { if (!isset($this->server['HTTP_USER_AGENT'])) { return false; } foreach ($agent as $regex) { if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) { return true; } } return false; } /** * Returns the unverified server host from the headers without checking * whether it is a trusted domain * @return string Server host */ public function getInsecureServerHost() { $host = 'localhost'; if (isset($this->server['HTTP_X_FORWARDED_HOST'])) { if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) { $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']); $host = trim(current($parts)); } else { $host = $this->server['HTTP_X_FORWARDED_HOST']; } } else { if (isset($this->server['HTTP_HOST'])) { $host = $this->server['HTTP_HOST']; } else if (isset($this->server['SERVER_NAME'])) { $host = $this->server['SERVER_NAME']; } } return $host; } /** * Returns the server host from the headers, or the first configured * trusted domain if the host isn't in the trusted list * @return string Server host */ public function getServerHost() { // overwritehost is always trusted $host = $this->getOverwriteHost(); if ($host !== null) { return $host; } // get the host from the headers $host = $this->getInsecureServerHost(); // Verify that the host is a trusted domain if the trusted domains // are defined // If no trusted domain is provided the first trusted domain is returned $trustedDomainHelper = new TrustedDomainHelper($this->config); if ($trustedDomainHelper->isTrustedDomain($host)) { return $host; } else { $trustedList = $this->config->getSystemValue('trusted_domains', []); if(!empty($trustedList)) { return $trustedList[0]; } else { return ''; } } } /** * Returns the overwritehost setting from the config if set and * if the overwrite condition is met * @return string|null overwritehost value or null if not defined or the defined condition * isn't met */ private function getOverwriteHost() { if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) { return $this->config->getSystemValue('overwritehost'); } return null; } } Http/Output.php 0000604 00000004412 15247165065 0007504 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Stefan Weil <sw@weilnetz.de> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Http; use OCP\AppFramework\Http\IOutput; /** * Very thin wrapper class to make output testable */ class Output implements IOutput { /** @var string */ private $webRoot; /** * @param $webRoot */ public function __construct($webRoot) { $this->webRoot = $webRoot; } /** * @param string $out */ public function setOutput($out) { print($out); } /** * @param string|resource $path or file handle * * @return bool false if an error occurred */ public function setReadfile($path) { if (is_resource($path)) { $output = fopen('php://output', 'w'); return stream_copy_to_stream($path, $output) > 0; } else { return @readfile($path); } } /** * @param string $header */ public function setHeader($header) { header($header); } /** * @param int $code sets the http status code */ public function setHttpResponseCode($code) { http_response_code($code); } /** * @return int returns the current http response code */ public function getHttpResponseCode() { return http_response_code(); } /** * @param string $name * @param string $value * @param int $expire * @param string $path * @param string $domain * @param bool $secure * @param bool $httpOnly */ public function setCookie($name, $value, $expire, $path, $domain, $secure, $httpOnly) { $path = $this->webRoot ? : '/'; setcookie($name, $value, $expire, $path, $domain, $secure, $httpOnly); } } Http/Dispatcher.php 0000604 00000013413 15247165065 0010273 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Georg Ehrke <georg@owncloud.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Thomas Tanghus <thomas@tanghus.net> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Http; use \OC\AppFramework\Middleware\MiddlewareDispatcher; use \OC\AppFramework\Http; use \OC\AppFramework\Utility\ControllerMethodReflector; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Http\DataResponse; use OCP\IRequest; /** * Class to dispatch the request to the middleware dispatcher */ class Dispatcher { private $middlewareDispatcher; private $protocol; private $reflector; private $request; /** * @param Http $protocol the http protocol with contains all status headers * @param MiddlewareDispatcher $middlewareDispatcher the dispatcher which * runs the middleware * @param ControllerMethodReflector $reflector the reflector that is used to inject * the arguments for the controller * @param IRequest $request the incoming request */ public function __construct(Http $protocol, MiddlewareDispatcher $middlewareDispatcher, ControllerMethodReflector $reflector, IRequest $request) { $this->protocol = $protocol; $this->middlewareDispatcher = $middlewareDispatcher; $this->reflector = $reflector; $this->request = $request; } /** * Handles a request and calls the dispatcher on the controller * @param Controller $controller the controller which will be called * @param string $methodName the method name which will be called on * the controller * @return array $array[0] contains a string with the http main header, * $array[1] contains headers in the form: $key => value, $array[2] contains * the response output * @throws \Exception */ public function dispatch(Controller $controller, $methodName) { $out = array(null, array(), null); try { // prefill reflector with everything thats needed for the // middlewares $this->reflector->reflect($controller, $methodName); $this->middlewareDispatcher->beforeController($controller, $methodName); $response = $this->executeController($controller, $methodName); // if an exception appears, the middleware checks if it can handle the // exception and creates a response. If no response is created, it is // assumed that theres no middleware who can handle it and the error is // thrown again } catch(\Exception $exception){ $response = $this->middlewareDispatcher->afterException( $controller, $methodName, $exception); if (is_null($response)) { throw $exception; } } $response = $this->middlewareDispatcher->afterController( $controller, $methodName, $response); // depending on the cache object the headers need to be changed $out[0] = $this->protocol->getStatusHeader($response->getStatus(), $response->getLastModified(), $response->getETag()); $out[1] = array_merge($response->getHeaders()); $out[2] = $response->getCookies(); $out[3] = $this->middlewareDispatcher->beforeOutput( $controller, $methodName, $response->render() ); $out[4] = $response; return $out; } /** * Uses the reflected parameters, types and request parameters to execute * the controller * @param Controller $controller the controller to be executed * @param string $methodName the method on the controller that should be executed * @return Response */ private function executeController($controller, $methodName) { $arguments = array(); // valid types that will be casted $types = array('int', 'integer', 'bool', 'boolean', 'float'); foreach($this->reflector->getParameters() as $param => $default) { // try to get the parameter from the request object and cast // it to the type annotated in the @param annotation $value = $this->request->getParam($param, $default); $type = $this->reflector->getType($param); // if this is submitted using GET or a POST form, 'false' should be // converted to false if(($type === 'bool' || $type === 'boolean') && $value === 'false' && ( $this->request->method === 'GET' || strpos($this->request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false ) ) { $value = false; } elseif($value !== null && in_array($type, $types)) { settype($value, $type); } $arguments[] = $value; } $response = call_user_func_array(array($controller, $methodName), $arguments); // format response if($response instanceof DataResponse || !($response instanceof Response)) { // get format from the url format or request format parameter $format = $this->request->getParam('format'); // if none is given try the first Accept header if($format === null) { $headers = $this->request->getHeader('Accept'); $format = $controller->getResponderByHTTPHeader($headers, null); } if ($format !== null) { $response = $controller->buildResponse($response, $format); } else { $response = $controller->buildResponse($response); } } return $response; } } Utility/SimpleContainer.php 0000604 00000012042 15247165065 0012022 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Joas Schilling <coding@schilljs.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Utility; use ReflectionClass; use ReflectionException; use Closure; use Pimple\Container; use OCP\AppFramework\QueryException; use OCP\IContainer; /** * Class SimpleContainer * * SimpleContainer is a simple implementation of IContainer on basis of Pimple */ class SimpleContainer extends Container implements IContainer { /** * @param ReflectionClass $class the class to instantiate * @return \stdClass the created class */ private function buildClass(ReflectionClass $class) { $constructor = $class->getConstructor(); if ($constructor === null) { return $class->newInstance(); } else { $parameters = []; foreach ($constructor->getParameters() as $parameter) { $parameterClass = $parameter->getClass(); // try to find out if it is a class or a simple parameter if ($parameterClass === null) { $resolveName = $parameter->getName(); } else { $resolveName = $parameterClass->name; } try { $parameters[] = $this->query($resolveName); } catch (\Exception $e) { // Service not found, use the default value when available if ($parameter->isDefaultValueAvailable()) { $parameters[] = $parameter->getDefaultValue(); } else if ($parameterClass !== null) { $resolveName = $parameter->getName(); $parameters[] = $this->query($resolveName); } else { throw $e; } } } return $class->newInstanceArgs($parameters); } } /** * If a parameter is not registered in the container try to instantiate it * by using reflection to find out how to build the class * @param string $name the class name to resolve * @return \stdClass * @throws QueryException if the class could not be found or instantiated */ public function resolve($name) { $baseMsg = 'Could not resolve ' . $name . '!'; try { $class = new ReflectionClass($name); if ($class->isInstantiable()) { return $this->buildClass($class); } else { throw new QueryException($baseMsg . ' Class can not be instantiated'); } } catch(ReflectionException $e) { throw new QueryException($baseMsg . ' ' . $e->getMessage()); } } /** * @param string $name name of the service to query for * @return mixed registered service for the given $name * @throws QueryException if the query could not be resolved */ public function query($name) { $name = $this->sanitizeName($name); if ($this->offsetExists($name)) { return $this->offsetGet($name); } else { $object = $this->resolve($name); $this->registerService($name, function () use ($object) { return $object; }); return $object; } } /** * @param string $name * @param mixed $value */ public function registerParameter($name, $value) { $this[$name] = $value; } /** * The given closure is call the first time the given service is queried. * The closure has to return the instance for the given service. * Created instance will be cached in case $shared is true. * * @param string $name name of the service to register another backend for * @param Closure $closure the closure to be called on service creation * @param bool $shared */ public function registerService($name, Closure $closure, $shared = true) { $name = $this->sanitizeName($name); if (isset($this[$name])) { unset($this[$name]); } if ($shared) { $this[$name] = $closure; } else { $this[$name] = parent::factory($closure); } } /** * Shortcut for returning a service from a service under a different key, * e.g. to tell the container to return a class when queried for an * interface * @param string $alias the alias that should be registered * @param string $target the target that should be resolved instead */ public function registerAlias($alias, $target) { $this->registerService($alias, function (IContainer $container) use ($target) { return $container->query($target); }, false); } /* * @param string $name * @return string */ protected function sanitizeName($name) { if (isset($name[0]) && $name[0] === '\\') { return ltrim($name, '\\'); } return $name; } } Utility/TimeFactory.php 0000604 00000002163 15247165065 0011157 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Morris Jobke <hey@morrisjobke.de> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Utility; use OCP\AppFramework\Utility\ITimeFactory; /** * Needed to mock calls to time() */ class TimeFactory implements ITimeFactory { /** * @return int the result of a call to time() */ public function getTime() { return time(); } } Utility/ControllerMethodReflector.php 0000604 00000010105 15247165065 0014056 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Morris Jobke <hey@morrisjobke.de> * @author Olivier Paroz <github@oparoz.com> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Utility; use \OCP\AppFramework\Utility\IControllerMethodReflector; /** * Reads and parses annotations from doc comments */ class ControllerMethodReflector implements IControllerMethodReflector { public $annotations = []; private $types = []; private $parameters = []; /** * @param object $object an object or classname * @param string $method the method which we want to inspect */ public function reflect($object, $method){ $reflection = new \ReflectionMethod($object, $method); $docs = $reflection->getDocComment(); // extract everything prefixed by @ and first letter uppercase preg_match_all('/^\h+\*\h+@(?P<annotation>[A-Z]\w+)((?P<parameter>.*))?$/m', $docs, $matches); foreach($matches['annotation'] as $key => $annontation) { $annotationValue = $matches['parameter'][$key]; if(isset($annotationValue[0]) && $annotationValue[0] === '(' && $annotationValue[strlen($annotationValue) - 1] === ')') { $cutString = substr($annotationValue, 1, -1); $cutString = str_replace(' ', '', $cutString); $splittedArray = explode(',', $cutString); foreach($splittedArray as $annotationValues) { list($key, $value) = explode('=', $annotationValues); $this->annotations[$annontation][$key] = $value; } continue; } $this->annotations[$annontation] = [$annotationValue]; } // extract type parameter information preg_match_all('/@param\h+(?P<type>\w+)\h+\$(?P<var>\w+)/', $docs, $matches); $this->types = array_combine($matches['var'], $matches['type']); foreach ($reflection->getParameters() as $param) { // extract type information from PHP 7 scalar types and prefer them // over phpdoc annotations if (method_exists($param, 'getType')) { $type = $param->getType(); if ($type !== null) { $this->types[$param->getName()] = (string) $type; } } if($param->isOptional()) { $default = $param->getDefaultValue(); } else { $default = null; } $this->parameters[$param->name] = $default; } } /** * Inspects the PHPDoc parameters for types * @param string $parameter the parameter whose type comments should be * parsed * @return string|null type in the type parameters (@param int $something) * would return int or null if not existing */ public function getType($parameter) { if(array_key_exists($parameter, $this->types)) { return $this->types[$parameter]; } else { return null; } } /** * @return array the arguments of the method with key => default value */ public function getParameters() { return $this->parameters; } /** * Check if a method contains an annotation * @param string $name the name of the annotation * @return bool true if the annotation is found */ public function hasAnnotation($name) { return array_key_exists($name, $this->annotations); } /** * Get optional annotation parameter by key * * @param string $name the name of the annotation * @param string $key the string of the annotation * @return string */ public function getAnnotationParameter($name, $key) { if(isset($this->annotations[$name][$key])) { return $this->annotations[$name][$key]; } return ''; } } App.php 0000604 00000013745 15247165065 0006016 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Andreas Fischer <bantu@owncloud.com> * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework; use OC\AppFramework\Http\Dispatcher; use OC\AppFramework\DependencyInjection\DIContainer; use OCP\AppFramework\Http; use OCP\AppFramework\QueryException; use OCP\AppFramework\Http\ICallbackResponse; /** * Entry point for every request in your app. You can consider this as your * public static void main() method * * Handles all the dependency injection, controllers and output flow */ class App { /** @var string[] */ private static $nameSpaceCache = []; /** * Turns an app id into a namespace by either reading the appinfo.xml's * namespace tag or uppercasing the appid's first letter * @param string $appId the app id * @param string $topNamespace the namespace which should be prepended to * the transformed app id, defaults to OCA\ * @return string the starting namespace for the app */ public static function buildAppNamespace($appId, $topNamespace='OCA\\') { // Hit the cache! if (isset(self::$nameSpaceCache[$appId])) { return $topNamespace . self::$nameSpaceCache[$appId]; } $appInfo = \OC_App::getAppInfo($appId); if (isset($appInfo['namespace'])) { self::$nameSpaceCache[$appId] = trim($appInfo['namespace']); } else { // if the tag is not found, fall back to uppercasing the first letter self::$nameSpaceCache[$appId] = ucfirst($appId); } return $topNamespace . self::$nameSpaceCache[$appId]; } /** * Shortcut for calling a controller method and printing the result * @param string $controllerName the name of the controller under which it is * stored in the DI container * @param string $methodName the method that you want to call * @param DIContainer $container an instance of a pimple container. * @param array $urlParams list of URL parameters (optional) */ public static function main($controllerName, $methodName, DIContainer $container, array $urlParams = null) { if (!is_null($urlParams)) { $container['OCP\\IRequest']->setUrlParameters($urlParams); } else if (isset($container['urlParams']) && !is_null($container['urlParams'])) { $container['OCP\\IRequest']->setUrlParameters($container['urlParams']); } $appName = $container['AppName']; // first try $controllerName then go for \OCA\AppName\Controller\$controllerName try { $controller = $container->query($controllerName); } catch(QueryException $e) { if ($appName === 'core') { $appNameSpace = 'OC\\Core'; } else if ($appName === 'settings') { $appNameSpace = 'OC\\Settings'; } else { $appNameSpace = self::buildAppNamespace($appName); } $controllerName = $appNameSpace . '\\Controller\\' . $controllerName; $controller = $container->query($controllerName); } // initialize the dispatcher and run all the middleware before the controller /** @var Dispatcher $dispatcher */ $dispatcher = $container['Dispatcher']; list( $httpHeaders, $responseHeaders, $responseCookies, $output, $response ) = $dispatcher->dispatch($controller, $methodName); $io = $container['OCP\\AppFramework\\Http\\IOutput']; if(!is_null($httpHeaders)) { $io->setHeader($httpHeaders); } foreach($responseHeaders as $name => $value) { $io->setHeader($name . ': ' . $value); } foreach($responseCookies as $name => $value) { $expireDate = null; if($value['expireDate'] instanceof \DateTime) { $expireDate = $value['expireDate']->getTimestamp(); } $io->setCookie( $name, $value['value'], $expireDate, $container->getServer()->getWebRoot(), null, $container->getServer()->getRequest()->getServerProtocol() === 'https', true ); } /* * Status 204 does not have a body and no Content Length * Status 304 does not have a body and does not need a Content Length * https://tools.ietf.org/html/rfc7230#section-3.3 * https://tools.ietf.org/html/rfc7230#section-3.3.2 */ if ($httpHeaders !== Http::STATUS_NO_CONTENT && $httpHeaders !== Http::STATUS_NOT_MODIFIED) { if ($response instanceof ICallbackResponse) { $response->callback($io); } else if (!is_null($output)) { $io->setHeader('Content-Length: ' . strlen($output)); $io->setOutput($output); } } } /** * Shortcut for calling a controller method and printing the result. * Similar to App:main except that no headers will be sent. * This should be used for example when registering sections via * \OC\AppFramework\Core\API::registerAdmin() * * @param string $controllerName the name of the controller under which it is * stored in the DI container * @param string $methodName the method that you want to call * @param array $urlParams an array with variables extracted from the routes * @param DIContainer $container an instance of a pimple container. */ public static function part($controllerName, $methodName, array $urlParams, DIContainer $container){ $container['urlParams'] = $urlParams; $controller = $container[$controllerName]; $dispatcher = $container['Dispatcher']; list(, , $output) = $dispatcher->dispatch($controller, $methodName); return $output; } } Routing/RouteConfig.php 0000604 00000017642 15247165065 0011151 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Morris Jobke <hey@morrisjobke.de> * @author Patrick Paysant <ppaysant@linagora.com> * @author Robin Appelman <robin@icewind.nl> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Routing; use OC\AppFramework\DependencyInjection\DIContainer; use OCP\Route\IRouter; /** * Class RouteConfig * @package OC\AppFramework\routing */ class RouteConfig { /** @var DIContainer */ private $container; /** @var IRouter */ private $router; /** @var array */ private $routes; /** @var string */ private $appName; /** @var string[] */ private $controllerNameCache = []; /** * @param \OC\AppFramework\DependencyInjection\DIContainer $container * @param \OCP\Route\IRouter $router * @param array $routes * @internal param $appName */ public function __construct(DIContainer $container, IRouter $router, $routes) { $this->routes = $routes; $this->container = $container; $this->router = $router; $this->appName = $container['AppName']; } /** * The routes and resource will be registered to the \OCP\Route\IRouter */ public function register() { // parse simple $this->processSimpleRoutes($this->routes); // parse resources $this->processResources($this->routes); /* * OCS routes go into a different collection */ $oldCollection = $this->router->getCurrentCollection(); $this->router->useCollection($oldCollection.'.ocs'); // parse ocs simple routes $this->processOCS($this->routes); $this->router->useCollection($oldCollection); } private function processOCS(array $routes) { $ocsRoutes = isset($routes['ocs']) ? $routes['ocs'] : []; foreach ($ocsRoutes as $ocsRoute) { $name = $ocsRoute['name']; $postfix = ''; if (isset($ocsRoute['postfix'])) { $postfix = $ocsRoute['postfix']; } if (isset($ocsRoute['root'])) { $root = $ocsRoute['root']; } else { $root = '/apps/'.$this->appName; } $url = $root . $ocsRoute['url']; $verb = isset($ocsRoute['verb']) ? strtoupper($ocsRoute['verb']) : 'GET'; $split = explode('#', $name, 2); if (count($split) != 2) { throw new \UnexpectedValueException('Invalid route name'); } $controller = $split[0]; $action = $split[1]; $controllerName = $this->buildControllerName($controller); $actionName = $this->buildActionName($action); // register the route $handler = new RouteActionHandler($this->container, $controllerName, $actionName); $router = $this->router->create('ocs.'.$this->appName.'.'.$controller.'.'.$action . $postfix, $url) ->method($verb) ->action($handler); // optionally register requirements for route. This is used to // tell the route parser how url parameters should be matched if(array_key_exists('requirements', $ocsRoute)) { $router->requirements($ocsRoute['requirements']); } // optionally register defaults for route. This is used to // tell the route parser how url parameters should be default valued if(array_key_exists('defaults', $ocsRoute)) { $router->defaults($ocsRoute['defaults']); } } } /** * Creates one route base on the give configuration * @param array $routes * @throws \UnexpectedValueException */ private function processSimpleRoutes($routes) { $simpleRoutes = isset($routes['routes']) ? $routes['routes'] : array(); foreach ($simpleRoutes as $simpleRoute) { $name = $simpleRoute['name']; $postfix = ''; if (isset($simpleRoute['postfix'])) { $postfix = $simpleRoute['postfix']; } $url = $simpleRoute['url']; $verb = isset($simpleRoute['verb']) ? strtoupper($simpleRoute['verb']) : 'GET'; $split = explode('#', $name, 2); if (count($split) != 2) { throw new \UnexpectedValueException('Invalid route name'); } $controller = $split[0]; $action = $split[1]; $controllerName = $this->buildControllerName($controller); $actionName = $this->buildActionName($action); // register the route $handler = new RouteActionHandler($this->container, $controllerName, $actionName); $router = $this->router->create($this->appName.'.'.$controller.'.'.$action . $postfix, $url) ->method($verb) ->action($handler); // optionally register requirements for route. This is used to // tell the route parser how url parameters should be matched if(array_key_exists('requirements', $simpleRoute)) { $router->requirements($simpleRoute['requirements']); } // optionally register defaults for route. This is used to // tell the route parser how url parameters should be default valued if(array_key_exists('defaults', $simpleRoute)) { $router->defaults($simpleRoute['defaults']); } } } /** * For a given name and url restful routes are created: * - index * - show * - new * - create * - update * - destroy * * @param array $routes */ private function processResources($routes) { // declaration of all restful actions $actions = array( array('name' => 'index', 'verb' => 'GET', 'on-collection' => true), array('name' => 'show', 'verb' => 'GET'), array('name' => 'create', 'verb' => 'POST', 'on-collection' => true), array('name' => 'update', 'verb' => 'PUT'), array('name' => 'destroy', 'verb' => 'DELETE'), ); $resources = isset($routes['resources']) ? $routes['resources'] : array(); foreach ($resources as $resource => $config) { // the url parameter used as id to the resource foreach($actions as $action) { $url = $config['url']; $method = $action['name']; $verb = isset($action['verb']) ? strtoupper($action['verb']) : 'GET'; $collectionAction = isset($action['on-collection']) ? $action['on-collection'] : false; if (!$collectionAction) { $url = $url . '/{id}'; } if (isset($action['url-postfix'])) { $url = $url . '/' . $action['url-postfix']; } $controller = $resource; $controllerName = $this->buildControllerName($controller); $actionName = $this->buildActionName($method); $routeName = $this->appName . '.' . strtolower($resource) . '.' . strtolower($method); $this->router->create($routeName, $url)->method($verb)->action( new RouteActionHandler($this->container, $controllerName, $actionName) ); } } } /** * Based on a given route name the controller name is generated * @param string $controller * @return string */ private function buildControllerName($controller) { if (!isset($this->controllerNameCache[$controller])) { $this->controllerNameCache[$controller] = $this->underScoreToCamelCase(ucfirst($controller)) . 'Controller'; } return $this->controllerNameCache[$controller]; } /** * Based on the action part of the route name the controller method name is generated * @param string $action * @return string */ private function buildActionName($action) { return $this->underScoreToCamelCase($action); } /** * Underscored strings are converted to camel case strings * @param string $str * @return string */ private function underScoreToCamelCase($str) { $pattern = "/_[a-z]?/"; return preg_replace_callback( $pattern, function ($matches) { return strtoupper(ltrim($matches[0], "_")); }, $str); } } Routing/RouteActionHandler.php 0000604 00000002757 15247165065 0012460 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Routing; use \OC\AppFramework\App; use \OC\AppFramework\DependencyInjection\DIContainer; class RouteActionHandler { private $controllerName; private $actionName; private $container; /** * @param string $controllerName * @param string $actionName */ public function __construct(DIContainer $container, $controllerName, $actionName) { $this->controllerName = $controllerName; $this->actionName = $actionName; $this->container = $container; } public function __invoke($params) { App::main($this->controllerName, $this->actionName, $this->container, $params); } } OCS/V1Response.php 0000604 00000004061 15247165065 0007716 0 ustar 00 <?php /** * @copyright 2016 Roeland Jago Douma <roeland@famdouma.nl> * * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\AppFramework\OCS; use OCP\API; use OCP\AppFramework\Http; class V1Response extends BaseResponse { /** * The V1 endpoint has very limited http status codes basically everything * is status 200 except 401 * * @return int */ public function getStatus() { $status = parent::getStatus(); if ($status === Http::STATUS_FORBIDDEN || $status === API::RESPOND_UNAUTHORISED) { return Http::STATUS_UNAUTHORIZED; } return Http::STATUS_OK; } /** * In v1 all OK is 100 * * @return int */ public function getOCSStatus() { $status = parent::getOCSStatus(); if ($status === Http::STATUS_OK) { return 100; } return $status; } /** * Construct the meta part of the response * And then late the base class render * * @return string */ public function render() { $meta = [ 'status' => $this->getOCSStatus() === 100 ? 'ok' : 'failure', 'statuscode' => $this->getOCSStatus(), 'message' => $this->getOCSStatus() === 100 ? 'OK' : $this->statusMessage, ]; $meta['totalitems'] = $this->itemsCount !== null ? (string)$this->itemsCount : ''; $meta['itemsperpage'] = $this->itemsPerPage !== null ? (string)$this->itemsPerPage: ''; return $this->renderResult($meta); } } OCS/BaseResponse.php 0000604 00000005135 15247165065 0010305 0 ustar 00 <?php /** * @copyright 2016 Roeland Jago Douma <roeland@famdouma.nl> * * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\AppFramework\OCS; use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\Http\EmptyContentSecurityPolicy; use OCP\AppFramework\Http\Response; abstract class BaseResponse extends Response { /** @var array */ protected $data; /** @var string */ protected $format; /** @var string */ protected $statusMessage; /** @var int */ protected $itemsCount; /** @var int */ protected $itemsPerPage; /** * BaseResponse constructor. * * @param DataResponse|null $dataResponse * @param string $format * @param string|null $statusMessage * @param int|null $itemsCount * @param int|null $itemsPerPage */ public function __construct(DataResponse $dataResponse, $format = 'xml', $statusMessage = null, $itemsCount = null, $itemsPerPage = null) { $this->format = $format; $this->statusMessage = $statusMessage; $this->itemsCount = $itemsCount; $this->itemsPerPage = $itemsPerPage; $this->data = $dataResponse->getData(); $this->setHeaders($dataResponse->getHeaders()); $this->setStatus($dataResponse->getStatus()); $this->setETag($dataResponse->getETag()); $this->setLastModified($dataResponse->getLastModified()); $this->setCookies($dataResponse->getCookies()); $this->setContentSecurityPolicy(new EmptyContentSecurityPolicy()); if ($format === 'json') { $this->addHeader( 'Content-Type', 'application/json; charset=utf-8' ); } else { $this->addHeader( 'Content-Type', 'application/xml; charset=utf-8' ); } } /** * @param string[] $meta * @return string */ protected function renderResult($meta) { // TODO rewrite functions return \OC_API::renderResult($this->format, $meta, $this->data); } public function getOCSStatus() { return parent::getStatus(); } } OCS/V2Response.php 0000604 00000004253 15247165065 0007722 0 ustar 00 <?php /** * @copyright 2016 Roeland Jago Douma <roeland@famdouma.nl> * * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\AppFramework\OCS; use OCP\AppFramework\Http; use OCP\API; class V2Response extends BaseResponse { /** * The V2 endpoint just passes on status codes. * Of course we have to map the OCS specific codes to proper HTTP status codes * * @return int */ public function getStatus() { $status = parent::getStatus(); if ($status === API::RESPOND_UNAUTHORISED) { return Http::STATUS_UNAUTHORIZED; } else if ($status === API::RESPOND_NOT_FOUND) { return Http::STATUS_NOT_FOUND; } else if ($status === API::RESPOND_SERVER_ERROR || $status === API::RESPOND_UNKNOWN_ERROR) { return Http::STATUS_INTERNAL_SERVER_ERROR; } else if ($status < 200 || $status > 600) { return Http::STATUS_BAD_REQUEST; } return $status; } /** * Construct the meta part of the response * And then late the base class render * * @return string */ public function render() { $status = parent::getStatus(); $meta = [ 'status' => $status >= 200 && $status < 300 ? 'ok' : 'failure', 'statuscode' => $this->getOCSStatus(), 'message' => $status >= 200 && $status < 300 ? 'OK' : $this->statusMessage, ]; if ($this->itemsCount !== null) { $meta['totalitems'] = $this->itemsCount; } if ($this->itemsPerPage !== null) { $meta['itemsperpage'] = $this->itemsPerPage; } return $this->renderResult($meta); } } Middleware/OCSMiddleware.php 0000604 00000010366 15247165065 0011771 0 ustar 00 <?php /** * * @author Roeland Jago Douma <roeland@famdouma.nl> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\AppFramework\Middleware; use OC\AppFramework\Http; use OC\AppFramework\OCS\BaseResponse; use OC\AppFramework\OCS\V1Response; use OC\AppFramework\OCS\V2Response; use OCP\API; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\Http\Response; use OCP\AppFramework\OCS\OCSException; use OCP\AppFramework\OCSController; use OCP\IRequest; use OCP\AppFramework\Middleware; class OCSMiddleware extends Middleware { /** @var IRequest */ private $request; /** @var int */ private $ocsVersion; /** * @param IRequest $request */ public function __construct(IRequest $request) { $this->request = $request; } /** * @param \OCP\AppFramework\Controller $controller * @param string $methodName */ public function beforeController($controller, $methodName) { if ($controller instanceof OCSController) { if (substr_compare($this->request->getScriptName(), '/ocs/v2.php', -strlen('/ocs/v2.php')) === 0) { $this->ocsVersion = 2; } else { $this->ocsVersion = 1; } $controller->setOCSVersion($this->ocsVersion); } } /** * @param \OCP\AppFramework\Controller $controller * @param string $methodName * @param \Exception $exception * @throws \Exception * @return BaseResponse */ public function afterException($controller, $methodName, \Exception $exception) { if ($controller instanceof OCSController && $exception instanceof OCSException) { $code = $exception->getCode(); if ($code === 0) { $code = API::RESPOND_UNKNOWN_ERROR; } return $this->buildNewResponse($controller, $code, $exception->getMessage()); } throw $exception; } /** * @param \OCP\AppFramework\Controller $controller * @param string $methodName * @param Response $response * @return \OCP\AppFramework\Http\Response */ public function afterController($controller, $methodName, Response $response) { /* * If a different middleware has detected that a request unauthorized or forbidden * we need to catch the response and convert it to a proper OCS response. */ if ($controller instanceof OCSController && !($response instanceof BaseResponse)) { if ($response->getStatus() === Http::STATUS_UNAUTHORIZED || $response->getStatus() === Http::STATUS_FORBIDDEN) { $message = ''; if ($response instanceof JSONResponse) { /** @var DataResponse $response */ $message = $response->getData()['message']; } return $this->buildNewResponse($controller, API::RESPOND_UNAUTHORISED, $message); } } return $response; } /** * @param Controller $controller * @param int $code * @param string $message * @return V1Response|V2Response */ private function buildNewResponse($controller, $code, $message) { $format = $this->getFormat($controller); $data = new DataResponse(); $data->setStatus($code); if ($this->ocsVersion === 1) { $response = new V1Response($data, $format, $message); } else { $response = new V2Response($data, $format, $message); } return $response; } /** * @param \OCP\AppFramework\Controller $controller * @return string */ private function getFormat($controller) { // get format from the url format or request format parameter $format = $this->request->getParam('format'); // if none is given try the first Accept header if($format === null) { $headers = $this->request->getHeader('Accept'); $format = $controller->getResponderByHTTPHeader($headers, 'xml'); } return $format; } } Middleware/SessionMiddleware.php 0000604 00000004077 15247165065 0012772 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Morris Jobke <hey@morrisjobke.de> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Middleware; use OC\AppFramework\Utility\ControllerMethodReflector; use OCP\IRequest; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Middleware; use OCP\ISession; class SessionMiddleware extends Middleware { /** * @var IRequest */ private $request; /** * @var ControllerMethodReflector */ private $reflector; /** * @param IRequest $request * @param ControllerMethodReflector $reflector */ public function __construct(IRequest $request, ControllerMethodReflector $reflector, ISession $session ) { $this->request = $request; $this->reflector = $reflector; $this->session = $session; } /** * @param \OCP\AppFramework\Controller $controller * @param string $methodName */ public function beforeController($controller, $methodName) { $useSession = $this->reflector->hasAnnotation('UseSession'); if (!$useSession) { $this->session->close(); } } /** * @param \OCP\AppFramework\Controller $controller * @param string $methodName * @param Response $response * @return Response */ public function afterController($controller, $methodName, Response $response){ $useSession = $this->reflector->hasAnnotation('UseSession'); if ($useSession) { $this->session->close(); } return $response; } } Middleware/MiddlewareDispatcher.php 0000604 00000012356 15247165065 0013434 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Stefan Weil <sw@weilnetz.de> * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Thomas Tanghus <thomas@tanghus.net> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Middleware; use OCP\AppFramework\Controller; use OCP\AppFramework\Http\Response; use OCP\AppFramework\MiddleWare; /** * This class is used to store and run all the middleware in correct order */ class MiddlewareDispatcher { /** * @var array array containing all the middlewares */ private $middlewares; /** * @var int counter which tells us what middlware was executed once an * exception occurs */ private $middlewareCounter; /** * Constructor */ public function __construct(){ $this->middlewares = array(); $this->middlewareCounter = 0; } /** * Adds a new middleware * @param Middleware $middleWare the middleware which will be added */ public function registerMiddleware(Middleware $middleWare){ array_push($this->middlewares, $middleWare); } /** * returns an array with all middleware elements * @return array the middlewares */ public function getMiddlewares(){ return $this->middlewares; } /** * This is being run in normal order before the controller is being * called which allows several modifications and checks * * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller */ public function beforeController(Controller $controller, $methodName){ // we need to count so that we know which middlewares we have to ask in // case there is an exception $middlewareCount = count($this->middlewares); for($i = 0; $i < $middlewareCount; $i++){ $this->middlewareCounter++; $middleware = $this->middlewares[$i]; $middleware->beforeController($controller, $methodName); } } /** * This is being run when either the beforeController method or the * controller method itself is throwing an exception. The middleware is asked * in reverse order to handle the exception and to return a response. * If the response is null, it is assumed that the exception could not be * handled and the error will be thrown again * * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller * @param \Exception $exception the thrown exception * @return Response a Response object if the middleware can handle the * exception * @throws \Exception the passed in exception if it can't handle it */ public function afterException(Controller $controller, $methodName, \Exception $exception){ for($i=$this->middlewareCounter-1; $i>=0; $i--){ $middleware = $this->middlewares[$i]; try { return $middleware->afterException($controller, $methodName, $exception); } catch(\Exception $exception){ continue; } } throw $exception; } /** * This is being run after a successful controllermethod call and allows * the manipulation of a Response object. The middleware is run in reverse order * * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller * @param Response $response the generated response from the controller * @return Response a Response object */ public function afterController(Controller $controller, $methodName, Response $response){ for($i=count($this->middlewares)-1; $i>=0; $i--){ $middleware = $this->middlewares[$i]; $response = $middleware->afterController($controller, $methodName, $response); } return $response; } /** * This is being run after the response object has been rendered and * allows the manipulation of the output. The middleware is run in reverse order * * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller * @param string $output the generated output from a response * @return string the output that should be printed */ public function beforeOutput(Controller $controller, $methodName, $output){ for($i=count($this->middlewares)-1; $i>=0; $i--){ $middleware = $this->middlewares[$i]; $output = $middleware->beforeOutput($controller, $methodName, $output); } return $output; } } Middleware/Security/BruteForceMiddleware.php 0000604 00000005367 15247165065 0015221 0 ustar 00 <?php /** * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Utility\ControllerMethodReflector; use OC\Security\Bruteforce\Throttler; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Middleware; use OCP\IRequest; /** * Class BruteForceMiddleware performs the bruteforce protection for controllers * that are annotated with @BruteForceProtection(action=$action) whereas $action * is the action that should be logged within the database. * * @package OC\AppFramework\Middleware\Security */ class BruteForceMiddleware extends Middleware { /** @var ControllerMethodReflector */ private $reflector; /** @var Throttler */ private $throttler; /** @var IRequest */ private $request; /** * @param ControllerMethodReflector $controllerMethodReflector * @param Throttler $throttler * @param IRequest $request */ public function __construct(ControllerMethodReflector $controllerMethodReflector, Throttler $throttler, IRequest $request) { $this->reflector = $controllerMethodReflector; $this->throttler = $throttler; $this->request = $request; } /** * {@inheritDoc} */ public function beforeController($controller, $methodName) { parent::beforeController($controller, $methodName); if($this->reflector->hasAnnotation('BruteForceProtection')) { $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action'); $this->throttler->sleepDelay($this->request->getRemoteAddress(), $action); } } /** * {@inheritDoc} */ public function afterController($controller, $methodName, Response $response) { if($this->reflector->hasAnnotation('BruteForceProtection') && $response->isThrottled()) { $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action'); $ip = $this->request->getRemoteAddress(); $this->throttler->sleepDelay($ip, $action); $this->throttler->registerAttempt($action, $ip); } return parent::afterController($controller, $methodName, $response); } } Middleware/Security/Exceptions/SecurityException.php 0000604 00000002155 15247165065 0016762 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Middleware\Security\Exceptions; /** * Class SecurityException is the base class for security exceptions thrown by * the security middleware. * * @package OC\AppFramework\Middleware\Security\Exceptions */ class SecurityException extends \Exception {} Middleware/Security/Exceptions/StrictCookieMissingException.php 0000604 00000002403 15247165065 0021103 0 ustar 00 <?php /** * * @author Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\AppFramework\Middleware\Security\Exceptions; use OCP\AppFramework\Http; /** * Class StrictCookieMissingException is thrown when the strict cookie has not * been sent with the request but is required. * * @package OC\AppFramework\Middleware\Security\Exceptions */ class StrictCookieMissingException extends SecurityException { public function __construct() { parent::__construct('Strict Cookie has not been found in request.', Http::STATUS_PRECONDITION_FAILED); } } Middleware/Security/Exceptions/AppNotEnabledException.php 0000604 00000002504 15247165065 0017625 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Middleware\Security\Exceptions; use OCP\AppFramework\Http; /** * Class AppNotEnabledException is thrown when a resource for an application is * requested that is not enabled. * * @package OC\AppFramework\Middleware\Security\Exceptions */ class AppNotEnabledException extends SecurityException { public function __construct() { parent::__construct('App is not enabled', Http::STATUS_PRECONDITION_FAILED); } } Middleware/Security/Exceptions/CrossSiteRequestForgeryException.php 0000604 00000002476 15247165065 0022006 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Middleware\Security\Exceptions; use OCP\AppFramework\Http; /** * Class CrossSiteRequestForgeryException is thrown when a CSRF exception has * been encountered. * * @package OC\AppFramework\Middleware\Security\Exceptions */ class CrossSiteRequestForgeryException extends SecurityException { public function __construct() { parent::__construct('CSRF check failed', Http::STATUS_PRECONDITION_FAILED); } } Middleware/Security/Exceptions/NotAdminException.php 0000604 00000002555 15247165065 0016670 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Middleware\Security\Exceptions; use OCP\AppFramework\Http; /** * Class NotAdminException is thrown when a resource has been requested by a * non-admin user that is not accessible to non-admin users. * * @package OC\AppFramework\Middleware\Security\Exceptions */ class NotAdminException extends SecurityException { public function __construct($message = 'Logged in user must be an admin') { parent::__construct($message, Http::STATUS_FORBIDDEN); } } Middleware/Security/Exceptions/NotConfirmedException.php 0000604 00000002424 15247165065 0017541 0 ustar 00 <?php /** * @copyright Copyright (c) 2016 Joas Schilling <coding@schilljs.com> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\AppFramework\Middleware\Security\Exceptions; use OCP\AppFramework\Http; /** * Class NotConfirmedException is thrown when a resource has been requested by a * user that has not confirmed their password in the last 30 minutes. * * @package OC\AppFramework\Middleware\Security\Exceptions */ class NotConfirmedException extends SecurityException { public function __construct() { parent::__construct('Password confirmation is required', Http::STATUS_FORBIDDEN); } } Middleware/Security/Exceptions/NotLoggedInException.php 0000604 00000002530 15247165065 0017321 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Middleware\Security\Exceptions; use OCP\AppFramework\Http; /** * Class NotLoggedInException is thrown when a resource has been requested by a * guest user that is not accessible to the public. * * @package OC\AppFramework\Middleware\Security\Exceptions */ class NotLoggedInException extends SecurityException { public function __construct() { parent::__construct('Current user is not logged in', Http::STATUS_UNAUTHORIZED); } } Middleware/Security/SecurityMiddleware.php 0000604 00000022704 15247165065 0014762 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Stefan Weil <sw@weilnetz.de> * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Thomas Tanghus <thomas@tanghus.net> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Middleware\Security\Exceptions\AppNotEnabledException; use OC\AppFramework\Middleware\Security\Exceptions\CrossSiteRequestForgeryException; use OC\AppFramework\Middleware\Security\Exceptions\NotAdminException; use OC\AppFramework\Middleware\Security\Exceptions\NotConfirmedException; use OC\AppFramework\Middleware\Security\Exceptions\NotLoggedInException; use OC\AppFramework\Middleware\Security\Exceptions\StrictCookieMissingException; use OC\AppFramework\Utility\ControllerMethodReflector; use OC\Security\CSP\ContentSecurityPolicyManager; use OC\Security\CSP\ContentSecurityPolicyNonceManager; use OC\Security\CSRF\CsrfTokenManager; use OCP\AppFramework\Http\ContentSecurityPolicy; use OCP\AppFramework\Http\EmptyContentSecurityPolicy; use OCP\AppFramework\Http\RedirectResponse; use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Middleware; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\OCSController; use OCP\INavigationManager; use OCP\ISession; use OCP\IURLGenerator; use OCP\IRequest; use OCP\ILogger; use OCP\AppFramework\Controller; use OCP\Util; use OC\AppFramework\Middleware\Security\Exceptions\SecurityException; /** * Used to do all the authentication and checking stuff for a controller method * It reads out the annotations of a controller method and checks which if * security things should be checked and also handles errors in case a security * check fails */ class SecurityMiddleware extends Middleware { /** @var INavigationManager */ private $navigationManager; /** @var IRequest */ private $request; /** @var ControllerMethodReflector */ private $reflector; /** @var string */ private $appName; /** @var IURLGenerator */ private $urlGenerator; /** @var ILogger */ private $logger; /** @var ISession */ private $session; /** @var bool */ private $isLoggedIn; /** @var bool */ private $isAdminUser; /** @var ContentSecurityPolicyManager */ private $contentSecurityPolicyManager; /** @var CsrfTokenManager */ private $csrfTokenManager; /** @var ContentSecurityPolicyNonceManager */ private $cspNonceManager; /** * @param IRequest $request * @param ControllerMethodReflector $reflector * @param INavigationManager $navigationManager * @param IURLGenerator $urlGenerator * @param ILogger $logger * @param ISession $session * @param string $appName * @param bool $isLoggedIn * @param bool $isAdminUser * @param ContentSecurityPolicyManager $contentSecurityPolicyManager * @param CSRFTokenManager $csrfTokenManager * @param ContentSecurityPolicyNonceManager $cspNonceManager */ public function __construct(IRequest $request, ControllerMethodReflector $reflector, INavigationManager $navigationManager, IURLGenerator $urlGenerator, ILogger $logger, ISession $session, $appName, $isLoggedIn, $isAdminUser, ContentSecurityPolicyManager $contentSecurityPolicyManager, CsrfTokenManager $csrfTokenManager, ContentSecurityPolicyNonceManager $cspNonceManager) { $this->navigationManager = $navigationManager; $this->request = $request; $this->reflector = $reflector; $this->appName = $appName; $this->urlGenerator = $urlGenerator; $this->logger = $logger; $this->session = $session; $this->isLoggedIn = $isLoggedIn; $this->isAdminUser = $isAdminUser; $this->contentSecurityPolicyManager = $contentSecurityPolicyManager; $this->csrfTokenManager = $csrfTokenManager; $this->cspNonceManager = $cspNonceManager; } /** * This runs all the security checks before a method call. The * security checks are determined by inspecting the controller method * annotations * @param Controller $controller the controller * @param string $methodName the name of the method * @throws SecurityException when a security check fails */ public function beforeController($controller, $methodName) { // this will set the current navigation entry of the app, use this only // for normal HTML requests and not for AJAX requests $this->navigationManager->setActiveEntry($this->appName); // security checks $isPublicPage = $this->reflector->hasAnnotation('PublicPage'); if(!$isPublicPage) { if(!$this->isLoggedIn) { throw new NotLoggedInException(); } if(!$this->reflector->hasAnnotation('NoAdminRequired')) { if(!$this->isAdminUser) { throw new NotAdminException(); } } } if ($this->reflector->hasAnnotation('PasswordConfirmationRequired')) { $lastConfirm = (int) $this->session->get('last-password-confirm'); if ($lastConfirm < (time() - (30 * 60 + 15))) { // allow 15 seconds delay throw new NotConfirmedException(); } } // Check for strict cookie requirement if($this->reflector->hasAnnotation('StrictCookieRequired') || !$this->reflector->hasAnnotation('NoCSRFRequired')) { if(!$this->request->passesStrictCookieCheck()) { throw new StrictCookieMissingException(); } } // CSRF check - also registers the CSRF token since the session may be closed later Util::callRegister(); if(!$this->reflector->hasAnnotation('NoCSRFRequired')) { /* * Only allow the CSRF check to fail on OCS Requests. This kind of * hacks around that we have no full token auth in place yet and we * do want to offer CSRF checks for web requests. */ if(!$this->request->passesCSRFCheck() && !( $controller instanceof OCSController && $this->request->getHeader('OCS-APIREQUEST') === 'true')) { throw new CrossSiteRequestForgeryException(); } } /** * FIXME: Use DI once available * Checks if app is enabled (also includes a check whether user is allowed to access the resource) * The getAppPath() check is here since components such as settings also use the AppFramework and * therefore won't pass this check. */ if(\OC_App::getAppPath($this->appName) !== false && !\OC_App::isEnabled($this->appName)) { throw new AppNotEnabledException(); } } /** * Performs the default CSP modifications that may be injected by other * applications * * @param Controller $controller * @param string $methodName * @param Response $response * @return Response */ public function afterController($controller, $methodName, Response $response) { $policy = !is_null($response->getContentSecurityPolicy()) ? $response->getContentSecurityPolicy() : new ContentSecurityPolicy(); if (get_class($policy) === EmptyContentSecurityPolicy::class) { return $response; } $defaultPolicy = $this->contentSecurityPolicyManager->getDefaultPolicy(); $defaultPolicy = $this->contentSecurityPolicyManager->mergePolicies($defaultPolicy, $policy); if($this->cspNonceManager->browserSupportsCspV3()) { $defaultPolicy->useJsNonce($this->csrfTokenManager->getToken()->getEncryptedValue()); } $response->setContentSecurityPolicy($defaultPolicy); return $response; } /** * If an SecurityException is being caught, ajax requests return a JSON error * response and non ajax requests redirect to the index * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller * @param \Exception $exception the thrown exception * @throws \Exception the passed in exception if it can't handle it * @return Response a Response object or null in case that the exception could not be handled */ public function afterException($controller, $methodName, \Exception $exception) { if($exception instanceof SecurityException) { if($exception instanceof StrictCookieMissingException) { return new RedirectResponse(\OC::$WEBROOT); } if (stripos($this->request->getHeader('Accept'),'html') === false) { $response = new JSONResponse( array('message' => $exception->getMessage()), $exception->getCode() ); } else { if($exception instanceof NotLoggedInException) { $params = []; if (isset($this->request->server['REQUEST_URI'])) { $params['redirect_url'] = $this->request->server['REQUEST_URI']; } $url = $this->urlGenerator->linkToRoute('core.login.showLoginForm', $params); $response = new RedirectResponse($url); } else { $response = new TemplateResponse('core', '403', ['file' => $exception->getMessage()], 'guest'); $response->setStatus($exception->getCode()); } } $this->logger->debug($exception->getMessage()); return $response; } throw $exception; } } Middleware/Security/RateLimitingMiddleware.php 0000604 00000007773 15247165065 0015554 0 ustar 00 <?php /** * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch> * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Utility\ControllerMethodReflector; use OC\Security\RateLimiting\Exception\RateLimitExceededException; use OC\Security\RateLimiting\Limiter; use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Middleware; use OCP\IRequest; use OCP\IUserSession; /** * Class RateLimitingMiddleware is the middleware responsible for implementing the * ratelimiting in Nextcloud. * * It parses annotations such as: * * @UserRateThrottle(limit=5, period=100) * @AnonRateThrottle(limit=1, period=100) * * Those annotations above would mean that logged-in users can access the page 5 * times within 100 seconds, and anonymous users 1 time within 100 seconds. If * only an AnonRateThrottle is specified that one will also be applied to logged-in * users. * * @package OC\AppFramework\Middleware\Security */ class RateLimitingMiddleware extends Middleware { /** @var IRequest $request */ private $request; /** @var IUserSession */ private $userSession; /** @var ControllerMethodReflector */ private $reflector; /** @var Limiter */ private $limiter; /** * @param IRequest $request * @param IUserSession $userSession * @param ControllerMethodReflector $reflector * @param Limiter $limiter */ public function __construct(IRequest $request, IUserSession $userSession, ControllerMethodReflector $reflector, Limiter $limiter) { $this->request = $request; $this->userSession = $userSession; $this->reflector = $reflector; $this->limiter = $limiter; } /** * {@inheritDoc} * @throws RateLimitExceededException */ public function beforeController($controller, $methodName) { parent::beforeController($controller, $methodName); $anonLimit = $this->reflector->getAnnotationParameter('AnonRateThrottle', 'limit'); $anonPeriod = $this->reflector->getAnnotationParameter('AnonRateThrottle', 'period'); $userLimit = $this->reflector->getAnnotationParameter('UserRateThrottle', 'limit'); $userPeriod = $this->reflector->getAnnotationParameter('UserRateThrottle', 'period'); $rateLimitIdentifier = get_class($controller) . '::' . $methodName; if($userLimit !== '' && $userPeriod !== '' && $this->userSession->isLoggedIn()) { $this->limiter->registerUserRequest( $rateLimitIdentifier, $userLimit, $userPeriod, $this->userSession->getUser() ); } elseif ($anonLimit !== '' && $anonPeriod !== '') { $this->limiter->registerAnonRequest( $rateLimitIdentifier, $anonLimit, $anonPeriod, $this->request->getRemoteAddress() ); } } /** * {@inheritDoc} */ public function afterException($controller, $methodName, \Exception $exception) { if($exception instanceof RateLimitExceededException) { if (stripos($this->request->getHeader('Accept'),'html') === false) { $response = new JSONResponse( [ 'message' => $exception->getMessage(), ], $exception->getCode() ); } else { $response = new TemplateResponse( 'core', '403', [ 'file' => $exception->getMessage() ], 'guest' ); $response->setStatus($exception->getCode()); } return $response; } throw $exception; } } Middleware/Security/CORSMiddleware.php 0000604 00000013245 15247165065 0013721 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Christoph Wurst <christoph@owncloud.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Stefan Weil <sw@weilnetz.de> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Middleware\Security; use OC\AppFramework\Middleware\Security\Exceptions\SecurityException; use OC\AppFramework\Utility\ControllerMethodReflector; use OC\Authentication\Exceptions\PasswordLoginForbiddenException; use OC\Security\Bruteforce\Throttler; use OC\User\Session; use OCP\AppFramework\Controller; use OCP\AppFramework\Http; use OCP\AppFramework\Http\JSONResponse; use OCP\AppFramework\Http\Response; use OCP\AppFramework\Middleware; use OCP\IRequest; /** * This middleware sets the correct CORS headers on a response if the * controller has the @CORS annotation. This is needed for webapps that want * to access an API and don't run on the same domain, see * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS */ class CORSMiddleware extends Middleware { /** @var IRequest */ private $request; /** @var ControllerMethodReflector */ private $reflector; /** @var Session */ private $session; /** @var Throttler */ private $throttler; /** * @param IRequest $request * @param ControllerMethodReflector $reflector * @param Session $session * @param Throttler $throttler */ public function __construct(IRequest $request, ControllerMethodReflector $reflector, Session $session, Throttler $throttler) { $this->request = $request; $this->reflector = $reflector; $this->session = $session; $this->throttler = $throttler; } /** * This is being run in normal order before the controller is being * called which allows several modifications and checks * * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller * @throws SecurityException * @since 6.0.0 */ public function beforeController($controller, $methodName){ // ensure that @CORS annotated API routes are not used in conjunction // with session authentication since this enables CSRF attack vectors if ($this->reflector->hasAnnotation('CORS') && !$this->reflector->hasAnnotation('PublicPage')) { $user = $this->request->server['PHP_AUTH_USER']; $pass = $this->request->server['PHP_AUTH_PW']; $this->session->logout(); try { if (!$this->session->logClientIn($user, $pass, $this->request, $this->throttler)) { throw new SecurityException('CORS requires basic auth', Http::STATUS_UNAUTHORIZED); } } catch (PasswordLoginForbiddenException $ex) { throw new SecurityException('Password login forbidden, use token instead', Http::STATUS_UNAUTHORIZED); } } } /** * This is being run after a successful controllermethod call and allows * the manipulation of a Response object. The middleware is run in reverse order * * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller * @param Response $response the generated response from the controller * @return Response a Response object * @throws SecurityException */ public function afterController($controller, $methodName, Response $response){ // only react if its a CORS request and if the request sends origin and if(isset($this->request->server['HTTP_ORIGIN']) && $this->reflector->hasAnnotation('CORS')) { // allow credentials headers must not be true or CSRF is possible // otherwise foreach($response->getHeaders() as $header => $value) { if(strtolower($header) === 'access-control-allow-credentials' && strtolower(trim($value)) === 'true') { $msg = 'Access-Control-Allow-Credentials must not be '. 'set to true in order to prevent CSRF'; throw new SecurityException($msg); } } $origin = $this->request->server['HTTP_ORIGIN']; $response->addHeader('Access-Control-Allow-Origin', $origin); } return $response; } /** * If an SecurityException is being caught return a JSON error response * * @param Controller $controller the controller that is being called * @param string $methodName the name of the method that will be called on * the controller * @param \Exception $exception the thrown exception * @throws \Exception the passed in exception if it can't handle it * @return Response a Response object or null in case that the exception could not be handled */ public function afterException($controller, $methodName, \Exception $exception){ if($exception instanceof SecurityException){ $response = new JSONResponse(['message' => $exception->getMessage()]); if($exception->getCode() !== 0) { $response->setStatus($exception->getCode()); } else { $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR); } return $response; } throw $exception; } } DependencyInjection/DIContainer.php 0000604 00000031006 15247165065 0013344 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Christoph Wurst <christoph@owncloud.com> * @author Joas Schilling <coding@schilljs.com> * @author Jörn Friedrich Dreyer <jfd@butonic.de> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Roeland Jago Douma <roeland@famdouma.nl> * @author Thomas Müller <thomas.mueller@tmit.eu> * @author Thomas Tanghus <thomas@tanghus.net> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\DependencyInjection; use OC; use OC\AppFramework\Core\API; use OC\AppFramework\Http; use OC\AppFramework\Http\Dispatcher; use OC\AppFramework\Http\Output; use OC\AppFramework\Middleware\MiddlewareDispatcher; use OC\AppFramework\Middleware\Security\CORSMiddleware; use OC\AppFramework\Middleware\OCSMiddleware; use OC\AppFramework\Middleware\Security\RateLimitingMiddleware; use OC\AppFramework\Middleware\Security\SecurityMiddleware; use OC\AppFramework\Middleware\SessionMiddleware; use OC\AppFramework\Utility\SimpleContainer; use OC\Core\Middleware\TwoFactorMiddleware; use OC\RichObjectStrings\Validator; use OC\ServerContainer; use OCP\AppFramework\Http\IOutput; use OCP\AppFramework\IApi; use OCP\AppFramework\IAppContainer; use OCP\AppFramework\QueryException; use OCP\Files\Folder; use OCP\Files\IAppData; use OCP\GlobalScale\IConfig; use OCP\IL10N; use OCP\IRequest; use OCP\IServerContainer; use OCP\IUserSession; use OCP\RichObjectStrings\IValidator; use OCP\Util; class DIContainer extends SimpleContainer implements IAppContainer { /** * @var array */ private $middleWares = array(); /** @var ServerContainer */ private $server; /** * Put your class dependencies in here * @param string $appName the name of the app * @param array $urlParams * @param ServerContainer $server */ public function __construct($appName, $urlParams = array(), ServerContainer $server = null){ parent::__construct(); $this['AppName'] = $appName; $this['urlParams'] = $urlParams; /** @var \OC\ServerContainer $server */ if ($server === null) { $server = \OC::$server; } $this->server = $server; $this->server->registerAppContainer($appName, $this); // aliases $this->registerAlias('appName', 'AppName'); $this->registerAlias('webRoot', 'WebRoot'); $this->registerAlias('userId', 'UserId'); /** * Core services */ $this->registerService(IOutput::class, function($c){ return new Output($this->getServer()->getWebRoot()); }); $this->registerService(Folder::class, function() { return $this->getServer()->getUserFolder(); }); $this->registerService(IAppData::class, function (SimpleContainer $c) { return $this->getServer()->getAppDataDir($c->query('AppName')); }); $this->registerService(IL10N::class, function($c) { return $this->getServer()->getL10N($c->query('AppName')); }); $this->registerAlias(\OCP\AppFramework\Utility\IControllerMethodReflector::class, \OC\AppFramework\Utility\ControllerMethodReflector::class); $this->registerAlias('ControllerMethodReflector', \OCP\AppFramework\Utility\IControllerMethodReflector::class); $this->registerService(IRequest::class, function() { return $this->getServer()->query(IRequest::class); }); $this->registerAlias('Request', IRequest::class); $this->registerAlias(\OCP\AppFramework\Utility\ITimeFactory::class, \OC\AppFramework\Utility\TimeFactory::class); $this->registerAlias('TimeFactory', \OCP\AppFramework\Utility\ITimeFactory::class); $this->registerAlias(\OC\User\Session::class, \OCP\IUserSession::class); $this->registerService(IServerContainer::class, function ($c) { return $this->getServer(); }); $this->registerAlias('ServerContainer', IServerContainer::class); $this->registerService(\OCP\WorkflowEngine\IManager::class, function ($c) { return $c->query('OCA\WorkflowEngine\Manager'); }); $this->registerService(\OCP\AppFramework\IAppContainer::class, function ($c) { return $c; }); // commonly used attributes $this->registerService('UserId', function ($c) { return $c->query('OCP\\IUserSession')->getSession()->get('user_id'); }); $this->registerService('WebRoot', function ($c) { return $c->query('ServerContainer')->getWebRoot(); }); $this->registerService('fromMailAddress', function() { return Util::getDefaultEmailAddress('no-reply'); }); $this->registerService('OC_Defaults', function ($c) { return $c->getServer()->getThemingDefaults(); }); $this->registerService('OCP\Encryption\IManager', function ($c) { return $this->getServer()->getEncryptionManager(); }); $this->registerService(IConfig::class, function ($c) { return $c->query(OC\GlobalScale\Config::class); }); $this->registerService(IValidator::class, function($c) { return $c->query(Validator::class); }); $this->registerService(\OC\Security\IdentityProof\Manager::class, function ($c) { return new \OC\Security\IdentityProof\Manager( $this->getServer()->query(\OC\Files\AppData\Factory::class), $this->getServer()->getCrypto(), $this->getServer()->getConfig() ); }); /** * App Framework APIs */ $this->registerService('API', function($c){ $c->query('OCP\\ILogger')->debug( 'Accessing the API class is deprecated! Use the appropriate ' . 'services instead!' ); return new API($c['AppName']); }); $this->registerService('Protocol', function($c){ /** @var \OC\Server $server */ $server = $c->query('ServerContainer'); $protocol = $server->getRequest()->getHttpProtocol(); return new Http($_SERVER, $protocol); }); $this->registerService('Dispatcher', function($c) { return new Dispatcher( $c['Protocol'], $c['MiddlewareDispatcher'], $c['ControllerMethodReflector'], $c['Request'] ); }); /** * App Framework default arguments */ $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH'); $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept'); $this->registerParameter('corsMaxAge', 1728000); /** * Middleware */ $app = $this; $this->registerService('SecurityMiddleware', function($c) use ($app){ /** @var \OC\Server $server */ $server = $app->getServer(); return new SecurityMiddleware( $c['Request'], $c['ControllerMethodReflector'], $server->getNavigationManager(), $server->getURLGenerator(), $server->getLogger(), $server->getSession(), $c['AppName'], $app->isLoggedIn(), $app->isAdminUser(), $server->getContentSecurityPolicyManager(), $server->getCsrfTokenManager(), $server->getContentSecurityPolicyNonceManager() ); }); $this->registerService('BruteForceMiddleware', function($c) use ($app) { /** @var \OC\Server $server */ $server = $app->getServer(); return new OC\AppFramework\Middleware\Security\BruteForceMiddleware( $c['ControllerMethodReflector'], $server->getBruteForceThrottler(), $server->getRequest() ); }); $this->registerService('RateLimitingMiddleware', function($c) use ($app) { /** @var \OC\Server $server */ $server = $app->getServer(); return new RateLimitingMiddleware( $server->getRequest(), $server->getUserSession(), $c['ControllerMethodReflector'], $c->query(OC\Security\RateLimiting\Limiter::class) ); }); $this->registerService('CORSMiddleware', function($c) { return new CORSMiddleware( $c['Request'], $c['ControllerMethodReflector'], $c->query(IUserSession::class), $c->getServer()->getBruteForceThrottler() ); }); $this->registerService('SessionMiddleware', function($c) use ($app) { return new SessionMiddleware( $c['Request'], $c['ControllerMethodReflector'], $app->getServer()->getSession() ); }); $this->registerService('TwoFactorMiddleware', function (SimpleContainer $c) use ($app) { $twoFactorManager = $c->getServer()->getTwoFactorAuthManager(); $userSession = $app->getServer()->getUserSession(); $session = $app->getServer()->getSession(); $urlGenerator = $app->getServer()->getURLGenerator(); $reflector = $c['ControllerMethodReflector']; $request = $app->getServer()->getRequest(); return new TwoFactorMiddleware($twoFactorManager, $userSession, $session, $urlGenerator, $reflector, $request); }); $this->registerService('OCSMiddleware', function (SimpleContainer $c) { return new OCSMiddleware( $c['Request'] ); }); $middleWares = &$this->middleWares; $this->registerService('MiddlewareDispatcher', function($c) use (&$middleWares) { $dispatcher = new MiddlewareDispatcher(); $dispatcher->registerMiddleware($c['CORSMiddleware']); $dispatcher->registerMiddleware($c['OCSMiddleware']); $dispatcher->registerMiddleware($c['SecurityMiddleware']); $dispatcher->registerMiddleware($c['TwoFactorMiddleware']); $dispatcher->registerMiddleware($c['BruteForceMiddleware']); $dispatcher->registerMiddleware($c['RateLimitingMiddleware']); foreach($middleWares as $middleWare) { $dispatcher->registerMiddleware($c[$middleWare]); } $dispatcher->registerMiddleware($c['SessionMiddleware']); return $dispatcher; }); } /** * @deprecated implements only deprecated methods * @return IApi */ function getCoreApi() { return $this->query('API'); } /** * @return \OCP\IServerContainer */ function getServer() { return $this->server; } /** * @param string $middleWare * @return boolean|null */ function registerMiddleWare($middleWare) { array_push($this->middleWares, $middleWare); } /** * used to return the appname of the set application * @return string the name of your application */ function getAppName() { return $this->query('AppName'); } /** * @deprecated use IUserSession->isLoggedIn() * @return boolean */ function isLoggedIn() { return \OC::$server->getUserSession()->isLoggedIn(); } /** * @deprecated use IGroupManager->isAdmin($userId) * @return boolean */ function isAdminUser() { $uid = $this->getUserId(); return \OC_User::isAdminUser($uid); } private function getUserId() { return $this->getServer()->getSession()->get('user_id'); } /** * @deprecated use the ILogger instead * @param string $message * @param string $level * @return mixed */ function log($message, $level) { switch($level){ case 'debug': $level = \OCP\Util::DEBUG; break; case 'info': $level = \OCP\Util::INFO; break; case 'warn': $level = \OCP\Util::WARN; break; case 'fatal': $level = \OCP\Util::FATAL; break; default: $level = \OCP\Util::ERROR; break; } \OCP\Util::writeLog($this->getAppName(), $message, $level); } /** * Register a capability * * @param string $serviceName e.g. 'OCA\Files\Capabilities' */ public function registerCapability($serviceName) { $this->query('OC\CapabilitiesManager')->registerCapability(function() use ($serviceName) { return $this->query($serviceName); }); } /** * @param string $name * @return mixed * @throws QueryException if the query could not be resolved */ public function query($name) { try { return $this->queryNoFallback($name); } catch (QueryException $e) { return $this->getServer()->query($name); } } /** * @param string $name * @return mixed * @throws QueryException if the query could not be resolved */ public function queryNoFallback($name) { $name = $this->sanitizeName($name); if ($this->offsetExists($name)) { return parent::query($name); } else { if ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) { return parent::query($name); } else if ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) { return parent::query($name); } else if (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) { return parent::query($name); } } throw new QueryException('Could not resolve ' . $name . '!' . ' Class can not be instantiated'); } } Core/API.php 0000604 00000013336 15247165065 0006573 0 ustar 00 <?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Bernhard Posselt <dev@bernhard-posselt.com> * @author Lukas Reschke <lukas@statuscode.ch> * @author Morris Jobke <hey@morrisjobke.de> * @author Robin Appelman <robin@icewind.nl> * @author Robin McCorkell <robin@mccorkell.me.uk> * @author Thomas Müller <thomas.mueller@tmit.eu> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OC\AppFramework\Core; use OCP\AppFramework\IApi; /** * This is used to wrap the owncloud static api calls into an object to make the * code better abstractable for use in the dependency injection container * * Should you find yourself in need for more methods, simply inherit from this * class and add your methods * @deprecated */ class API implements IApi{ private $appName; /** * constructor * @param string $appName the name of your application */ public function __construct($appName){ $this->appName = $appName; } /** * Gets the userid of the current user * @return string the user id of the current user * @deprecated Use \OC::$server->getUserSession()->getUser()->getUID() */ public function getUserId(){ return \OCP\User::getUser(); } /** * Adds a new javascript file * @deprecated include javascript and css in template files * @param string $scriptName the name of the javascript in js/ without the suffix * @param string $appName the name of the app, defaults to the current one */ public function addScript($scriptName, $appName=null){ if($appName === null){ $appName = $this->appName; } \OCP\Util::addScript($appName, $scriptName); } /** * Adds a new css file * @deprecated include javascript and css in template files * @param string $styleName the name of the css file in css/without the suffix * @param string $appName the name of the app, defaults to the current one */ public function addStyle($styleName, $appName=null){ if($appName === null){ $appName = $this->appName; } \OCP\Util::addStyle($appName, $styleName); } /** * @deprecated include javascript and css in template files * shorthand for addScript for files in the 3rdparty directory * @param string $name the name of the file without the suffix */ public function add3rdPartyScript($name){ \OCP\Util::addScript($this->appName . '/3rdparty', $name); } /** * @deprecated include javascript and css in template files * shorthand for addStyle for files in the 3rdparty directory * @param string $name the name of the file without the suffix */ public function add3rdPartyStyle($name){ \OCP\Util::addStyle($this->appName . '/3rdparty', $name); } /** * @deprecated communication between apps should happen over built in * callbacks or interfaces (check the contacts and calendar managers) * Checks if an app is enabled * also use \OC::$server->getAppManager()->isEnabledForUser($appName) * @param string $appName the name of an app * @return bool true if app is enabled */ public function isAppEnabled($appName){ return \OCP\App::isEnabled($appName); } /** * used to return and open a new event source * @return \OCP\IEventSource a new open EventSource class * @deprecated Use \OC::$server->createEventSource(); */ public function openEventSource(){ return \OC::$server->createEventSource(); } /** * @deprecated register hooks directly for class that build in hook interfaces * connects a function to a hook * @param string $signalClass class name of emitter * @param string $signalName name of signal * @param string $slotClass class name of slot * @param string $slotName name of slot, in another word, this is the * name of the method that will be called when registered * signal is emitted. * @return bool always true */ public function connectHook($signalClass, $signalName, $slotClass, $slotName) { return \OCP\Util::connectHook($signalClass, $signalName, $slotClass, $slotName); } /** * @deprecated implement the emitter interface instead * Emits a signal. To get data from the slot use references! * @param string $signalClass class name of emitter * @param string $signalName name of signal * @param array $params default: array() array with additional data * @return bool true if slots exists or false if not */ public function emitHook($signalClass, $signalName, $params = array()) { return \OCP\Util::emitHook($signalClass, $signalName, $params); } /** * clear hooks * @deprecated clear hooks directly for class that build in hook interfaces * @param string $signalClass * @param string $signalName */ public function clearHook($signalClass=false, $signalName=false) { if ($signalClass) { \OC_Hook::clear($signalClass, $signalName); } } /** * Tells ownCloud to include a template in the admin overview * @param string $mainPath the path to the main php file without the php * suffix, relative to your apps directory! not the template directory * @param string $appName the name of the app, defaults to the current one */ public function registerAdmin($mainPath, $appName=null) { if($appName === null){ $appName = $this->appName; } \OCP\App::registerAdmin($appName, $mainPath); } }
| ver. 1.4 |
Github
|
.
| PHP 7.4.33 | Generation time: 0 |
proxy
|
phpinfo
|
Settings