1
0

AbstractMapping.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Aaron Wood <aaronjwood@gmail.com>
  6. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  7. * @author blizzz <blizzz@arthur-schiwon.de>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Joas Schilling <coding@schilljs.com>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OCA\User_LDAP\Mapping;
  28. use Doctrine\DBAL\Exception;
  29. use OCP\DB\IPreparedStatement;
  30. use OCP\DB\QueryBuilder\IQueryBuilder;
  31. use Doctrine\DBAL\Platforms\SqlitePlatform;
  32. /**
  33. * Class AbstractMapping
  34. *
  35. * @package OCA\User_LDAP\Mapping
  36. */
  37. abstract class AbstractMapping {
  38. /**
  39. * @var \OCP\IDBConnection $dbc
  40. */
  41. protected $dbc;
  42. /**
  43. * returns the DB table name which holds the mappings
  44. *
  45. * @return string
  46. */
  47. abstract protected function getTableName(bool $includePrefix = true);
  48. /**
  49. * @param \OCP\IDBConnection $dbc
  50. */
  51. public function __construct(\OCP\IDBConnection $dbc) {
  52. $this->dbc = $dbc;
  53. }
  54. /** @var array caches Names (value) by DN (key) */
  55. protected $cache = [];
  56. /**
  57. * checks whether a provided string represents an existing table col
  58. *
  59. * @param string $col
  60. * @return bool
  61. */
  62. public function isColNameValid($col) {
  63. switch ($col) {
  64. case 'ldap_dn':
  65. case 'ldap_dn_hash':
  66. case 'owncloud_name':
  67. case 'directory_uuid':
  68. return true;
  69. default:
  70. return false;
  71. }
  72. }
  73. /**
  74. * Gets the value of one column based on a provided value of another column
  75. *
  76. * @param string $fetchCol
  77. * @param string $compareCol
  78. * @param string $search
  79. * @return string|false
  80. * @throws \Exception
  81. */
  82. protected function getXbyY($fetchCol, $compareCol, $search) {
  83. if (!$this->isColNameValid($fetchCol)) {
  84. //this is used internally only, but we don't want to risk
  85. //having SQL injection at all.
  86. throw new \Exception('Invalid Column Name');
  87. }
  88. $query = $this->dbc->prepare('
  89. SELECT `' . $fetchCol . '`
  90. FROM `' . $this->getTableName() . '`
  91. WHERE `' . $compareCol . '` = ?
  92. ');
  93. try {
  94. $res = $query->execute([$search]);
  95. $data = $res->fetchOne();
  96. $res->closeCursor();
  97. return $data;
  98. } catch (Exception $e) {
  99. return false;
  100. }
  101. }
  102. /**
  103. * Performs a DELETE or UPDATE query to the database.
  104. *
  105. * @param IPreparedStatement $statement
  106. * @param array $parameters
  107. * @return bool true if at least one row was modified, false otherwise
  108. */
  109. protected function modify(IPreparedStatement $statement, $parameters) {
  110. try {
  111. $result = $statement->execute($parameters);
  112. $updated = $result->rowCount() > 0;
  113. $result->closeCursor();
  114. return $updated;
  115. } catch (Exception $e) {
  116. return false;
  117. }
  118. }
  119. /**
  120. * Gets the LDAP DN based on the provided name.
  121. * Replaces Access::ocname2dn
  122. *
  123. * @param string $name
  124. * @return string|false
  125. */
  126. public function getDNByName($name) {
  127. $dn = array_search($name, $this->cache);
  128. if ($dn === false && ($dn = $this->getXbyY('ldap_dn', 'owncloud_name', $name)) !== false) {
  129. $this->cache[$dn] = $name;
  130. }
  131. return $dn;
  132. }
  133. /**
  134. * Updates the DN based on the given UUID
  135. *
  136. * @param string $fdn
  137. * @param string $uuid
  138. * @return bool
  139. */
  140. public function setDNbyUUID($fdn, $uuid) {
  141. $oldDn = $this->getDnByUUID($uuid);
  142. $statement = $this->dbc->prepare('
  143. UPDATE `' . $this->getTableName() . '`
  144. SET `ldap_dn_hash` = ?, `ldap_dn` = ?
  145. WHERE `directory_uuid` = ?
  146. ');
  147. $r = $this->modify($statement, [$this->getDNHash($fdn), $fdn, $uuid]);
  148. if ($r && is_string($oldDn) && isset($this->cache[$oldDn])) {
  149. $this->cache[$fdn] = $this->cache[$oldDn];
  150. unset($this->cache[$oldDn]);
  151. }
  152. return $r;
  153. }
  154. /**
  155. * Updates the UUID based on the given DN
  156. *
  157. * required by Migration/UUIDFix
  158. *
  159. * @param $uuid
  160. * @param $fdn
  161. * @return bool
  162. */
  163. public function setUUIDbyDN($uuid, $fdn): bool {
  164. $statement = $this->dbc->prepare('
  165. UPDATE `' . $this->getTableName() . '`
  166. SET `directory_uuid` = ?
  167. WHERE `ldap_dn_hash` = ?
  168. ');
  169. unset($this->cache[$fdn]);
  170. return $this->modify($statement, [$uuid, $this->getDNHash($fdn)]);
  171. }
  172. /**
  173. * Get the hash to store in database column ldap_dn_hash for a given dn
  174. */
  175. protected function getDNHash(string $fdn): string {
  176. $hash = hash('sha256', $fdn, false);
  177. if (is_string($hash)) {
  178. return $hash;
  179. } else {
  180. throw new \RuntimeException('hash function did not return a string');
  181. }
  182. }
  183. /**
  184. * Gets the name based on the provided LDAP DN.
  185. *
  186. * @param string $fdn
  187. * @return string|false
  188. */
  189. public function getNameByDN($fdn) {
  190. if (!isset($this->cache[$fdn])) {
  191. $this->cache[$fdn] = $this->getXbyY('owncloud_name', 'ldap_dn_hash', $this->getDNHash($fdn));
  192. }
  193. return $this->cache[$fdn];
  194. }
  195. /**
  196. * @param array<string> $hashList
  197. */
  198. protected function prepareListOfIdsQuery(array $hashList): IQueryBuilder {
  199. $qb = $this->dbc->getQueryBuilder();
  200. $qb->select('owncloud_name', 'ldap_dn_hash', 'ldap_dn')
  201. ->from($this->getTableName(false))
  202. ->where($qb->expr()->in('ldap_dn_hash', $qb->createNamedParameter($hashList, IQueryBuilder::PARAM_STR_ARRAY)));
  203. return $qb;
  204. }
  205. protected function collectResultsFromListOfIdsQuery(IQueryBuilder $qb, array &$results): void {
  206. $stmt = $qb->executeQuery();
  207. while ($entry = $stmt->fetch(\Doctrine\DBAL\FetchMode::ASSOCIATIVE)) {
  208. $results[$entry['ldap_dn']] = $entry['owncloud_name'];
  209. $this->cache[$entry['ldap_dn']] = $entry['owncloud_name'];
  210. }
  211. $stmt->closeCursor();
  212. }
  213. /**
  214. * @param array<string> $fdns
  215. * @return array<string,string>
  216. */
  217. public function getListOfIdsByDn(array $fdns): array {
  218. $totalDBParamLimit = 65000;
  219. $sliceSize = 1000;
  220. $maxSlices = $this->dbc->getDatabasePlatform() instanceof SqlitePlatform ? 9 : $totalDBParamLimit / $sliceSize;
  221. $results = [];
  222. $slice = 1;
  223. $fdns = array_map([$this, 'getDNHash'], $fdns);
  224. $fdnsSlice = count($fdns) > $sliceSize ? array_slice($fdns, 0, $sliceSize) : $fdns;
  225. $qb = $this->prepareListOfIdsQuery($fdnsSlice);
  226. while (isset($fdnsSlice[999])) {
  227. // Oracle does not allow more than 1000 values in the IN list,
  228. // but allows slicing
  229. $slice++;
  230. $fdnsSlice = array_slice($fdns, $sliceSize * ($slice - 1), $sliceSize);
  231. /** @see https://github.com/vimeo/psalm/issues/4995 */
  232. /** @psalm-suppress TypeDoesNotContainType */
  233. if (!isset($qb)) {
  234. $qb = $this->prepareListOfIdsQuery($fdnsSlice);
  235. continue;
  236. }
  237. if (!empty($fdnsSlice)) {
  238. $qb->orWhere($qb->expr()->in('ldap_dn_hash', $qb->createNamedParameter($fdnsSlice, IQueryBuilder::PARAM_STR_ARRAY)));
  239. }
  240. if ($slice % $maxSlices === 0) {
  241. $this->collectResultsFromListOfIdsQuery($qb, $results);
  242. unset($qb);
  243. }
  244. }
  245. if (isset($qb)) {
  246. $this->collectResultsFromListOfIdsQuery($qb, $results);
  247. }
  248. return $results;
  249. }
  250. /**
  251. * Searches mapped names by the giving string in the name column
  252. *
  253. * @return string[]
  254. */
  255. public function getNamesBySearch(string $search, string $prefixMatch = "", string $postfixMatch = ""): array {
  256. $statement = $this->dbc->prepare('
  257. SELECT `owncloud_name`
  258. FROM `' . $this->getTableName() . '`
  259. WHERE `owncloud_name` LIKE ?
  260. ');
  261. try {
  262. $res = $statement->execute([$prefixMatch . $this->dbc->escapeLikeParameter($search) . $postfixMatch]);
  263. } catch (Exception $e) {
  264. return [];
  265. }
  266. $names = [];
  267. while ($row = $res->fetch()) {
  268. $names[] = $row['owncloud_name'];
  269. }
  270. return $names;
  271. }
  272. /**
  273. * Gets the name based on the provided LDAP UUID.
  274. *
  275. * @param string $uuid
  276. * @return string|false
  277. */
  278. public function getNameByUUID($uuid) {
  279. return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid);
  280. }
  281. public function getDnByUUID($uuid) {
  282. return $this->getXbyY('ldap_dn', 'directory_uuid', $uuid);
  283. }
  284. /**
  285. * Gets the UUID based on the provided LDAP DN
  286. *
  287. * @param string $dn
  288. * @return false|string
  289. * @throws \Exception
  290. */
  291. public function getUUIDByDN($dn) {
  292. return $this->getXbyY('directory_uuid', 'ldap_dn_hash', $this->getDNHash($dn));
  293. }
  294. public function getList(int $offset = 0, int $limit = null, bool $invalidatedOnly = false): array {
  295. $select = $this->dbc->getQueryBuilder();
  296. $select->selectAlias('ldap_dn', 'dn')
  297. ->selectAlias('owncloud_name', 'name')
  298. ->selectAlias('directory_uuid', 'uuid')
  299. ->from($this->getTableName())
  300. ->setMaxResults($limit)
  301. ->setFirstResult($offset);
  302. if ($invalidatedOnly) {
  303. $select->where($select->expr()->like('directory_uuid', $select->createNamedParameter('invalidated_%')));
  304. }
  305. $result = $select->executeQuery();
  306. $entries = $result->fetchAll();
  307. $result->closeCursor();
  308. return $entries;
  309. }
  310. /**
  311. * attempts to map the given entry
  312. *
  313. * @param string $fdn fully distinguished name (from LDAP)
  314. * @param string $name
  315. * @param string $uuid a unique identifier as used in LDAP
  316. * @return bool
  317. */
  318. public function map($fdn, $name, $uuid) {
  319. if (mb_strlen($fdn) > 4000) {
  320. \OC::$server->getLogger()->error(
  321. 'Cannot map, because the DN exceeds 4000 characters: {dn}',
  322. [
  323. 'app' => 'user_ldap',
  324. 'dn' => $fdn,
  325. ]
  326. );
  327. return false;
  328. }
  329. $row = [
  330. 'ldap_dn_hash' => $this->getDNHash($fdn),
  331. 'ldap_dn' => $fdn,
  332. 'owncloud_name' => $name,
  333. 'directory_uuid' => $uuid
  334. ];
  335. try {
  336. $result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
  337. if ((bool)$result === true) {
  338. $this->cache[$fdn] = $name;
  339. }
  340. // insertIfNotExist returns values as int
  341. return (bool)$result;
  342. } catch (\Exception $e) {
  343. return false;
  344. }
  345. }
  346. /**
  347. * removes a mapping based on the owncloud_name of the entry
  348. *
  349. * @param string $name
  350. * @return bool
  351. */
  352. public function unmap($name) {
  353. $statement = $this->dbc->prepare('
  354. DELETE FROM `' . $this->getTableName() . '`
  355. WHERE `owncloud_name` = ?');
  356. $dn = array_search($name, $this->cache);
  357. if ($dn !== false) {
  358. unset($this->cache[$dn]);
  359. }
  360. return $this->modify($statement, [$name]);
  361. }
  362. /**
  363. * Truncates the mapping table
  364. *
  365. * @return bool
  366. */
  367. public function clear() {
  368. $sql = $this->dbc
  369. ->getDatabasePlatform()
  370. ->getTruncateTableSQL('`' . $this->getTableName() . '`');
  371. try {
  372. $this->dbc->executeQuery($sql);
  373. return true;
  374. } catch (Exception $e) {
  375. return false;
  376. }
  377. }
  378. /**
  379. * clears the mapping table one by one and executing a callback with
  380. * each row's id (=owncloud_name col)
  381. *
  382. * @param callable $preCallback
  383. * @param callable $postCallback
  384. * @return bool true on success, false when at least one row was not
  385. * deleted
  386. */
  387. public function clearCb(callable $preCallback, callable $postCallback): bool {
  388. $picker = $this->dbc->getQueryBuilder();
  389. $picker->select('owncloud_name')
  390. ->from($this->getTableName());
  391. $cursor = $picker->executeQuery();
  392. $result = true;
  393. while (($id = $cursor->fetchOne()) !== false) {
  394. $preCallback($id);
  395. if ($isUnmapped = $this->unmap($id)) {
  396. $postCallback($id);
  397. }
  398. $result = $result && $isUnmapped;
  399. }
  400. $cursor->closeCursor();
  401. return $result;
  402. }
  403. /**
  404. * returns the number of entries in the mappings table
  405. *
  406. * @return int
  407. */
  408. public function count(): int {
  409. $query = $this->dbc->getQueryBuilder();
  410. $query->select($query->func()->count('ldap_dn_hash'))
  411. ->from($this->getTableName());
  412. $res = $query->execute();
  413. $count = $res->fetchOne();
  414. $res->closeCursor();
  415. return (int)$count;
  416. }
  417. public function countInvalidated(): int {
  418. $query = $this->dbc->getQueryBuilder();
  419. $query->select($query->func()->count('ldap_dn_hash'))
  420. ->from($this->getTableName())
  421. ->where($query->expr()->like('directory_uuid', $query->createNamedParameter('invalidated_%')));
  422. $res = $query->execute();
  423. $count = $res->fetchOne();
  424. $res->closeCursor();
  425. return (int)$count;
  426. }
  427. }