summaryrefslogtreecommitdiffstats
path: root/apps
diff options
context:
space:
mode:
authorRoeland Jago Douma <rullzer@users.noreply.github.com>2018-05-10 09:32:07 +0200
committerGitHub <noreply@github.com>2018-05-10 09:32:07 +0200
commit58e4ddd63807227d7477fed70f0297a124f64cdf (patch)
tree474b03d8f7ee64859f26acfb5e74ac9dd9ae1228 /apps
parent48034bdc4a21aced21373f4871a28498b7ff0bff (diff)
parentced15ab7567fd3dc72734993609d663e399748b6 (diff)
downloadnextcloud-server-58e4ddd63807227d7477fed70f0297a124f64cdf.tar.gz
nextcloud-server-58e4ddd63807227d7477fed70f0297a124f64cdf.zip
Merge pull request #9360 from GitHubUser4234/ldap_password_renew_invarg_fix
Fix "Invalid argument supplied for foreach()"
Diffstat (limited to 'apps')
-rw-r--r--apps/user_ldap/lib/User/User.php4
-rw-r--r--apps/user_ldap/tests/User/UserTest.php8
2 files changed, 6 insertions, 6 deletions
diff --git a/apps/user_ldap/lib/User/User.php b/apps/user_ldap/lib/User/User.php
index eb4101ddc25..27578921450 100644
--- a/apps/user_ldap/lib/User/User.php
+++ b/apps/user_ldap/lib/User/User.php
@@ -617,7 +617,7 @@ class User {
$uid = $params['uid'];
if(isset($uid) && $uid === $this->getUsername()) {
//retrieve relevant user attributes
- $result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
+ $result = $this->access->search('objectclass=*', array($this->dn), ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
if(array_key_exists('pwdpolicysubentry', $result[0])) {
$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
@@ -634,7 +634,7 @@ class User {
$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
$result = $this->connection->getFromCache($cacheKey);
if(is_null($result)) {
- $result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
+ $result = $this->access->search('objectclass=*', array($ppolicyDN), ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
$this->connection->writeToCache($cacheKey, $result);
}
diff --git a/apps/user_ldap/tests/User/UserTest.php b/apps/user_ldap/tests/User/UserTest.php
index 27bd7762e39..c61a9bd3d47 100644
--- a/apps/user_ldap/tests/User/UserTest.php
+++ b/apps/user_ldap/tests/User/UserTest.php
@@ -1132,7 +1132,7 @@ class UserTest extends \Test\TestCase {
$this->access->expects($this->any())
->method('search')
->will($this->returnCallback(function($filter, $base) {
- if($base === 'uid=alice') {
+ if($base === array('uid=alice')) {
return array(
array(
'pwdchangedtime' => array((new \DateTime())->sub(new \DateInterval('P28D'))->format('Ymdhis').'Z'),
@@ -1140,7 +1140,7 @@ class UserTest extends \Test\TestCase {
),
);
}
- if($base === 'cn=default,ou=policies,dc=foo,dc=bar') {
+ if($base === array('cn=default,ou=policies,dc=foo,dc=bar')) {
return array(
array(
'pwdmaxage' => array('2592000'),
@@ -1202,7 +1202,7 @@ class UserTest extends \Test\TestCase {
$this->access->expects($this->any())
->method('search')
->will($this->returnCallback(function($filter, $base) {
- if($base === 'uid=alice') {
+ if($base === array('uid=alice')) {
return array(
array(
'pwdpolicysubentry' => array('cn=custom,ou=policies,dc=foo,dc=bar'),
@@ -1211,7 +1211,7 @@ class UserTest extends \Test\TestCase {
)
);
}
- if($base === 'cn=custom,ou=policies,dc=foo,dc=bar') {
+ if($base === array('cn=custom,ou=policies,dc=foo,dc=bar')) {
return array(
array(
'pwdmaxage' => array('2592000'),
'n264' href='#n264'>264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
<?php
/**
 * @copyright Copyright (c) 2016, ownCloud, Inc.
 *
 * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
 * @author Bart Visscher <bartv@thisnet.nl>
 * @author Benjamin Liles <benliles@arch.tamu.edu>
 * @author Christian Berendt <berendt@b1-systems.de>
 * @author Christopher Bartz <bartz@dkrz.de>
 * @author Daniel Tosello <tosello.daniel@gmail.com>
 * @author Felix Moeller <mail@felixmoeller.de>
 * @author Joas Schilling <coding@schilljs.com>
 * @author Jörn Friedrich Dreyer <jfd@butonic.de>
 * @author Lukas Reschke <lukas@statuscode.ch>
 * @author Martin Mattel <martin.mattel@diemattels.at>
 * @author Morris Jobke <hey@morrisjobke.de>
 * @author Philipp Kapfer <philipp.kapfer@gmx.at>
 * @author Robin Appelman <robin@icewind.nl>
 * @author Robin McCorkell <robin@mccorkell.me.uk>
 * @author Thomas Müller <thomas.mueller@tmit.eu>
 * @author Tim Dettrick <t.dettrick@uq.edu.au>
 * @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 OCA\Files_External\Lib\Storage;

use Guzzle\Http\Url;
use Guzzle\Http\Exception\ClientErrorResponseException;
use Icewind\Streams\CallbackWrapper;
use Icewind\Streams\IteratorDirectory;
use Icewind\Streams\RetryWrapper;
use OpenCloud;
use OpenCloud\Common\Exceptions;
use OpenCloud\OpenStack;
use OpenCloud\Rackspace;
use OpenCloud\ObjectStore\Resource\DataObject;

class Swift extends \OC\Files\Storage\Common {

	/**
	 * @var \OpenCloud\ObjectStore\Service
	 */
	private $connection;
	/**
	 * @var \OpenCloud\ObjectStore\Resource\Container
	 */
	private $container;
	/**
	 * @var \OpenCloud\OpenStack
	 */
	private $anchor;
	/**
	 * @var string
	 */
	private $bucket;
	/**
	 * Connection parameters
	 *
	 * @var array
	 */
	private $params;

	/** @var string  */
	private $id;

	/**
	 * Key value cache mapping path to data object. Maps path to
	 * \OpenCloud\OpenStack\ObjectStorage\Resource\DataObject for existing
	 * paths and path to false for not existing paths.
	 * @var \OCP\ICache
	 */
	private $objectCache;

	/**
	 * @param string $path
	 */
	private function normalizePath($path) {
		$path = trim($path, '/');

		if (!$path) {
			$path = '.';
		}

		$path = str_replace('#', '%23', $path);

		return $path;
	}

	const SUBCONTAINER_FILE = '.subcontainers';

	/**
	 * translate directory path to container name
	 *
	 * @param string $path
	 * @return string
	 */

	/**
	 * Fetches an object from the API.
	 * If the object is cached already or a
	 * failed "doesn't exist" response was cached,
	 * that one will be returned.
	 *
	 * @param string $path
	 * @return \OpenCloud\ObjectStore\Resource\DataObject|bool object
	 * or false if the object did not exist
	 */
	private function fetchObject($path) {
		if ($this->objectCache->hasKey($path)) {
			// might be "false" if object did not exist from last check
			return $this->objectCache->get($path);
		}
		try {
			$object = $this->getContainer()->getPartialObject($path);
			$this->objectCache->set($path, $object);
			return $object;
		} catch (ClientErrorResponseException $e) {
			// this exception happens when the object does not exist, which
			// is expected in most cases
			$this->objectCache->set($path, false);
			return false;
		} catch (ClientErrorResponseException $e) {
			// Expected response is "404 Not Found", so only log if it isn't
			if ($e->getResponse()->getStatusCode() !== 404) {
				\OC::$server->getLogger()->logException($e, [
					'level' => \OCP\Util::ERROR,
					'app' => 'files_external',
				]);
			}
			return false;
		}
	}

	/**
	 * Returns whether the given path exists.
	 *
	 * @param string $path
	 *
	 * @return bool true if the object exist, false otherwise
	 */
	private function doesObjectExist($path) {
		return $this->fetchObject($path) !== false;
	}

	public function __construct($params) {
		if ((empty($params['key']) and empty($params['password']))
			or empty($params['user']) or empty($params['bucket'])
			or empty($params['region'])
		) {
			throw new \Exception("API Key or password, Username, Bucket and Region have to be configured.");
		}

		$this->id = 'swift::' . $params['user'] . md5($params['bucket']);

		$bucketUrl = Url::factory($params['bucket']);
		if ($bucketUrl->isAbsolute()) {
			$this->bucket = end($bucketUrl->getPathSegments());
			$params['endpoint_url'] = $bucketUrl->addPath('..')->normalizePath();
		} else {
			$this->bucket = $params['bucket'];
		}

		if (empty($params['url'])) {
			$params['url'] = 'https://identity.api.rackspacecloud.com/v2.0/';
		}

		if (empty($params['service_name'])) {
			$params['service_name'] = 'cloudFiles';
		}

		$this->params = $params;
		// FIXME: private class...
		$this->objectCache = new \OC\Cache\CappedMemoryCache();
	}

	public function mkdir($path) {
		$path = $this->normalizePath($path);

		if ($this->is_dir($path)) {
			return false;
		}

		if ($path !== '.') {
			$path .= '/';
		}

		try {
			$customHeaders = array('content-type' => 'httpd/unix-directory');
			$metadataHeaders = DataObject::stockHeaders(array());
			$allHeaders = $customHeaders + $metadataHeaders;
			$this->getContainer()->uploadObject($path, '', $allHeaders);
			// invalidate so that the next access gets the real object
			// with all properties
			$this->objectCache->remove($path);
		} catch (Exceptions\CreateUpdateError $e) {
			\OC::$server->getLogger()->logException($e, [
				'level' => \OCP\Util::ERROR,
				'app' => 'files_external',
			]);
			return false;
		}

		return true;
	}

	public function file_exists($path) {
		$path = $this->normalizePath($path);

		if ($path !== '.' && $this->is_dir($path)) {
			$path .= '/';
		}

		return $this->doesObjectExist($path);
	}

	public function rmdir($path) {
		$path = $this->normalizePath($path);

		if (!$this->is_dir($path) || !$this->isDeletable($path)) {
			return false;
		}

		$dh = $this->opendir($path);
		while ($file = readdir($dh)) {
			if (\OC\Files\Filesystem::isIgnoredDir($file)) {
				continue;
			}

			if ($this->is_dir($path . '/' . $file)) {
				$this->rmdir($path . '/' . $file);
			} else {
				$this->unlink($path . '/' . $file);
			}
		}

		try {
			$this->getContainer()->dataObject()->setName($path . '/')->delete();
			$this->objectCache->remove($path . '/');
		} catch (Exceptions\DeleteError $e) {
			\OC::$server->getLogger()->logException($e, [
				'level' => \OCP\Util::ERROR,
				'app' => 'files_external',
			]);
			return false;
		}

		return true;
	}

	public function opendir($path) {
		$path = $this->normalizePath($path);

		if ($path === '.') {
			$path = '';
		} else {
			$path .= '/';
		}

		$path = str_replace('%23', '#', $path); // the prefix is sent as a query param, so revert the encoding of #

		try {
			$files = array();
			/** @var OpenCloud\Common\Collection $objects */
			$objects = $this->getContainer()->objectList(array(
				'prefix' => $path,
				'delimiter' => '/'
			));

			/** @var OpenCloud\ObjectStore\Resource\DataObject $object */
			foreach ($objects as $object) {
				$file = basename($object->getName());
				if ($file !== basename($path) && $file !== '.') {
					$files[] = $file;
				}
			}

			return IteratorDirectory::wrap($files);
		} catch (\Exception $e) {
			\OC::$server->getLogger()->logException($e, [
				'level' => \OCP\Util::ERROR,
				'app' => 'files_external',
			]);
			return false;
		}

	}

	public function stat($path) {
		$path = $this->normalizePath($path);

		if ($path === '.') {
			$path = '';
		} else if ($this->is_dir($path)) {
			$path .= '/';
		}

		try {
			/** @var DataObject $object */
			$object = $this->fetchObject($path);
			if (!$object) {
				return false;
			}
		} catch (ClientErrorResponseException $e) {
			\OC::$server->getLogger()->logException($e, [
				'level' => \OCP\Util::ERROR,
				'app' => 'files_external',
			]);
			return false;
		}

		$dateTime = \DateTime::createFromFormat(\DateTime::RFC1123, $object->getLastModified());
		if ($dateTime !== false) {
			$mtime = $dateTime->getTimestamp();
		} else {
			$mtime = null;
		}
		$objectMetadata = $object->getMetadata();
		$metaTimestamp = $objectMetadata->getProperty('timestamp');
		if (isset($metaTimestamp)) {
			$mtime = $metaTimestamp;
		}

		if (!empty($mtime)) {
			$mtime = floor($mtime);
		}

		$stat = array();
		$stat['size'] = (int)$object->getContentLength();
		$stat['mtime'] = $mtime;
		$stat['atime'] = time();
		return $stat;
	}

	public function filetype($path) {
		$path = $this->normalizePath($path);

		if ($path !== '.' && $this->doesObjectExist($path)) {
			return 'file';
		}

		if ($path !== '.') {
			$path .= '/';
		}

		if ($this->doesObjectExist($path)) {
			return 'dir';
		}
	}

	public function unlink($path) {
		$path = $this->normalizePath($path);

		if ($this->is_dir($path)) {
			return $this->rmdir($path);
		}

		try {
			$this->getContainer()->dataObject()->setName($path)->delete();
			$this->objectCache->remove($path);
			$this->objectCache->remove($path . '/');
		} catch (ClientErrorResponseException $e) {
			if ($e->getResponse()->getStatusCode() !== 404) {
				\OC::$server->getLogger()->logException($e, [
					'level' => \OCP\Util::ERROR,
					'app' => 'files_external',
				]);
			}
			return false;
		}

		return true;
	}

	public function fopen($path, $mode) {
		$path = $this->normalizePath($path);

		switch ($mode) {
			case 'a':
			case 'ab':
			case 'a+':
				return false;
			case 'r':
			case 'rb':
				try {
					$c = $this->getContainer();
					$streamFactory = new \Guzzle\Stream\PhpStreamRequestFactory();
					/** @var \OpenCloud\Common\Http\Client $client */
					$client = $c->getClient();
					$streamInterface = $streamFactory->fromRequest($client->get($c->getUrl($path)));
					$streamInterface->rewind();
					$stream = $streamInterface->getStream();
					stream_context_set_option($stream, 'swift','content', $streamInterface);
					if(!strrpos($streamInterface
						->getMetaData('wrapper_data')[0], '404 Not Found')) {
						return RetryWrapper::wrap($stream);
					}
					return false;
				} catch (\Guzzle\Http\Exception\BadResponseException $e) {
					\OC::$server->getLogger()->logException($e, [
						'level' => \OCP\Util::ERROR,
						'app' => 'files_external',
					]);
					return false;
				}
			case 'w':
			case 'wb':
			case 'r+':
			case 'w+':
			case 'wb+':
			case 'x':
			case 'x+':
			case 'c':
			case 'c+':
				if (strrpos($path, '.') !== false) {
					$ext = substr($path, strrpos($path, '.'));
				} else {
					$ext = '';
				}
				$tmpFile = \OCP\Files::tmpFile($ext);
				// Fetch existing file if required
				if ($mode[0] !== 'w' && $this->file_exists($path)) {
					if ($mode[0] === 'x') {
						// File cannot already exist
						return false;
					}
					$source = $this->fopen($path, 'r');
					file_put_contents($tmpFile, $source);
				}
				$handle = fopen($tmpFile, $mode);
				return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
					$this->writeBack($tmpFile, $path);
				});
		}
	}

	public function touch($path, $mtime = null) {
		$path = $this->normalizePath($path);
		if (is_null($mtime)) {
			$mtime = time();
		}
		$metadata = array('timestamp' => $mtime);
		if ($this->file_exists($path)) {
			if ($this->is_dir($path) && $path !== '.') {
				$path .= '/';
			}

			$object = $this->fetchObject($path);
			if ($object->saveMetadata($metadata)) {
				// invalidate target object to force repopulation on fetch
				$this->objectCache->remove($path);
			}
			return true;
		} else {
			$mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
			$customHeaders = array('content-type' => $mimeType);
			$metadataHeaders = DataObject::stockHeaders($metadata);
			$allHeaders = $customHeaders + $metadataHeaders;
			$this->getContainer()->uploadObject($path, '', $allHeaders);
			// invalidate target object to force repopulation on fetch
			$this->objectCache->remove($path);
			return true;
		}
	}

	public function copy($path1, $path2) {
		$path1 = $this->normalizePath($path1);
		$path2 = $this->normalizePath($path2);

		$fileType = $this->filetype($path1);
		if ($fileType === 'file') {

			// make way
			$this->unlink($path2);

			try {
				$source = $this->fetchObject($path1);
				$source->copy($this->bucket . '/' . $path2);
				// invalidate target object to force repopulation on fetch
				$this->objectCache->remove($path2);
				$this->objectCache->remove($path2 . '/');
			} catch (ClientErrorResponseException $e) {
				\OC::$server->getLogger()->logException($e, [
					'level' => \OCP\Util::ERROR,
					'app' => 'files_external',
				]);
				return false;
			}

		} else if ($fileType === 'dir') {

			// make way
			$this->unlink($path2);

			try {
				$source = $this->fetchObject($path1 . '/');
				$source->copy($this->bucket . '/' . $path2 . '/');
				// invalidate target object to force repopulation on fetch
				$this->objectCache->remove($path2);
				$this->objectCache->remove($path2 . '/');
			} catch (ClientErrorResponseException $e) {
				\OC::$server->getLogger()->logException($e, [
					'level' => \OCP\Util::ERROR,
					'app' => 'files_external',
				]);
				return false;
			}

			$dh = $this->opendir($path1);
			while ($file = readdir($dh)) {
				if (\OC\Files\Filesystem::isIgnoredDir($file)) {
					continue;
				}

				$source = $path1 . '/' . $file;
				$target = $path2 . '/' . $file;
				$this->copy($source, $target);
			}

		} else {
			//file does not exist
			return false;
		}

		return true;
	}

	public function rename($path1, $path2) {
		$path1 = $this->normalizePath($path1);
		$path2 = $this->normalizePath($path2);

		$fileType = $this->filetype($path1);

		if ($fileType === 'dir' || $fileType === 'file') {
			// copy
			if ($this->copy($path1, $path2) === false) {
				return false;
			}

			// cleanup
			if ($this->unlink($path1) === false) {
				$this->unlink($path2);
				return false;
			}

			return true;
		}

		return false;
	}

	public function getId() {
		return $this->id;
	}

	/**
	 * Returns the connection
	 *
	 * @return OpenCloud\ObjectStore\Service connected client
	 * @throws \Exception if connection could not be made
	 */
	public function getConnection() {
		if (!is_null($this->connection)) {
			return $this->connection;
		}

		$settings = array(
			'username' => $this->params['user'],
		);

		if (!empty($this->params['password'])) {
			$settings['password'] = $this->params['password'];
		} else if (!empty($this->params['key'])) {
			$settings['apiKey'] = $this->params['key'];
		}

		if (!empty($this->params['tenant'])) {
			$settings['tenantName'] = $this->params['tenant'];
		}

		if (!empty($this->params['timeout'])) {
			$settings['timeout'] = $this->params['timeout'];
		}

		if (isset($settings['apiKey'])) {
			$this->anchor = new Rackspace($this->params['url'], $settings);
		} else {
			$this->anchor = new OpenStack($this->params['url'], $settings);
		}

		$connection = $this->anchor->objectStoreService($this->params['service_name'], $this->params['region']);

		if (!empty($this->params['endpoint_url'])) {
			$endpoint = $connection->getEndpoint();
			$endpoint->setPublicUrl($this->params['endpoint_url']);
			$endpoint->setPrivateUrl($this->params['endpoint_url']);
			$connection->setEndpoint($endpoint);
		}

		$this->connection = $connection;

		return $this->connection;
	}

	/**
	 * Returns the initialized object store container.
	 *
	 * @return OpenCloud\ObjectStore\Resource\Container
	 */
	public function getContainer() {
		if (!is_null($this->container)) {
			return $this->container;
		}

		try {
			$this->container = $this->getConnection()->getContainer($this->bucket);
		} catch (ClientErrorResponseException $e) {
			$this->container = $this->getConnection()->createContainer($this->bucket);
		}

		if (!$this->file_exists('.')) {
			$this->mkdir('.');
		}

		return $this->container;
	}

	public function writeBack($tmpFile, $path) {
		$fileData = fopen($tmpFile, 'r');
		$this->getContainer()->uploadObject($path, $fileData);
		// invalidate target object to force repopulation on fetch
		$this->objectCache->remove($path);
		unlink($tmpFile);
	}

	public function hasUpdated($path, $time) {
		if ($this->is_file($path)) {
			return parent::hasUpdated($path, $time);
		}
		$path = $this->normalizePath($path);
		$dh = $this->opendir($path);
		$content = array();
		while (($file = readdir($dh)) !== false) {
			$content[] = $file;
		}
		if ($path === '.') {
			$path = '';
		}
		$cachedContent = $this->getCache()->getFolderContents($path);
		$cachedNames = array_map(function ($content) {
			return $content['name'];
		}, $cachedContent);
		sort($cachedNames);
		sort($content);
		return $cachedNames !== $content;
	}

	/**
	 * check if curl is installed
	 */
	public static function checkDependencies() {
		return true;
	}

}