AbstractMapping.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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 Doctrine\DBAL\Platforms\SqlitePlatform;
  30. use OCP\DB\IPreparedStatement;
  31. use OCP\DB\QueryBuilder\IQueryBuilder;
  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. return hash('sha256', $fdn, false);
  177. }
  178. /**
  179. * Gets the name based on the provided LDAP DN.
  180. *
  181. * @param string $fdn
  182. * @return string|false
  183. */
  184. public function getNameByDN($fdn) {
  185. if (!isset($this->cache[$fdn])) {
  186. $this->cache[$fdn] = $this->getXbyY('owncloud_name', 'ldap_dn_hash', $this->getDNHash($fdn));
  187. }
  188. return $this->cache[$fdn];
  189. }
  190. /**
  191. * @param array<string> $hashList
  192. */
  193. protected function prepareListOfIdsQuery(array $hashList): IQueryBuilder {
  194. $qb = $this->dbc->getQueryBuilder();
  195. $qb->select('owncloud_name', 'ldap_dn_hash', 'ldap_dn')
  196. ->from($this->getTableName(false))
  197. ->where($qb->expr()->in('ldap_dn_hash', $qb->createNamedParameter($hashList, IQueryBuilder::PARAM_STR_ARRAY)));
  198. return $qb;
  199. }
  200. protected function collectResultsFromListOfIdsQuery(IQueryBuilder $qb, array &$results): void {
  201. $stmt = $qb->executeQuery();
  202. while ($entry = $stmt->fetch(\Doctrine\DBAL\FetchMode::ASSOCIATIVE)) {
  203. $results[$entry['ldap_dn']] = $entry['owncloud_name'];
  204. $this->cache[$entry['ldap_dn']] = $entry['owncloud_name'];
  205. }
  206. $stmt->closeCursor();
  207. }
  208. /**
  209. * @param array<string> $fdns
  210. * @return array<string,string>
  211. */
  212. public function getListOfIdsByDn(array $fdns): array {
  213. $totalDBParamLimit = 65000;
  214. $sliceSize = 1000;
  215. $maxSlices = $this->dbc->getDatabasePlatform() instanceof SqlitePlatform ? 9 : $totalDBParamLimit / $sliceSize;
  216. $results = [];
  217. $slice = 1;
  218. $fdns = array_map([$this, 'getDNHash'], $fdns);
  219. $fdnsSlice = count($fdns) > $sliceSize ? array_slice($fdns, 0, $sliceSize) : $fdns;
  220. $qb = $this->prepareListOfIdsQuery($fdnsSlice);
  221. while (isset($fdnsSlice[999])) {
  222. // Oracle does not allow more than 1000 values in the IN list,
  223. // but allows slicing
  224. $slice++;
  225. $fdnsSlice = array_slice($fdns, $sliceSize * ($slice - 1), $sliceSize);
  226. /** @see https://github.com/vimeo/psalm/issues/4995 */
  227. /** @psalm-suppress TypeDoesNotContainType */
  228. if (!isset($qb)) {
  229. $qb = $this->prepareListOfIdsQuery($fdnsSlice);
  230. continue;
  231. }
  232. if (!empty($fdnsSlice)) {
  233. $qb->orWhere($qb->expr()->in('ldap_dn_hash', $qb->createNamedParameter($fdnsSlice, IQueryBuilder::PARAM_STR_ARRAY)));
  234. }
  235. if ($slice % $maxSlices === 0) {
  236. $this->collectResultsFromListOfIdsQuery($qb, $results);
  237. unset($qb);
  238. }
  239. }
  240. if (isset($qb)) {
  241. $this->collectResultsFromListOfIdsQuery($qb, $results);
  242. }
  243. return $results;
  244. }
  245. /**
  246. * Searches mapped names by the giving string in the name column
  247. *
  248. * @return string[]
  249. */
  250. public function getNamesBySearch(string $search, string $prefixMatch = "", string $postfixMatch = ""): array {
  251. $statement = $this->dbc->prepare('
  252. SELECT `owncloud_name`
  253. FROM `' . $this->getTableName() . '`
  254. WHERE `owncloud_name` LIKE ?
  255. ');
  256. try {
  257. $res = $statement->execute([$prefixMatch . $this->dbc->escapeLikeParameter($search) . $postfixMatch]);
  258. } catch (Exception $e) {
  259. return [];
  260. }
  261. $names = [];
  262. while ($row = $res->fetch()) {
  263. $names[] = $row['owncloud_name'];
  264. }
  265. return $names;
  266. }
  267. /**
  268. * Gets the name based on the provided LDAP UUID.
  269. *
  270. * @param string $uuid
  271. * @return string|false
  272. */
  273. public function getNameByUUID($uuid) {
  274. return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid);
  275. }
  276. public function getDnByUUID($uuid) {
  277. return $this->getXbyY('ldap_dn', 'directory_uuid', $uuid);
  278. }
  279. /**
  280. * Gets the UUID based on the provided LDAP DN
  281. *
  282. * @param string $dn
  283. * @return false|string
  284. * @throws \Exception
  285. */
  286. public function getUUIDByDN($dn) {
  287. return $this->getXbyY('directory_uuid', 'ldap_dn_hash', $this->getDNHash($dn));
  288. }
  289. public function getList(int $offset = 0, int $limit = null, bool $invalidatedOnly = false): array {
  290. $select = $this->dbc->getQueryBuilder();
  291. $select->selectAlias('ldap_dn', 'dn')
  292. ->selectAlias('owncloud_name', 'name')
  293. ->selectAlias('directory_uuid', 'uuid')
  294. ->from($this->getTableName())
  295. ->setMaxResults($limit)
  296. ->setFirstResult($offset);
  297. if ($invalidatedOnly) {
  298. $select->where($select->expr()->like('directory_uuid', $select->createNamedParameter('invalidated_%')));
  299. }
  300. $result = $select->executeQuery();
  301. $entries = $result->fetchAll();
  302. $result->closeCursor();
  303. return $entries;
  304. }
  305. /**
  306. * attempts to map the given entry
  307. *
  308. * @param string $fdn fully distinguished name (from LDAP)
  309. * @param string $name
  310. * @param string $uuid a unique identifier as used in LDAP
  311. * @return bool
  312. */
  313. public function map($fdn, $name, $uuid) {
  314. if (mb_strlen($fdn) > 4000) {
  315. \OC::$server->getLogger()->error(
  316. 'Cannot map, because the DN exceeds 4000 characters: {dn}',
  317. [
  318. 'app' => 'user_ldap',
  319. 'dn' => $fdn,
  320. ]
  321. );
  322. return false;
  323. }
  324. $row = [
  325. 'ldap_dn_hash' => $this->getDNHash($fdn),
  326. 'ldap_dn' => $fdn,
  327. 'owncloud_name' => $name,
  328. 'directory_uuid' => $uuid
  329. ];
  330. try {
  331. $result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
  332. if ((bool)$result === true) {
  333. $this->cache[$fdn] = $name;
  334. }
  335. // insertIfNotExist returns values as int
  336. return (bool)$result;
  337. } catch (\Exception $e) {
  338. return false;
  339. }
  340. }
  341. /**
  342. * removes a mapping based on the owncloud_name of the entry
  343. *
  344. * @param string $name
  345. * @return bool
  346. */
  347. public function unmap($name) {
  348. $statement = $this->dbc->prepare('
  349. DELETE FROM `' . $this->getTableName() . '`
  350. WHERE `owncloud_name` = ?');
  351. $dn = array_search($name, $this->cache);
  352. if ($dn !== false) {
  353. unset($this->cache[$dn]);
  354. }
  355. return $this->modify($statement, [$name]);
  356. }
  357. /**
  358. * Truncates the mapping table
  359. *
  360. * @return bool
  361. */
  362. public function clear() {
  363. $sql = $this->dbc
  364. ->getDatabasePlatform()
  365. ->getTruncateTableSQL('`' . $this->getTableName() . '`');
  366. try {
  367. $this->dbc->executeQuery($sql);
  368. return true;
  369. } catch (Exception $e) {
  370. return false;
  371. }
  372. }
  373. /**
  374. * clears the mapping table one by one and executing a callback with
  375. * each row's id (=owncloud_name col)
  376. *
  377. * @param callable $preCallback
  378. * @param callable $postCallback
  379. * @return bool true on success, false when at least one row was not
  380. * deleted
  381. */
  382. public function clearCb(callable $preCallback, callable $postCallback): bool {
  383. $picker = $this->dbc->getQueryBuilder();
  384. $picker->select('owncloud_name')
  385. ->from($this->getTableName());
  386. $cursor = $picker->executeQuery();
  387. $result = true;
  388. while (($id = $cursor->fetchOne()) !== false) {
  389. $preCallback($id);
  390. if ($isUnmapped = $this->unmap($id)) {
  391. $postCallback($id);
  392. }
  393. $result = $result && $isUnmapped;
  394. }
  395. $cursor->closeCursor();
  396. return $result;
  397. }
  398. /**
  399. * returns the number of entries in the mappings table
  400. *
  401. * @return int
  402. */
  403. public function count(): int {
  404. $query = $this->dbc->getQueryBuilder();
  405. $query->select($query->func()->count('ldap_dn_hash'))
  406. ->from($this->getTableName());
  407. $res = $query->execute();
  408. $count = $res->fetchOne();
  409. $res->closeCursor();
  410. return (int)$count;
  411. }
  412. public function countInvalidated(): int {
  413. $query = $this->dbc->getQueryBuilder();
  414. $query->select($query->func()->count('ldap_dn_hash'))
  415. ->from($this->getTableName())
  416. ->where($query->expr()->like('directory_uuid', $query->createNamedParameter('invalidated_%')));
  417. $res = $query->execute();
  418. $count = $res->fetchOne();
  419. $res->closeCursor();
  420. return (int)$count;
  421. }
  422. }