You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Access.php 62KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Aaron Wood <aaronjwood@gmail.com>
  6. * @author Alexander Bergolth <leo@strike.wu.ac.at>
  7. * @author Andreas Fischer <bantu@owncloud.com>
  8. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  9. * @author Bart Visscher <bartv@thisnet.nl>
  10. * @author Benjamin Diele <benjamin@diele.be>
  11. * @author Christopher Schäpers <kondou@ts.unde.re>
  12. * @author Joas Schilling <coding@schilljs.com>
  13. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  14. * @author Lorenzo M. Catucci <lorenzo@sancho.ccd.uniroma2.it>
  15. * @author Lukas Reschke <lukas@statuscode.ch>
  16. * @author Lyonel Vincent <lyonel@ezix.org>
  17. * @author Mario Kolling <mario.kolling@serpro.gov.br>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Nicolas Grekas <nicolas.grekas@gmail.com>
  20. * @author Ralph Krimmel <rkrimme1@gwdg.de>
  21. * @author Renaud Fortier <Renaud.Fortier@fsaa.ulaval.ca>
  22. * @author Robin McCorkell <robin@mccorkell.me.uk>
  23. * @author Roger Szabo <roger.szabo@web.de>
  24. *
  25. * @license AGPL-3.0
  26. *
  27. * This code is free software: you can redistribute it and/or modify
  28. * it under the terms of the GNU Affero General Public License, version 3,
  29. * as published by the Free Software Foundation.
  30. *
  31. * This program is distributed in the hope that it will be useful,
  32. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  33. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  34. * GNU Affero General Public License for more details.
  35. *
  36. * You should have received a copy of the GNU Affero General Public License, version 3,
  37. * along with this program. If not, see <http://www.gnu.org/licenses/>
  38. *
  39. */
  40. namespace OCA\User_LDAP;
  41. use OC\HintException;
  42. use OCA\User_LDAP\Exceptions\ConstraintViolationException;
  43. use OCA\User_LDAP\User\IUserTools;
  44. use OCA\User_LDAP\User\Manager;
  45. use OCA\User_LDAP\User\OfflineUser;
  46. use OCA\User_LDAP\Mapping\AbstractMapping;
  47. use OC\ServerNotAvailableException;
  48. /**
  49. * Class Access
  50. * @package OCA\User_LDAP
  51. */
  52. class Access extends LDAPUtility implements IUserTools {
  53. /**
  54. * @var \OCA\User_LDAP\Connection
  55. */
  56. public $connection;
  57. /** @var Manager */
  58. public $userManager;
  59. //never ever check this var directly, always use getPagedSearchResultState
  60. protected $pagedSearchedSuccessful;
  61. /**
  62. * @var string[] $cookies an array of returned Paged Result cookies
  63. */
  64. protected $cookies = array();
  65. /**
  66. * @var string $lastCookie the last cookie returned from a Paged Results
  67. * operation, defaults to an empty string
  68. */
  69. protected $lastCookie = '';
  70. /**
  71. * @var AbstractMapping $userMapper
  72. */
  73. protected $userMapper;
  74. /**
  75. * @var AbstractMapping $userMapper
  76. */
  77. protected $groupMapper;
  78. /**
  79. * @var \OCA\User_LDAP\Helper
  80. */
  81. private $helper;
  82. public function __construct(Connection $connection, ILDAPWrapper $ldap,
  83. Manager $userManager, Helper $helper) {
  84. parent::__construct($ldap);
  85. $this->connection = $connection;
  86. $this->userManager = $userManager;
  87. $this->userManager->setLdapAccess($this);
  88. $this->helper = $helper;
  89. }
  90. /**
  91. * sets the User Mapper
  92. * @param AbstractMapping $mapper
  93. */
  94. public function setUserMapper(AbstractMapping $mapper) {
  95. $this->userMapper = $mapper;
  96. }
  97. /**
  98. * returns the User Mapper
  99. * @throws \Exception
  100. * @return AbstractMapping
  101. */
  102. public function getUserMapper() {
  103. if(is_null($this->userMapper)) {
  104. throw new \Exception('UserMapper was not assigned to this Access instance.');
  105. }
  106. return $this->userMapper;
  107. }
  108. /**
  109. * sets the Group Mapper
  110. * @param AbstractMapping $mapper
  111. */
  112. public function setGroupMapper(AbstractMapping $mapper) {
  113. $this->groupMapper = $mapper;
  114. }
  115. /**
  116. * returns the Group Mapper
  117. * @throws \Exception
  118. * @return AbstractMapping
  119. */
  120. public function getGroupMapper() {
  121. if(is_null($this->groupMapper)) {
  122. throw new \Exception('GroupMapper was not assigned to this Access instance.');
  123. }
  124. return $this->groupMapper;
  125. }
  126. /**
  127. * @return bool
  128. */
  129. private function checkConnection() {
  130. return ($this->connection instanceof Connection);
  131. }
  132. /**
  133. * returns the Connection instance
  134. * @return \OCA\User_LDAP\Connection
  135. */
  136. public function getConnection() {
  137. return $this->connection;
  138. }
  139. /**
  140. * reads a given attribute for an LDAP record identified by a DN
  141. * @param string $dn the record in question
  142. * @param string $attr the attribute that shall be retrieved
  143. * if empty, just check the record's existence
  144. * @param string $filter
  145. * @return array|false an array of values on success or an empty
  146. * array if $attr is empty, false otherwise
  147. */
  148. public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
  149. if(!$this->checkConnection()) {
  150. \OCP\Util::writeLog('user_ldap',
  151. 'No LDAP Connector assigned, access impossible for readAttribute.',
  152. \OCP\Util::WARN);
  153. return false;
  154. }
  155. $cr = $this->connection->getConnectionResource();
  156. if(!$this->ldap->isResource($cr)) {
  157. //LDAP not available
  158. \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
  159. return false;
  160. }
  161. //Cancel possibly running Paged Results operation, otherwise we run in
  162. //LDAP protocol errors
  163. $this->abandonPagedSearch();
  164. // openLDAP requires that we init a new Paged Search. Not needed by AD,
  165. // but does not hurt either.
  166. $pagingSize = intval($this->connection->ldapPagingSize);
  167. // 0 won't result in replies, small numbers may leave out groups
  168. // (cf. #12306), 500 is default for paging and should work everywhere.
  169. $maxResults = $pagingSize > 20 ? $pagingSize : 500;
  170. $attr = mb_strtolower($attr, 'UTF-8');
  171. // the actual read attribute later may contain parameters on a ranged
  172. // request, e.g. member;range=99-199. Depends on server reply.
  173. $attrToRead = $attr;
  174. $values = [];
  175. $isRangeRequest = false;
  176. do {
  177. $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
  178. if(is_bool($result)) {
  179. // when an exists request was run and it was successful, an empty
  180. // array must be returned
  181. return $result ? [] : false;
  182. }
  183. if (!$isRangeRequest) {
  184. $values = $this->extractAttributeValuesFromResult($result, $attr);
  185. if (!empty($values)) {
  186. return $values;
  187. }
  188. }
  189. $isRangeRequest = false;
  190. $result = $this->extractRangeData($result, $attr);
  191. if (!empty($result)) {
  192. $normalizedResult = $this->extractAttributeValuesFromResult(
  193. [ $attr => $result['values'] ],
  194. $attr
  195. );
  196. $values = array_merge($values, $normalizedResult);
  197. if($result['rangeHigh'] === '*') {
  198. // when server replies with * as high range value, there are
  199. // no more results left
  200. return $values;
  201. } else {
  202. $low = $result['rangeHigh'] + 1;
  203. $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
  204. $isRangeRequest = true;
  205. }
  206. }
  207. } while($isRangeRequest);
  208. \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
  209. return false;
  210. }
  211. /**
  212. * Runs an read operation against LDAP
  213. *
  214. * @param resource $cr the LDAP connection
  215. * @param string $dn
  216. * @param string $attribute
  217. * @param string $filter
  218. * @param int $maxResults
  219. * @return array|bool false if there was any error, true if an exists check
  220. * was performed and the requested DN found, array with the
  221. * returned data on a successful usual operation
  222. */
  223. public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
  224. $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
  225. $dn = $this->helper->DNasBaseParameter($dn);
  226. $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute));
  227. if (!$this->ldap->isResource($rr)) {
  228. if ($attribute !== '') {
  229. //do not throw this message on userExists check, irritates
  230. \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
  231. }
  232. //in case an error occurs , e.g. object does not exist
  233. return false;
  234. }
  235. if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
  236. \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
  237. return true;
  238. }
  239. $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
  240. if (!$this->ldap->isResource($er)) {
  241. //did not match the filter, return false
  242. return false;
  243. }
  244. //LDAP attributes are not case sensitive
  245. $result = \OCP\Util::mb_array_change_key_case(
  246. $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
  247. return $result;
  248. }
  249. /**
  250. * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
  251. * data if present.
  252. *
  253. * @param array $result from ILDAPWrapper::getAttributes()
  254. * @param string $attribute the attribute name that was read
  255. * @return string[]
  256. */
  257. public function extractAttributeValuesFromResult($result, $attribute) {
  258. $values = [];
  259. if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
  260. $lowercaseAttribute = strtolower($attribute);
  261. for($i=0;$i<$result[$attribute]['count'];$i++) {
  262. if($this->resemblesDN($attribute)) {
  263. $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
  264. } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
  265. $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
  266. } else {
  267. $values[] = $result[$attribute][$i];
  268. }
  269. }
  270. }
  271. return $values;
  272. }
  273. /**
  274. * Attempts to find ranged data in a getAttribute results and extracts the
  275. * returned values as well as information on the range and full attribute
  276. * name for further processing.
  277. *
  278. * @param array $result from ILDAPWrapper::getAttributes()
  279. * @param string $attribute the attribute name that was read. Without ";range=…"
  280. * @return array If a range was detected with keys 'values', 'attributeName',
  281. * 'attributeFull' and 'rangeHigh', otherwise empty.
  282. */
  283. public function extractRangeData($result, $attribute) {
  284. $keys = array_keys($result);
  285. foreach($keys as $key) {
  286. if($key !== $attribute && strpos($key, $attribute) === 0) {
  287. $queryData = explode(';', $key);
  288. if(strpos($queryData[1], 'range=') === 0) {
  289. $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
  290. $data = [
  291. 'values' => $result[$key],
  292. 'attributeName' => $queryData[0],
  293. 'attributeFull' => $key,
  294. 'rangeHigh' => $high,
  295. ];
  296. return $data;
  297. }
  298. }
  299. }
  300. return [];
  301. }
  302. /**
  303. * Set password for an LDAP user identified by a DN
  304. *
  305. * @param string $userDN the user in question
  306. * @param string $password the new password
  307. * @return bool
  308. * @throws HintException
  309. * @throws \Exception
  310. */
  311. public function setPassword($userDN, $password) {
  312. if(intval($this->connection->turnOnPasswordChange) !== 1) {
  313. throw new \Exception('LDAP password changes are disabled.');
  314. }
  315. $cr = $this->connection->getConnectionResource();
  316. if(!$this->ldap->isResource($cr)) {
  317. //LDAP not available
  318. \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
  319. return false;
  320. }
  321. try {
  322. return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
  323. } catch(ConstraintViolationException $e) {
  324. throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
  325. }
  326. }
  327. /**
  328. * checks whether the given attributes value is probably a DN
  329. * @param string $attr the attribute in question
  330. * @return boolean if so true, otherwise false
  331. */
  332. private function resemblesDN($attr) {
  333. $resemblingAttributes = array(
  334. 'dn',
  335. 'uniquemember',
  336. 'member',
  337. // memberOf is an "operational" attribute, without a definition in any RFC
  338. 'memberof'
  339. );
  340. return in_array($attr, $resemblingAttributes);
  341. }
  342. /**
  343. * checks whether the given string is probably a DN
  344. * @param string $string
  345. * @return boolean
  346. */
  347. public function stringResemblesDN($string) {
  348. $r = $this->ldap->explodeDN($string, 0);
  349. // if exploding a DN succeeds and does not end up in
  350. // an empty array except for $r[count] being 0.
  351. return (is_array($r) && count($r) > 1);
  352. }
  353. /**
  354. * returns a DN-string that is cleaned from not domain parts, e.g.
  355. * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
  356. * becomes dc=foobar,dc=server,dc=org
  357. * @param string $dn
  358. * @return string
  359. */
  360. public function getDomainDNFromDN($dn) {
  361. $allParts = $this->ldap->explodeDN($dn, 0);
  362. if($allParts === false) {
  363. //not a valid DN
  364. return '';
  365. }
  366. $domainParts = array();
  367. $dcFound = false;
  368. foreach($allParts as $part) {
  369. if(!$dcFound && strpos($part, 'dc=') === 0) {
  370. $dcFound = true;
  371. }
  372. if($dcFound) {
  373. $domainParts[] = $part;
  374. }
  375. }
  376. $domainDN = implode(',', $domainParts);
  377. return $domainDN;
  378. }
  379. /**
  380. * returns the LDAP DN for the given internal Nextcloud name of the group
  381. * @param string $name the Nextcloud name in question
  382. * @return string|false LDAP DN on success, otherwise false
  383. */
  384. public function groupname2dn($name) {
  385. return $this->groupMapper->getDNByName($name);
  386. }
  387. /**
  388. * returns the LDAP DN for the given internal Nextcloud name of the user
  389. * @param string $name the Nextcloud name in question
  390. * @return string|false with the LDAP DN on success, otherwise false
  391. */
  392. public function username2dn($name) {
  393. $fdn = $this->userMapper->getDNByName($name);
  394. //Check whether the DN belongs to the Base, to avoid issues on multi-
  395. //server setups
  396. if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
  397. return $fdn;
  398. }
  399. return false;
  400. }
  401. /**
  402. * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
  403. * @param string $fdn the dn of the group object
  404. * @param string $ldapName optional, the display name of the object
  405. * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
  406. */
  407. public function dn2groupname($fdn, $ldapName = null) {
  408. //To avoid bypassing the base DN settings under certain circumstances
  409. //with the group support, check whether the provided DN matches one of
  410. //the given Bases
  411. if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
  412. return false;
  413. }
  414. return $this->dn2ocname($fdn, $ldapName, false);
  415. }
  416. /**
  417. * accepts an array of group DNs and tests whether they match the user
  418. * filter by doing read operations against the group entries. Returns an
  419. * array of DNs that match the filter.
  420. *
  421. * @param string[] $groupDNs
  422. * @return string[]
  423. */
  424. public function groupsMatchFilter($groupDNs) {
  425. $validGroupDNs = [];
  426. foreach($groupDNs as $dn) {
  427. $cacheKey = 'groupsMatchFilter-'.$dn;
  428. $groupMatchFilter = $this->connection->getFromCache($cacheKey);
  429. if(!is_null($groupMatchFilter)) {
  430. if($groupMatchFilter) {
  431. $validGroupDNs[] = $dn;
  432. }
  433. continue;
  434. }
  435. // Check the base DN first. If this is not met already, we don't
  436. // need to ask the server at all.
  437. if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
  438. $this->connection->writeToCache($cacheKey, false);
  439. continue;
  440. }
  441. $result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
  442. if(is_array($result)) {
  443. $this->connection->writeToCache($cacheKey, true);
  444. $validGroupDNs[] = $dn;
  445. } else {
  446. $this->connection->writeToCache($cacheKey, false);
  447. }
  448. }
  449. return $validGroupDNs;
  450. }
  451. /**
  452. * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
  453. * @param string $dn the dn of the user object
  454. * @param string $ldapName optional, the display name of the object
  455. * @return string|false with with the name to use in Nextcloud
  456. */
  457. public function dn2username($fdn, $ldapName = null) {
  458. //To avoid bypassing the base DN settings under certain circumstances
  459. //with the group support, check whether the provided DN matches one of
  460. //the given Bases
  461. if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
  462. return false;
  463. }
  464. return $this->dn2ocname($fdn, $ldapName, true);
  465. }
  466. /**
  467. * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
  468. * @param string $dn the dn of the user object
  469. * @param string $ldapName optional, the display name of the object
  470. * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
  471. * @return string|false with with the name to use in Nextcloud
  472. */
  473. public function dn2ocname($fdn, $ldapName = null, $isUser = true) {
  474. if($isUser) {
  475. $mapper = $this->getUserMapper();
  476. $nameAttribute = $this->connection->ldapUserDisplayName;
  477. } else {
  478. $mapper = $this->getGroupMapper();
  479. $nameAttribute = $this->connection->ldapGroupDisplayName;
  480. }
  481. //let's try to retrieve the Nextcloud name from the mappings table
  482. $ocName = $mapper->getNameByDN($fdn);
  483. if(is_string($ocName)) {
  484. return $ocName;
  485. }
  486. //second try: get the UUID and check if it is known. Then, update the DN and return the name.
  487. $uuid = $this->getUUID($fdn, $isUser);
  488. if(is_string($uuid)) {
  489. $ocName = $mapper->getNameByUUID($uuid);
  490. if(is_string($ocName)) {
  491. $mapper->setDNbyUUID($fdn, $uuid);
  492. return $ocName;
  493. }
  494. } else {
  495. //If the UUID can't be detected something is foul.
  496. \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
  497. return false;
  498. }
  499. if(is_null($ldapName)) {
  500. $ldapName = $this->readAttribute($fdn, $nameAttribute);
  501. if(!isset($ldapName[0]) && empty($ldapName[0])) {
  502. \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
  503. return false;
  504. }
  505. $ldapName = $ldapName[0];
  506. }
  507. if($isUser) {
  508. $usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
  509. if ($usernameAttribute !== '') {
  510. $username = $this->readAttribute($fdn, $usernameAttribute);
  511. $username = $username[0];
  512. } else {
  513. $username = $uuid;
  514. }
  515. $intName = $this->sanitizeUsername($username);
  516. } else {
  517. $intName = $ldapName;
  518. }
  519. //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
  520. //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
  521. //NOTE: mind, disabling cache affects only this instance! Using it
  522. // outside of core user management will still cache the user as non-existing.
  523. $originalTTL = $this->connection->ldapCacheTTL;
  524. $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
  525. if(($isUser && !\OCP\User::userExists($intName))
  526. || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
  527. if($mapper->map($fdn, $intName, $uuid)) {
  528. $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
  529. return $intName;
  530. }
  531. }
  532. $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
  533. $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
  534. if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
  535. return $altName;
  536. }
  537. //if everything else did not help..
  538. \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
  539. return false;
  540. }
  541. /**
  542. * gives back the user names as they are used ownClod internally
  543. * @param array $ldapUsers as returned by fetchList()
  544. * @return array an array with the user names to use in Nextcloud
  545. *
  546. * gives back the user names as they are used ownClod internally
  547. */
  548. public function nextcloudUserNames($ldapUsers) {
  549. return $this->ldap2NextcloudNames($ldapUsers, true);
  550. }
  551. /**
  552. * gives back the group names as they are used ownClod internally
  553. * @param array $ldapGroups as returned by fetchList()
  554. * @return array an array with the group names to use in Nextcloud
  555. *
  556. * gives back the group names as they are used ownClod internally
  557. */
  558. public function nextcloudGroupNames($ldapGroups) {
  559. return $this->ldap2NextcloudNames($ldapGroups, false);
  560. }
  561. /**
  562. * @param array $ldapObjects as returned by fetchList()
  563. * @param bool $isUsers
  564. * @return array
  565. */
  566. private function ldap2NextcloudNames($ldapObjects, $isUsers) {
  567. if($isUsers) {
  568. $nameAttribute = $this->connection->ldapUserDisplayName;
  569. $sndAttribute = $this->connection->ldapUserDisplayName2;
  570. } else {
  571. $nameAttribute = $this->connection->ldapGroupDisplayName;
  572. }
  573. $nextcloudNames = array();
  574. foreach($ldapObjects as $ldapObject) {
  575. $nameByLDAP = null;
  576. if( isset($ldapObject[$nameAttribute])
  577. && is_array($ldapObject[$nameAttribute])
  578. && isset($ldapObject[$nameAttribute][0])
  579. ) {
  580. // might be set, but not necessarily. if so, we use it.
  581. $nameByLDAP = $ldapObject[$nameAttribute][0];
  582. }
  583. $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
  584. if($ncName) {
  585. $nextcloudNames[] = $ncName;
  586. if($isUsers) {
  587. //cache the user names so it does not need to be retrieved
  588. //again later (e.g. sharing dialogue).
  589. if(is_null($nameByLDAP)) {
  590. continue;
  591. }
  592. $sndName = isset($ldapObject[$sndAttribute][0])
  593. ? $ldapObject[$sndAttribute][0] : '';
  594. $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
  595. }
  596. }
  597. }
  598. return $nextcloudNames;
  599. }
  600. /**
  601. * caches the user display name
  602. * @param string $ocName the internal Nextcloud username
  603. * @param string|false $home the home directory path
  604. */
  605. public function cacheUserHome($ocName, $home) {
  606. $cacheKey = 'getHome'.$ocName;
  607. $this->connection->writeToCache($cacheKey, $home);
  608. }
  609. /**
  610. * caches a user as existing
  611. * @param string $ocName the internal Nextcloud username
  612. */
  613. public function cacheUserExists($ocName) {
  614. $this->connection->writeToCache('userExists'.$ocName, true);
  615. }
  616. /**
  617. * caches the user display name
  618. * @param string $ocName the internal Nextcloud username
  619. * @param string $displayName the display name
  620. * @param string $displayName2 the second display name
  621. */
  622. public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
  623. $user = $this->userManager->get($ocName);
  624. if($user === null) {
  625. return;
  626. }
  627. $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
  628. $cacheKeyTrunk = 'getDisplayName';
  629. $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
  630. }
  631. /**
  632. * creates a unique name for internal Nextcloud use for users. Don't call it directly.
  633. * @param string $name the display name of the object
  634. * @return string|false with with the name to use in Nextcloud or false if unsuccessful
  635. *
  636. * Instead of using this method directly, call
  637. * createAltInternalOwnCloudName($name, true)
  638. */
  639. private function _createAltInternalOwnCloudNameForUsers($name) {
  640. $attempts = 0;
  641. //while loop is just a precaution. If a name is not generated within
  642. //20 attempts, something else is very wrong. Avoids infinite loop.
  643. while($attempts < 20){
  644. $altName = $name . '_' . rand(1000,9999);
  645. if(!\OCP\User::userExists($altName)) {
  646. return $altName;
  647. }
  648. $attempts++;
  649. }
  650. return false;
  651. }
  652. /**
  653. * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
  654. * @param string $name the display name of the object
  655. * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
  656. *
  657. * Instead of using this method directly, call
  658. * createAltInternalOwnCloudName($name, false)
  659. *
  660. * Group names are also used as display names, so we do a sequential
  661. * numbering, e.g. Developers_42 when there are 41 other groups called
  662. * "Developers"
  663. */
  664. private function _createAltInternalOwnCloudNameForGroups($name) {
  665. $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
  666. if(!($usedNames) || count($usedNames) === 0) {
  667. $lastNo = 1; //will become name_2
  668. } else {
  669. natsort($usedNames);
  670. $lastName = array_pop($usedNames);
  671. $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
  672. }
  673. $altName = $name.'_'.strval($lastNo+1);
  674. unset($usedNames);
  675. $attempts = 1;
  676. while($attempts < 21){
  677. // Check to be really sure it is unique
  678. // while loop is just a precaution. If a name is not generated within
  679. // 20 attempts, something else is very wrong. Avoids infinite loop.
  680. if(!\OC::$server->getGroupManager()->groupExists($altName)) {
  681. return $altName;
  682. }
  683. $altName = $name . '_' . ($lastNo + $attempts);
  684. $attempts++;
  685. }
  686. return false;
  687. }
  688. /**
  689. * creates a unique name for internal Nextcloud use.
  690. * @param string $name the display name of the object
  691. * @param boolean $isUser whether name should be created for a user (true) or a group (false)
  692. * @return string|false with with the name to use in Nextcloud or false if unsuccessful
  693. */
  694. private function createAltInternalOwnCloudName($name, $isUser) {
  695. $originalTTL = $this->connection->ldapCacheTTL;
  696. $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
  697. if($isUser) {
  698. $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
  699. } else {
  700. $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
  701. }
  702. $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
  703. return $altName;
  704. }
  705. /**
  706. * fetches a list of users according to a provided loginName and utilizing
  707. * the login filter.
  708. *
  709. * @param string $loginName
  710. * @param array $attributes optional, list of attributes to read
  711. * @return array
  712. */
  713. public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
  714. $loginName = $this->escapeFilterPart($loginName);
  715. $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
  716. $users = $this->fetchListOfUsers($filter, $attributes);
  717. return $users;
  718. }
  719. /**
  720. * counts the number of users according to a provided loginName and
  721. * utilizing the login filter.
  722. *
  723. * @param string $loginName
  724. * @return array
  725. */
  726. public function countUsersByLoginName($loginName) {
  727. $loginName = $this->escapeFilterPart($loginName);
  728. $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
  729. $users = $this->countUsers($filter);
  730. return $users;
  731. }
  732. /**
  733. * @param string $filter
  734. * @param string|string[] $attr
  735. * @param int $limit
  736. * @param int $offset
  737. * @return array
  738. */
  739. public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null) {
  740. $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
  741. $this->batchApplyUserAttributes($ldapRecords);
  742. return $this->fetchList($ldapRecords, (count($attr) > 1));
  743. }
  744. /**
  745. * provided with an array of LDAP user records the method will fetch the
  746. * user object and requests it to process the freshly fetched attributes and
  747. * and their values
  748. * @param array $ldapRecords
  749. */
  750. public function batchApplyUserAttributes(array $ldapRecords){
  751. $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
  752. foreach($ldapRecords as $userRecord) {
  753. if(!isset($userRecord[$displayNameAttribute])) {
  754. // displayName is obligatory
  755. continue;
  756. }
  757. $ocName = $this->dn2ocname($userRecord['dn'][0]);
  758. if($ocName === false) {
  759. continue;
  760. }
  761. $this->cacheUserExists($ocName);
  762. $user = $this->userManager->get($ocName);
  763. if($user instanceof OfflineUser) {
  764. $user->unmark();
  765. $user = $this->userManager->get($ocName);
  766. }
  767. if ($user !== null) {
  768. $user->processAttributes($userRecord);
  769. } else {
  770. \OC::$server->getLogger()->debug(
  771. "The ldap user manager returned null for $ocName",
  772. ['app'=>'user_ldap']
  773. );
  774. }
  775. }
  776. }
  777. /**
  778. * @param string $filter
  779. * @param string|string[] $attr
  780. * @param int $limit
  781. * @param int $offset
  782. * @return array
  783. */
  784. public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
  785. return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
  786. }
  787. /**
  788. * @param array $list
  789. * @param bool $manyAttributes
  790. * @return array
  791. */
  792. private function fetchList($list, $manyAttributes) {
  793. if(is_array($list)) {
  794. if($manyAttributes) {
  795. return $list;
  796. } else {
  797. $list = array_reduce($list, function($carry, $item) {
  798. $attribute = array_keys($item)[0];
  799. $carry[] = $item[$attribute][0];
  800. return $carry;
  801. }, array());
  802. return array_unique($list, SORT_LOCALE_STRING);
  803. }
  804. }
  805. //error cause actually, maybe throw an exception in future.
  806. return array();
  807. }
  808. /**
  809. * executes an LDAP search, optimized for Users
  810. * @param string $filter the LDAP filter for the search
  811. * @param string|string[] $attr optional, when a certain attribute shall be filtered out
  812. * @param integer $limit
  813. * @param integer $offset
  814. * @return array with the search result
  815. *
  816. * Executes an LDAP search
  817. */
  818. public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
  819. return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
  820. }
  821. /**
  822. * @param string $filter
  823. * @param string|string[] $attr
  824. * @param int $limit
  825. * @param int $offset
  826. * @return false|int
  827. */
  828. public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
  829. return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
  830. }
  831. /**
  832. * executes an LDAP search, optimized for Groups
  833. * @param string $filter the LDAP filter for the search
  834. * @param string|string[] $attr optional, when a certain attribute shall be filtered out
  835. * @param integer $limit
  836. * @param integer $offset
  837. * @return array with the search result
  838. *
  839. * Executes an LDAP search
  840. */
  841. public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
  842. return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
  843. }
  844. /**
  845. * returns the number of available groups
  846. * @param string $filter the LDAP search filter
  847. * @param string[] $attr optional
  848. * @param int|null $limit
  849. * @param int|null $offset
  850. * @return int|bool
  851. */
  852. public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
  853. return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
  854. }
  855. /**
  856. * returns the number of available objects on the base DN
  857. *
  858. * @param int|null $limit
  859. * @param int|null $offset
  860. * @return int|bool
  861. */
  862. public function countObjects($limit = null, $offset = null) {
  863. return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
  864. }
  865. /**
  866. * Returns the LDAP handler
  867. * @throws \OC\ServerNotAvailableException
  868. */
  869. /**
  870. * @return mixed
  871. * @throws \OC\ServerNotAvailableException
  872. */
  873. private function invokeLDAPMethod() {
  874. $arguments = func_get_args();
  875. $command = array_shift($arguments);
  876. $cr = array_shift($arguments);
  877. if (!method_exists($this->ldap, $command)) {
  878. return null;
  879. }
  880. array_unshift($arguments, $cr);
  881. // php no longer supports call-time pass-by-reference
  882. // thus cannot support controlPagedResultResponse as the third argument
  883. // is a reference
  884. $doMethod = function () use ($command, &$arguments) {
  885. if ($command == 'controlPagedResultResponse') {
  886. throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
  887. } else {
  888. return call_user_func_array(array($this->ldap, $command), $arguments);
  889. }
  890. };
  891. try {
  892. $ret = $doMethod();
  893. } catch (ServerNotAvailableException $e) {
  894. /* Server connection lost, attempt to reestablish it
  895. * Maybe implement exponential backoff?
  896. * This was enough to get solr indexer working which has large delays between LDAP fetches.
  897. */
  898. \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", \OCP\Util::DEBUG);
  899. $this->connection->resetConnectionResource();
  900. $cr = $this->connection->getConnectionResource();
  901. if(!$this->ldap->isResource($cr)) {
  902. // Seems like we didn't find any resource.
  903. \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
  904. throw $e;
  905. }
  906. $arguments[0] = array_pad([], count($arguments[0]), $cr);
  907. $ret = $doMethod();
  908. }
  909. return $ret;
  910. }
  911. /**
  912. * retrieved. Results will according to the order in the array.
  913. * @param int $limit optional, maximum results to be counted
  914. * @param int $offset optional, a starting point
  915. * @return array|false array with the search result as first value and pagedSearchOK as
  916. * second | false if not successful
  917. * @throws \OC\ServerNotAvailableException
  918. */
  919. private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
  920. if(!is_null($attr) && !is_array($attr)) {
  921. $attr = array(mb_strtolower($attr, 'UTF-8'));
  922. }
  923. // See if we have a resource, in case not cancel with message
  924. $cr = $this->connection->getConnectionResource();
  925. if(!$this->ldap->isResource($cr)) {
  926. // Seems like we didn't find any resource.
  927. // Return an empty array just like before.
  928. \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
  929. return false;
  930. }
  931. //check whether paged search should be attempted
  932. $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
  933. $linkResources = array_pad(array(), count($base), $cr);
  934. $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
  935. // cannot use $cr anymore, might have changed in the previous call!
  936. $error = $this->ldap->errno($this->connection->getConnectionResource());
  937. if(!is_array($sr) || $error !== 0) {
  938. \OCP\Util::writeLog('user_ldap', 'Attempt for Paging? '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
  939. return false;
  940. }
  941. return array($sr, $pagedSearchOK);
  942. }
  943. /**
  944. * processes an LDAP paged search operation
  945. * @param array $sr the array containing the LDAP search resources
  946. * @param string $filter the LDAP filter for the search
  947. * @param array $base an array containing the LDAP subtree(s) that shall be searched
  948. * @param int $iFoundItems number of results in the search operation
  949. * @param int $limit maximum results to be counted
  950. * @param int $offset a starting point
  951. * @param bool $pagedSearchOK whether a paged search has been executed
  952. * @param bool $skipHandling required for paged search when cookies to
  953. * prior results need to be gained
  954. * @return bool cookie validity, true if we have more pages, false otherwise.
  955. */
  956. private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
  957. $cookie = null;
  958. if($pagedSearchOK) {
  959. $cr = $this->connection->getConnectionResource();
  960. foreach($sr as $key => $res) {
  961. if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
  962. $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
  963. }
  964. }
  965. //browsing through prior pages to get the cookie for the new one
  966. if($skipHandling) {
  967. return false;
  968. }
  969. // if count is bigger, then the server does not support
  970. // paged search. Instead, he did a normal search. We set a
  971. // flag here, so the callee knows how to deal with it.
  972. if($iFoundItems <= $limit) {
  973. $this->pagedSearchedSuccessful = true;
  974. }
  975. } else {
  976. if(!is_null($limit)) {
  977. \OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
  978. }
  979. }
  980. /* ++ Fixing RHDS searches with pages with zero results ++
  981. * Return cookie status. If we don't have more pages, with RHDS
  982. * cookie is null, with openldap cookie is an empty string and
  983. * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
  984. */
  985. return !empty($cookie) || $cookie === '0';
  986. }
  987. /**
  988. * executes an LDAP search, but counts the results only
  989. * @param string $filter the LDAP filter for the search
  990. * @param array $base an array containing the LDAP subtree(s) that shall be searched
  991. * @param string|string[] $attr optional, array, one or more attributes that shall be
  992. * retrieved. Results will according to the order in the array.
  993. * @param int $limit optional, maximum results to be counted
  994. * @param int $offset optional, a starting point
  995. * @param bool $skipHandling indicates whether the pages search operation is
  996. * completed
  997. * @return int|false Integer or false if the search could not be initialized
  998. *
  999. */
  1000. private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
  1001. \OCP\Util::writeLog('user_ldap', 'Count filter: '.print_r($filter, true), \OCP\Util::DEBUG);
  1002. $limitPerPage = intval($this->connection->ldapPagingSize);
  1003. if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
  1004. $limitPerPage = $limit;
  1005. }
  1006. $counter = 0;
  1007. $count = null;
  1008. $this->connection->getConnectionResource();
  1009. do {
  1010. $search = $this->executeSearch($filter, $base, $attr,
  1011. $limitPerPage, $offset);
  1012. if($search === false) {
  1013. return $counter > 0 ? $counter : false;
  1014. }
  1015. list($sr, $pagedSearchOK) = $search;
  1016. /* ++ Fixing RHDS searches with pages with zero results ++
  1017. * countEntriesInSearchResults() method signature changed
  1018. * by removing $limit and &$hasHitLimit parameters
  1019. */
  1020. $count = $this->countEntriesInSearchResults($sr);
  1021. $counter += $count;
  1022. $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
  1023. $offset, $pagedSearchOK, $skipHandling);
  1024. $offset += $limitPerPage;
  1025. /* ++ Fixing RHDS searches with pages with zero results ++
  1026. * Continue now depends on $hasMorePages value
  1027. */
  1028. $continue = $pagedSearchOK && $hasMorePages;
  1029. } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
  1030. return $counter;
  1031. }
  1032. /**
  1033. * @param array $searchResults
  1034. * @return int
  1035. */
  1036. private function countEntriesInSearchResults($searchResults) {
  1037. $counter = 0;
  1038. foreach($searchResults as $res) {
  1039. $count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
  1040. $counter += $count;
  1041. }
  1042. return $counter;
  1043. }
  1044. /**
  1045. * Executes an LDAP search
  1046. * @param string $filter the LDAP filter for the search
  1047. * @param array $base an array containing the LDAP subtree(s) that shall be searched
  1048. * @param string|string[] $attr optional, array, one or more attributes that shall be
  1049. * @param int $limit
  1050. * @param int $offset
  1051. * @param bool $skipHandling
  1052. * @return array with the search result
  1053. */
  1054. public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
  1055. if($limit <= 0) {
  1056. //otherwise search will fail
  1057. $limit = null;
  1058. }
  1059. /* ++ Fixing RHDS searches with pages with zero results ++
  1060. * As we can have pages with zero results and/or pages with less
  1061. * than $limit results but with a still valid server 'cookie',
  1062. * loops through until we get $continue equals true and
  1063. * $findings['count'] < $limit
  1064. */
  1065. $findings = array();
  1066. $savedoffset = $offset;
  1067. do {
  1068. $search = $this->executeSearch($filter, $base, $attr, $limit, $offset);
  1069. if($search === false) {
  1070. return array();
  1071. }
  1072. list($sr, $pagedSearchOK) = $search;
  1073. $cr = $this->connection->getConnectionResource();
  1074. if($skipHandling) {
  1075. //i.e. result do not need to be fetched, we just need the cookie
  1076. //thus pass 1 or any other value as $iFoundItems because it is not
  1077. //used
  1078. $this->processPagedSearchStatus($sr, $filter, $base, 1, $limit,
  1079. $offset, $pagedSearchOK,
  1080. $skipHandling);
  1081. return array();
  1082. }
  1083. foreach($sr as $res) {
  1084. $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
  1085. }
  1086. $continue = $this->processPagedSearchStatus($sr, $filter, $base, $findings['count'],
  1087. $limit, $offset, $pagedSearchOK,
  1088. $skipHandling);
  1089. $offset += $limit;
  1090. } while ($continue && $pagedSearchOK && $findings['count'] < $limit);
  1091. // reseting offset
  1092. $offset = $savedoffset;
  1093. // if we're here, probably no connection resource is returned.
  1094. // to make Nextcloud behave nicely, we simply give back an empty array.
  1095. if(is_null($findings)) {
  1096. return array();
  1097. }
  1098. if(!is_null($attr)) {
  1099. $selection = array();
  1100. $i = 0;
  1101. foreach($findings as $item) {
  1102. if(!is_array($item)) {
  1103. continue;
  1104. }
  1105. $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
  1106. foreach($attr as $key) {
  1107. $key = mb_strtolower($key, 'UTF-8');
  1108. if(isset($item[$key])) {
  1109. if(is_array($item[$key]) && isset($item[$key]['count'])) {
  1110. unset($item[$key]['count']);
  1111. }
  1112. if($key !== 'dn') {
  1113. $selection[$i][$key] = $this->resemblesDN($key) ?
  1114. $this->helper->sanitizeDN($item[$key])
  1115. : $item[$key];
  1116. } else {
  1117. $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
  1118. }
  1119. }
  1120. }
  1121. $i++;
  1122. }
  1123. $findings = $selection;
  1124. }
  1125. //we slice the findings, when
  1126. //a) paged search unsuccessful, though attempted
  1127. //b) no paged search, but limit set
  1128. if((!$this->getPagedSearchResultState()
  1129. && $pagedSearchOK)
  1130. || (
  1131. !$pagedSearchOK
  1132. && !is_null($limit)
  1133. )
  1134. ) {
  1135. $findings = array_slice($findings, intval($offset), $limit);
  1136. }
  1137. return $findings;
  1138. }
  1139. /**
  1140. * @param string $name
  1141. * @return bool|mixed|string
  1142. */
  1143. public function sanitizeUsername($name) {
  1144. if($this->connection->ldapIgnoreNamingRules) {
  1145. return $name;
  1146. }
  1147. // Transliteration
  1148. // latin characters to ASCII
  1149. $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
  1150. // Replacements
  1151. $name = str_replace(' ', '_', $name);
  1152. // Every remaining disallowed characters will be removed
  1153. $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
  1154. return $name;
  1155. }
  1156. /**
  1157. * escapes (user provided) parts for LDAP filter
  1158. * @param string $input, the provided value
  1159. * @param bool $allowAsterisk whether in * at the beginning should be preserved
  1160. * @return string the escaped string
  1161. */
  1162. public function escapeFilterPart($input, $allowAsterisk = false) {
  1163. $asterisk = '';
  1164. if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
  1165. $asterisk = '*';
  1166. $input = mb_substr($input, 1, null, 'UTF-8');
  1167. }
  1168. $search = array('*', '\\', '(', ')');
  1169. $replace = array('\\*', '\\\\', '\\(', '\\)');
  1170. return $asterisk . str_replace($search, $replace, $input);
  1171. }
  1172. /**
  1173. * combines the input filters with AND
  1174. * @param string[] $filters the filters to connect
  1175. * @return string the combined filter
  1176. */
  1177. public function combineFilterWithAnd($filters) {
  1178. return $this->combineFilter($filters, '&');
  1179. }
  1180. /**
  1181. * combines the input filters with OR
  1182. * @param string[] $filters the filters to connect
  1183. * @return string the combined filter
  1184. * Combines Filter arguments with OR
  1185. */
  1186. public function combineFilterWithOr($filters) {
  1187. return $this->combineFilter($filters, '|');
  1188. }
  1189. /**
  1190. * combines the input filters with given operator
  1191. * @param string[] $filters the filters to connect
  1192. * @param string $operator either & or |
  1193. * @return string the combined filter
  1194. */
  1195. private function combineFilter($filters, $operator) {
  1196. $combinedFilter = '('.$operator;
  1197. foreach($filters as $filter) {
  1198. if ($filter !== '' && $filter[0] !== '(') {
  1199. $filter = '('.$filter.')';
  1200. }
  1201. $combinedFilter.=$filter;
  1202. }
  1203. $combinedFilter.=')';
  1204. return $combinedFilter;
  1205. }
  1206. /**
  1207. * creates a filter part for to perform search for users
  1208. * @param string $search the search term
  1209. * @return string the final filter part to use in LDAP searches
  1210. */
  1211. public function getFilterPartForUserSearch($search) {
  1212. return $this->getFilterPartForSearch($search,
  1213. $this->connection->ldapAttributesForUserSearch,
  1214. $this->connection->ldapUserDisplayName);
  1215. }
  1216. /**
  1217. * creates a filter part for to perform search for groups
  1218. * @param string $search the search term
  1219. * @return string the final filter part to use in LDAP searches
  1220. */
  1221. public function getFilterPartForGroupSearch($search) {
  1222. return $this->getFilterPartForSearch($search,
  1223. $this->connection->ldapAttributesForGroupSearch,
  1224. $this->connection->ldapGroupDisplayName);
  1225. }
  1226. /**
  1227. * creates a filter part for searches by splitting up the given search
  1228. * string into single words
  1229. * @param string $search the search term
  1230. * @param string[] $searchAttributes needs to have at least two attributes,
  1231. * otherwise it does not make sense :)
  1232. * @return string the final filter part to use in LDAP searches
  1233. * @throws \Exception
  1234. */
  1235. private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
  1236. if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
  1237. throw new \Exception('searchAttributes must be an array with at least two string');
  1238. }
  1239. $searchWords = explode(' ', trim($search));
  1240. $wordFilters = array();
  1241. foreach($searchWords as $word) {
  1242. $word = $this->prepareSearchTerm($word);
  1243. //every word needs to appear at least once
  1244. $wordMatchOneAttrFilters = array();
  1245. foreach($searchAttributes as $attr) {
  1246. $wordMatchOneAttrFilters[] = $attr . '=' . $word;
  1247. }
  1248. $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
  1249. }
  1250. return $this->combineFilterWithAnd($wordFilters);
  1251. }
  1252. /**
  1253. * creates a filter part for searches
  1254. * @param string $search the search term
  1255. * @param string[]|null $searchAttributes
  1256. * @param string $fallbackAttribute a fallback attribute in case the user
  1257. * did not define search attributes. Typically the display name attribute.
  1258. * @return string the final filter part to use in LDAP searches
  1259. */
  1260. private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
  1261. $filter = array();
  1262. $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
  1263. if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
  1264. try {
  1265. return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
  1266. } catch(\Exception $e) {
  1267. \OCP\Util::writeLog(
  1268. 'user_ldap',
  1269. 'Creating advanced filter for search failed, falling back to simple method.',
  1270. \OCP\Util::INFO
  1271. );
  1272. }
  1273. }
  1274. $search = $this->prepareSearchTerm($search);
  1275. if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
  1276. if ($fallbackAttribute === '') {
  1277. return '';
  1278. }
  1279. $filter[] = $fallbackAttribute . '=' . $search;
  1280. } else {
  1281. foreach($searchAttributes as $attribute) {
  1282. $filter[] = $attribute . '=' . $search;
  1283. }
  1284. }
  1285. if(count($filter) === 1) {
  1286. return '('.$filter[0].')';
  1287. }
  1288. return $this->combineFilterWithOr($filter);
  1289. }
  1290. /**
  1291. * returns the search term depending on whether we are allowed
  1292. * list users found by ldap with the current input appended by
  1293. * a *
  1294. * @return string
  1295. */
  1296. private function prepareSearchTerm($term) {
  1297. $config = \OC::$server->getConfig();
  1298. $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
  1299. $result = $term;
  1300. if ($term === '') {
  1301. $result = '*';
  1302. } else if ($allowEnum !== 'no') {
  1303. $result = $term . '*';
  1304. }
  1305. return $result;
  1306. }
  1307. /**
  1308. * returns the filter used for counting users
  1309. * @return string
  1310. */
  1311. public function getFilterForUserCount() {
  1312. $filter = $this->combineFilterWithAnd(array(
  1313. $this->connection->ldapUserFilter,
  1314. $this->connection->ldapUserDisplayName . '=*'
  1315. ));
  1316. return $filter;
  1317. }
  1318. /**
  1319. * @param string $name
  1320. * @param string $password
  1321. * @return bool
  1322. */
  1323. public function areCredentialsValid($name, $password) {
  1324. $name = $this->helper->DNasBaseParameter($name);
  1325. $testConnection = clone $this->connection;
  1326. $credentials = array(
  1327. 'ldapAgentName' => $name,
  1328. 'ldapAgentPassword' => $password
  1329. );
  1330. if(!$testConnection->setConfiguration($credentials)) {
  1331. return false;
  1332. }
  1333. return $testConnection->bind();
  1334. }
  1335. /**
  1336. * reverse lookup of a DN given a known UUID
  1337. *
  1338. * @param string $uuid
  1339. * @return string
  1340. * @throws \Exception
  1341. */
  1342. public function getUserDnByUuid($uuid) {
  1343. $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
  1344. $filter = $this->connection->ldapUserFilter;
  1345. $base = $this->connection->ldapBaseUsers;
  1346. if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
  1347. // Sacrebleu! The UUID attribute is unknown :( We need first an
  1348. // existing DN to be able to reliably detect it.
  1349. $result = $this->search($filter, $base, ['dn'], 1);
  1350. if(!isset($result[0]) || !isset($result[0]['dn'])) {
  1351. throw new \Exception('Cannot determine UUID attribute');
  1352. }
  1353. $dn = $result[0]['dn'][0];
  1354. if(!$this->detectUuidAttribute($dn, true)) {
  1355. throw new \Exception('Cannot determine UUID attribute');
  1356. }
  1357. } else {
  1358. // The UUID attribute is either known or an override is given.
  1359. // By calling this method we ensure that $this->connection->$uuidAttr
  1360. // is definitely set
  1361. if(!$this->detectUuidAttribute('', true)) {
  1362. throw new \Exception('Cannot determine UUID attribute');
  1363. }
  1364. }
  1365. $uuidAttr = $this->connection->ldapUuidUserAttribute;
  1366. if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
  1367. $uuid = $this->formatGuid2ForFilterUser($uuid);
  1368. }
  1369. $filter = $uuidAttr . '=' . $uuid;
  1370. $result = $this->searchUsers($filter, ['dn'], 2);
  1371. if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
  1372. // we put the count into account to make sure that this is
  1373. // really unique
  1374. return $result[0]['dn'][0];
  1375. }
  1376. throw new \Exception('Cannot determine UUID attribute');
  1377. }
  1378. /**
  1379. * auto-detects the directory's UUID attribute
  1380. * @param string $dn a known DN used to check against
  1381. * @param bool $isUser
  1382. * @param bool $force the detection should be run, even if it is not set to auto
  1383. * @return bool true on success, false otherwise
  1384. */
  1385. private function detectUuidAttribute($dn, $isUser = true, $force = false) {
  1386. if($isUser) {
  1387. $uuidAttr = 'ldapUuidUserAttribute';
  1388. $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
  1389. } else {
  1390. $uuidAttr = 'ldapUuidGroupAttribute';
  1391. $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
  1392. }
  1393. if(($this->connection->$uuidAttr !== 'auto') && !$force) {
  1394. return true;
  1395. }
  1396. if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
  1397. $this->connection->$uuidAttr = $uuidOverride;
  1398. return true;
  1399. }
  1400. // for now, supported attributes are entryUUID, nsuniqueid, objectGUID, ipaUniqueID
  1401. $testAttributes = array('entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid');
  1402. foreach($testAttributes as $attribute) {
  1403. $value = $this->readAttribute($dn, $attribute);
  1404. if(is_array($value) && isset($value[0]) && !empty($value[0])) {
  1405. \OCP\Util::writeLog('user_ldap',
  1406. 'Setting '.$attribute.' as '.$uuidAttr,
  1407. \OCP\Util::DEBUG);
  1408. $this->connection->$uuidAttr = $attribute;
  1409. return true;
  1410. }
  1411. }
  1412. \OCP\Util::writeLog('user_ldap',
  1413. 'Could not autodetect the UUID attribute',
  1414. \OCP\Util::ERROR);
  1415. return false;
  1416. }
  1417. /**
  1418. * @param string $dn
  1419. * @param bool $isUser
  1420. * @return string|bool
  1421. */
  1422. public function getUUID($dn, $isUser = true) {
  1423. if($isUser) {
  1424. $uuidAttr = 'ldapUuidUserAttribute';
  1425. $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
  1426. } else {
  1427. $uuidAttr = 'ldapUuidGroupAttribute';
  1428. $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
  1429. }
  1430. $uuid = false;
  1431. if($this->detectUuidAttribute($dn, $isUser)) {
  1432. $uuid = $this->readAttribute($dn, $this->connection->$uuidAttr);
  1433. if( !is_array($uuid)
  1434. && $uuidOverride !== ''
  1435. && $this->detectUuidAttribute($dn, $isUser, true)) {
  1436. $uuid = $this->readAttribute($dn,
  1437. $this->connection->$uuidAttr);
  1438. }
  1439. if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
  1440. $uuid = $uuid[0];
  1441. }
  1442. }
  1443. return $uuid;
  1444. }
  1445. /**
  1446. * converts a binary ObjectGUID into a string representation
  1447. * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
  1448. * @return string
  1449. * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
  1450. */
  1451. private function convertObjectGUID2Str($oguid) {
  1452. $hex_guid = bin2hex($oguid);
  1453. $hex_guid_to_guid_str = '';
  1454. for($k = 1; $k <= 4; ++$k) {
  1455. $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
  1456. }
  1457. $hex_guid_to_guid_str .= '-';
  1458. for($k = 1; $k <= 2; ++$k) {
  1459. $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
  1460. }
  1461. $hex_guid_to_guid_str .= '-';
  1462. for($k = 1; $k <= 2; ++$k) {
  1463. $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
  1464. }
  1465. $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
  1466. $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
  1467. return strtoupper($hex_guid_to_guid_str);
  1468. }
  1469. /**
  1470. * the first three blocks of the string-converted GUID happen to be in
  1471. * reverse order. In order to use it in a filter, this needs to be
  1472. * corrected. Furthermore the dashes need to be replaced and \\ preprended
  1473. * to every two hax figures.
  1474. *
  1475. * If an invalid string is passed, it will be returned without change.
  1476. *
  1477. * @param string $guid
  1478. * @return string
  1479. */
  1480. public function formatGuid2ForFilterUser($guid) {
  1481. if(!is_string($guid)) {
  1482. throw new \InvalidArgumentException('String expected');
  1483. }
  1484. $blocks = explode('-', $guid);
  1485. if(count($blocks) !== 5) {
  1486. /*
  1487. * Why not throw an Exception instead? This method is a utility
  1488. * called only when trying to figure out whether a "missing" known
  1489. * LDAP user was or was not renamed on the LDAP server. And this
  1490. * even on the use case that a reverse lookup is needed (UUID known,
  1491. * not DN), i.e. when finding users (search dialog, users page,
  1492. * login, …) this will not be fired. This occurs only if shares from
  1493. * a users are supposed to be mounted who cannot be found. Throwing
  1494. * an exception here would kill the experience for a valid, acting
  1495. * user. Instead we write a log message.
  1496. */
  1497. \OC::$server->getLogger()->info(
  1498. 'Passed string does not resemble a valid GUID. Known UUID ' .
  1499. '({uuid}) probably does not match UUID configuration.',
  1500. [ 'app' => 'user_ldap', 'uuid' => $guid ]
  1501. );
  1502. return $guid;
  1503. }
  1504. for($i=0; $i < 3; $i++) {
  1505. $pairs = str_split($blocks[$i], 2);
  1506. $pairs = array_reverse($pairs);
  1507. $blocks[$i] = implode('', $pairs);
  1508. }
  1509. for($i=0; $i < 5; $i++) {
  1510. $pairs = str_split($blocks[$i], 2);
  1511. $blocks[$i] = '\\' . implode('\\', $pairs);
  1512. }
  1513. return implode('', $blocks);
  1514. }
  1515. /**
  1516. * gets a SID of the domain of the given dn
  1517. * @param string $dn
  1518. * @return string|bool
  1519. */
  1520. public function getSID($dn) {
  1521. $domainDN = $this->getDomainDNFromDN($dn);
  1522. $cacheKey = 'getSID-'.$domainDN;
  1523. $sid = $this->connection->getFromCache($cacheKey);
  1524. if(!is_null($sid)) {
  1525. return $sid;
  1526. }
  1527. $objectSid = $this->readAttribute($domainDN, 'objectsid');
  1528. if(!is_array($objectSid) || empty($objectSid)) {
  1529. $this->connection->writeToCache($cacheKey, false);
  1530. return false;
  1531. }
  1532. $domainObjectSid = $this->convertSID2Str($objectSid[0]);
  1533. $this->connection->writeToCache($cacheKey, $domainObjectSid);
  1534. return $domainObjectSid;
  1535. }
  1536. /**
  1537. * converts a binary SID into a string representation
  1538. * @param string $sid
  1539. * @return string
  1540. */
  1541. public function convertSID2Str($sid) {
  1542. // The format of a SID binary string is as follows:
  1543. // 1 byte for the revision level
  1544. // 1 byte for the number n of variable sub-ids
  1545. // 6 bytes for identifier authority value
  1546. // n*4 bytes for n sub-ids
  1547. //
  1548. // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
  1549. // Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
  1550. $revision = ord($sid[0]);
  1551. $numberSubID = ord($sid[1]);
  1552. $subIdStart = 8; // 1 + 1 + 6
  1553. $subIdLength = 4;
  1554. if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
  1555. // Incorrect number of bytes present.
  1556. return '';
  1557. }
  1558. // 6 bytes = 48 bits can be represented using floats without loss of
  1559. // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
  1560. $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
  1561. $subIDs = array();
  1562. for ($i = 0; $i < $numberSubID; $i++) {
  1563. $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
  1564. $subIDs[] = sprintf('%u', $subID[1]);
  1565. }
  1566. // Result for example above: S-1-5-21-249921958-728525901-1594176202
  1567. return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
  1568. }
  1569. /**
  1570. * checks if the given DN is part of the given base DN(s)
  1571. * @param string $dn the DN
  1572. * @param string[] $bases array containing the allowed base DN or DNs
  1573. * @return bool
  1574. */
  1575. public function isDNPartOfBase($dn, $bases) {
  1576. $belongsToBase = false;
  1577. $bases = $this->helper->sanitizeDN($bases);
  1578. foreach($bases as $base) {
  1579. $belongsToBase = true;
  1580. if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
  1581. $belongsToBase = false;
  1582. }
  1583. if($belongsToBase) {
  1584. break;
  1585. }
  1586. }
  1587. return $belongsToBase;
  1588. }
  1589. /**
  1590. * resets a running Paged Search operation
  1591. */
  1592. private function abandonPagedSearch() {
  1593. if($this->connection->hasPagedResultSupport) {
  1594. $cr = $this->connection->getConnectionResource();
  1595. $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
  1596. $this->getPagedSearchResultState();
  1597. $this->lastCookie = '';
  1598. $this->cookies = array();
  1599. }
  1600. }
  1601. /**
  1602. * get a cookie for the next LDAP paged search
  1603. * @param string $base a string with the base DN for the search
  1604. * @param string $filter the search filter to identify the correct search
  1605. * @param int $limit the limit (or 'pageSize'), to identify the correct search well
  1606. * @param int $offset the offset for the new search to identify the correct search really good
  1607. * @return string containing the key or empty if none is cached
  1608. */
  1609. private function getPagedResultCookie($base, $filter, $limit, $offset) {
  1610. if($offset === 0) {
  1611. return '';
  1612. }
  1613. $offset -= $limit;
  1614. //we work with cache here
  1615. $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
  1616. $cookie = '';
  1617. if(isset($this->cookies[$cacheKey])) {
  1618. $cookie = $this->cookies[$cacheKey];
  1619. if(is_null($cookie)) {
  1620. $cookie = '';
  1621. }
  1622. }
  1623. return $cookie;
  1624. }
  1625. /**
  1626. * checks whether an LDAP paged search operation has more pages that can be
  1627. * retrieved, typically when offset and limit are provided.
  1628. *
  1629. * Be very careful to use it: the last cookie value, which is inspected, can
  1630. * be reset by other operations. Best, call it immediately after a search(),
  1631. * searchUsers() or searchGroups() call. count-methods are probably safe as
  1632. * well. Don't rely on it with any fetchList-method.
  1633. * @return bool
  1634. */
  1635. public function hasMoreResults() {
  1636. if(!$this->connection->hasPagedResultSupport) {
  1637. return false;
  1638. }
  1639. if(empty($this->lastCookie) && $this->lastCookie !== '0') {
  1640. // as in RFC 2696, when all results are returned, the cookie will
  1641. // be empty.
  1642. return false;
  1643. }
  1644. return true;
  1645. }
  1646. /**
  1647. * set a cookie for LDAP paged search run
  1648. * @param string $base a string with the base DN for the search
  1649. * @param string $filter the search filter to identify the correct search
  1650. * @param int $limit the limit (or 'pageSize'), to identify the correct search well
  1651. * @param int $offset the offset for the run search to identify the correct search really good
  1652. * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
  1653. * @return void
  1654. */
  1655. private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
  1656. // allow '0' for 389ds
  1657. if(!empty($cookie) || $cookie === '0') {
  1658. $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
  1659. $this->cookies[$cacheKey] = $cookie;
  1660. $this->lastCookie = $cookie;
  1661. }
  1662. }
  1663. /**
  1664. * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
  1665. * @return boolean|null true on success, null or false otherwise
  1666. */
  1667. public function getPagedSearchResultState() {
  1668. $result = $this->pagedSearchedSuccessful;
  1669. $this->pagedSearchedSuccessful = null;
  1670. return $result;
  1671. }
  1672. /**
  1673. * Prepares a paged search, if possible
  1674. * @param string $filter the LDAP filter for the search
  1675. * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
  1676. * @param string[] $attr optional, when a certain attribute shall be filtered outside
  1677. * @param int $limit
  1678. * @param int $offset
  1679. * @return bool|true
  1680. */
  1681. private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
  1682. $pagedSearchOK = false;
  1683. if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
  1684. $offset = intval($offset); //can be null
  1685. \OCP\Util::writeLog('user_ldap',
  1686. 'initializing paged search for Filter '.$filter.' base '.print_r($bases, true)
  1687. .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
  1688. \OCP\Util::DEBUG);
  1689. //get the cookie from the search for the previous search, required by LDAP
  1690. foreach($bases as $base) {
  1691. $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
  1692. if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
  1693. // no cookie known, although the offset is not 0. Maybe cache run out. We need
  1694. // to start all over *sigh* (btw, Dear Reader, did you know LDAP paged
  1695. // searching was designed by MSFT?)
  1696. // Lukas: No, but thanks to reading that source I finally know!
  1697. // '0' is valid, because 389ds
  1698. $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
  1699. //a bit recursive, $offset of 0 is the exit
  1700. \OCP\Util::writeLog('user_ldap', 'Looking for cookie L/O '.$limit.'/'.$reOffset, \OCP\Util::INFO);
  1701. $this->search($filter, array($base), $attr, $limit, $reOffset, true);
  1702. $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
  1703. //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
  1704. //TODO: remember this, probably does not change in the next request...
  1705. if(empty($cookie) && $cookie !== '0') {
  1706. // '0' is valid, because 389ds
  1707. $cookie = null;
  1708. }
  1709. }
  1710. if(!is_null($cookie)) {
  1711. //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
  1712. $this->abandonPagedSearch();
  1713. $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
  1714. $this->connection->getConnectionResource(), $limit,
  1715. false, $cookie);
  1716. if(!$pagedSearchOK) {
  1717. return false;
  1718. }
  1719. \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
  1720. } else {
  1721. \OCP\Util::writeLog('user_ldap',
  1722. 'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
  1723. \OCP\Util::INFO);
  1724. }
  1725. }
  1726. /* ++ Fixing RHDS searches with pages with zero results ++
  1727. * We coudn't get paged searches working with our RHDS for login ($limit = 0),
  1728. * due to pages with zero results.
  1729. * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
  1730. * if we don't have a previous paged search.
  1731. */
  1732. } else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
  1733. // a search without limit was requested. However, if we do use
  1734. // Paged Search once, we always must do it. This requires us to
  1735. // initialize it with the configured page size.
  1736. $this->abandonPagedSearch();
  1737. // in case someone set it to 0 … use 500, otherwise no results will
  1738. // be returned.
  1739. $pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
  1740. $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
  1741. $this->connection->getConnectionResource(),
  1742. $pageSize, false, '');
  1743. }
  1744. return $pagedSearchOK;
  1745. }
  1746. }