PageRenderTime 36ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/libraries/openid/Auth/OpenID/FileStore.php

https://bitbucket.org/StasPiv/playzone
PHP | 621 lines | 406 code | 80 blank | 135 comment | 66 complexity | 9de8c5906961a3e9f07323b41079b1f4 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * This file supplies a Memcached store backend for OpenID servers and
  4. * consumers.
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * LICENSE: See the COPYING file included in this distribution.
  9. *
  10. * @package OpenID
  11. * @author JanRain, Inc. <openid@janrain.com>
  12. * @copyright 2005-2008 Janrain, Inc.
  13. * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
  14. */
  15. // Do not allow direct access
  16. defined( '_JEXEC' ) or die( 'Restricted access' );
  17. /**
  18. * Require base class for creating a new interface.
  19. */
  20. require_once 'Auth/OpenID.php';
  21. require_once 'Auth/OpenID/Interface.php';
  22. require_once 'Auth/OpenID/HMAC.php';
  23. require_once 'Auth/OpenID/Nonce.php';
  24. /**
  25. * This is a filesystem-based store for OpenID associations and
  26. * nonces. This store should be safe for use in concurrent systems on
  27. * both windows and unix (excluding NFS filesystems). There are a
  28. * couple race conditions in the system, but those failure cases have
  29. * been set up in such a way that the worst-case behavior is someone
  30. * having to try to log in a second time.
  31. *
  32. * Most of the methods of this class are implementation details.
  33. * People wishing to just use this store need only pay attention to
  34. * the constructor.
  35. *
  36. * @package OpenID
  37. */
  38. class Auth_OpenID_FileStore extends Auth_OpenID_OpenIDStore {
  39. /**
  40. * Initializes a new {@link Auth_OpenID_FileStore}. This
  41. * initializes the nonce and association directories, which are
  42. * subdirectories of the directory passed in.
  43. *
  44. * @param string $directory This is the directory to put the store
  45. * directories in.
  46. */
  47. function Auth_OpenID_FileStore($directory)
  48. {
  49. if (!Auth_OpenID::ensureDir($directory)) {
  50. trigger_error('Not a directory and failed to create: '
  51. . $directory, E_USER_ERROR);
  52. }
  53. $directory = realpath($directory);
  54. $this->directory = $directory;
  55. $this->active = true;
  56. $this->nonce_dir = $directory . DIRECTORY_SEPARATOR . 'nonces';
  57. $this->association_dir = $directory . DIRECTORY_SEPARATOR .
  58. 'associations';
  59. // Temp dir must be on the same filesystem as the assciations
  60. // $directory.
  61. $this->temp_dir = $directory . DIRECTORY_SEPARATOR . 'temp';
  62. $this->max_nonce_age = 6 * 60 * 60; // Six hours, in seconds
  63. if (!$this->_setup()) {
  64. trigger_error('Failed to initialize OpenID file store in ' .
  65. $directory, E_USER_ERROR);
  66. }
  67. }
  68. function destroy()
  69. {
  70. Auth_OpenID_FileStore::_rmtree($this->directory);
  71. $this->active = false;
  72. }
  73. /**
  74. * Make sure that the directories in which we store our data
  75. * exist.
  76. *
  77. * @access private
  78. */
  79. function _setup()
  80. {
  81. return (Auth_OpenID::ensureDir($this->nonce_dir) &&
  82. Auth_OpenID::ensureDir($this->association_dir) &&
  83. Auth_OpenID::ensureDir($this->temp_dir));
  84. }
  85. /**
  86. * Create a temporary file on the same filesystem as
  87. * $this->association_dir.
  88. *
  89. * The temporary directory should not be cleaned if there are any
  90. * processes using the store. If there is no active process using
  91. * the store, it is safe to remove all of the files in the
  92. * temporary directory.
  93. *
  94. * @return array ($fd, $filename)
  95. * @access private
  96. */
  97. function _mktemp()
  98. {
  99. $name = Auth_OpenID_FileStore::_mkstemp($dir = $this->temp_dir);
  100. $file_obj = @fopen($name, 'wb');
  101. if ($file_obj !== false) {
  102. return array($file_obj, $name);
  103. } else {
  104. Auth_OpenID_FileStore::_removeIfPresent($name);
  105. }
  106. }
  107. function cleanupNonces()
  108. {
  109. global $Auth_OpenID_SKEW;
  110. $nonces = Auth_OpenID_FileStore::_listdir($this->nonce_dir);
  111. $now = time();
  112. $removed = 0;
  113. // Check all nonces for expiry
  114. foreach ($nonces as $nonce_fname) {
  115. $base = basename($nonce_fname);
  116. $parts = explode('-', $base, 2);
  117. $timestamp = $parts[0];
  118. $timestamp = intval($timestamp, 16);
  119. if (abs($timestamp - $now) > $Auth_OpenID_SKEW) {
  120. Auth_OpenID_FileStore::_removeIfPresent($nonce_fname);
  121. $removed += 1;
  122. }
  123. }
  124. return $removed;
  125. }
  126. /**
  127. * Create a unique filename for a given server url and
  128. * handle. This implementation does not assume anything about the
  129. * format of the handle. The filename that is returned will
  130. * contain the domain name from the server URL for ease of human
  131. * inspection of the data directory.
  132. *
  133. * @return string $filename
  134. */
  135. function getAssociationFilename($server_url, $handle)
  136. {
  137. if (!$this->active) {
  138. trigger_error("FileStore no longer active", E_USER_ERROR);
  139. return null;
  140. }
  141. if (strpos($server_url, '://') === false) {
  142. trigger_error(sprintf("Bad server URL: %s", $server_url),
  143. E_USER_WARNING);
  144. return null;
  145. }
  146. list($proto, $rest) = explode('://', $server_url, 2);
  147. $parts = explode('/', $rest);
  148. $domain = Auth_OpenID_FileStore::_filenameEscape($parts[0]);
  149. $url_hash = Auth_OpenID_FileStore::_safe64($server_url);
  150. if ($handle) {
  151. $handle_hash = Auth_OpenID_FileStore::_safe64($handle);
  152. } else {
  153. $handle_hash = '';
  154. }
  155. $filename = sprintf('%s-%s-%s-%s', $proto, $domain, $url_hash,
  156. $handle_hash);
  157. return $this->association_dir. DIRECTORY_SEPARATOR . $filename;
  158. }
  159. /**
  160. * Store an association in the association directory.
  161. */
  162. function storeAssociation($server_url, $association)
  163. {
  164. if (!$this->active) {
  165. trigger_error("FileStore no longer active", E_USER_ERROR);
  166. return false;
  167. }
  168. $association_s = $association->serialize();
  169. $filename = $this->getAssociationFilename($server_url,
  170. $association->handle);
  171. list($tmp_file, $tmp) = $this->_mktemp();
  172. if (!$tmp_file) {
  173. trigger_error("_mktemp didn't return a valid file descriptor",
  174. E_USER_WARNING);
  175. return false;
  176. }
  177. fwrite($tmp_file, $association_s);
  178. fflush($tmp_file);
  179. fclose($tmp_file);
  180. if (@rename($tmp, $filename)) {
  181. return true;
  182. } else {
  183. // In case we are running on Windows, try unlinking the
  184. // file in case it exists.
  185. @unlink($filename);
  186. // Now the target should not exist. Try renaming again,
  187. // giving up if it fails.
  188. if (@rename($tmp, $filename)) {
  189. return true;
  190. }
  191. }
  192. // If there was an error, don't leave the temporary file
  193. // around.
  194. Auth_OpenID_FileStore::_removeIfPresent($tmp);
  195. return false;
  196. }
  197. /**
  198. * Retrieve an association. If no handle is specified, return the
  199. * association with the most recent issue time.
  200. *
  201. * @return mixed $association
  202. */
  203. function getAssociation($server_url, $handle = null)
  204. {
  205. if (!$this->active) {
  206. trigger_error("FileStore no longer active", E_USER_ERROR);
  207. return null;
  208. }
  209. if ($handle === null) {
  210. $handle = '';
  211. }
  212. // The filename with the empty handle is a prefix of all other
  213. // associations for the given server URL.
  214. $filename = $this->getAssociationFilename($server_url, $handle);
  215. if ($handle) {
  216. return $this->_getAssociation($filename);
  217. } else {
  218. $association_files =
  219. Auth_OpenID_FileStore::_listdir($this->association_dir);
  220. $matching_files = array();
  221. // strip off the path to do the comparison
  222. $name = basename($filename);
  223. foreach ($association_files as $association_file) {
  224. $base = basename($association_file);
  225. if (strpos($base, $name) === 0) {
  226. $matching_files[] = $association_file;
  227. }
  228. }
  229. $matching_associations = array();
  230. // read the matching files and sort by time issued
  231. foreach ($matching_files as $full_name) {
  232. $association = $this->_getAssociation($full_name);
  233. if ($association !== null) {
  234. $matching_associations[] = array($association->issued,
  235. $association);
  236. }
  237. }
  238. $issued = array();
  239. $assocs = array();
  240. foreach ($matching_associations as $key => $assoc) {
  241. $issued[$key] = $assoc[0];
  242. $assocs[$key] = $assoc[1];
  243. }
  244. array_multisort($issued, SORT_DESC, $assocs, SORT_DESC,
  245. $matching_associations);
  246. // return the most recently issued one.
  247. if ($matching_associations) {
  248. list($issued, $assoc) = $matching_associations[0];
  249. return $assoc;
  250. } else {
  251. return null;
  252. }
  253. }
  254. }
  255. /**
  256. * @access private
  257. */
  258. function _getAssociation($filename)
  259. {
  260. if (!$this->active) {
  261. trigger_error("FileStore no longer active", E_USER_ERROR);
  262. return null;
  263. }
  264. $assoc_file = @fopen($filename, 'rb');
  265. if ($assoc_file === false) {
  266. return null;
  267. }
  268. $assoc_s = fread($assoc_file, filesize($filename));
  269. fclose($assoc_file);
  270. if (!$assoc_s) {
  271. return null;
  272. }
  273. $association =
  274. Auth_OpenID_Association::deserialize('Auth_OpenID_Association',
  275. $assoc_s);
  276. if (!$association) {
  277. Auth_OpenID_FileStore::_removeIfPresent($filename);
  278. return null;
  279. }
  280. if ($association->getExpiresIn() == 0) {
  281. Auth_OpenID_FileStore::_removeIfPresent($filename);
  282. return null;
  283. } else {
  284. return $association;
  285. }
  286. }
  287. /**
  288. * Remove an association if it exists. Do nothing if it does not.
  289. *
  290. * @return bool $success
  291. */
  292. function removeAssociation($server_url, $handle)
  293. {
  294. if (!$this->active) {
  295. trigger_error("FileStore no longer active", E_USER_ERROR);
  296. return null;
  297. }
  298. $assoc = $this->getAssociation($server_url, $handle);
  299. if ($assoc === null) {
  300. return false;
  301. } else {
  302. $filename = $this->getAssociationFilename($server_url, $handle);
  303. return Auth_OpenID_FileStore::_removeIfPresent($filename);
  304. }
  305. }
  306. /**
  307. * Return whether this nonce is present. As a side effect, mark it
  308. * as no longer present.
  309. *
  310. * @return bool $present
  311. */
  312. function useNonce($server_url, $timestamp, $salt)
  313. {
  314. global $Auth_OpenID_SKEW;
  315. if (!$this->active) {
  316. trigger_error("FileStore no longer active", E_USER_ERROR);
  317. return null;
  318. }
  319. if ( abs($timestamp - time()) > $Auth_OpenID_SKEW ) {
  320. return False;
  321. }
  322. if ($server_url) {
  323. list($proto, $rest) = explode('://', $server_url, 2);
  324. } else {
  325. $proto = '';
  326. $rest = '';
  327. }
  328. $parts = explode('/', $rest, 2);
  329. $domain = $this->_filenameEscape($parts[0]);
  330. $url_hash = $this->_safe64($server_url);
  331. $salt_hash = $this->_safe64($salt);
  332. $filename = sprintf('%08x-%s-%s-%s-%s', $timestamp, $proto,
  333. $domain, $url_hash, $salt_hash);
  334. $filename = $this->nonce_dir . DIRECTORY_SEPARATOR . $filename;
  335. $result = @fopen($filename, 'x');
  336. if ($result === false) {
  337. return false;
  338. } else {
  339. fclose($result);
  340. return true;
  341. }
  342. }
  343. /**
  344. * Remove expired entries from the database. This is potentially
  345. * expensive, so only run when it is acceptable to take time.
  346. *
  347. * @access private
  348. */
  349. function _allAssocs()
  350. {
  351. $all_associations = array();
  352. $association_filenames =
  353. Auth_OpenID_FileStore::_listdir($this->association_dir);
  354. foreach ($association_filenames as $association_filename) {
  355. $association_file = fopen($association_filename, 'rb');
  356. if ($association_file !== false) {
  357. $assoc_s = fread($association_file,
  358. filesize($association_filename));
  359. fclose($association_file);
  360. // Remove expired or corrupted associations
  361. $association =
  362. Auth_OpenID_Association::deserialize(
  363. 'Auth_OpenID_Association', $assoc_s);
  364. if ($association === null) {
  365. Auth_OpenID_FileStore::_removeIfPresent(
  366. $association_filename);
  367. } else {
  368. if ($association->getExpiresIn() == 0) {
  369. $all_associations[] = array($association_filename,
  370. $association);
  371. }
  372. }
  373. }
  374. }
  375. return $all_associations;
  376. }
  377. function clean()
  378. {
  379. if (!$this->active) {
  380. trigger_error("FileStore no longer active", E_USER_ERROR);
  381. return null;
  382. }
  383. $nonces = Auth_OpenID_FileStore::_listdir($this->nonce_dir);
  384. $now = time();
  385. // Check all nonces for expiry
  386. foreach ($nonces as $nonce) {
  387. if (!Auth_OpenID_checkTimestamp($nonce, $now)) {
  388. $filename = $this->nonce_dir . DIRECTORY_SEPARATOR . $nonce;
  389. Auth_OpenID_FileStore::_removeIfPresent($filename);
  390. }
  391. }
  392. foreach ($this->_allAssocs() as $pair) {
  393. list($assoc_filename, $assoc) = $pair;
  394. if ($assoc->getExpiresIn() == 0) {
  395. Auth_OpenID_FileStore::_removeIfPresent($assoc_filename);
  396. }
  397. }
  398. }
  399. /**
  400. * @access private
  401. */
  402. function _rmtree($dir)
  403. {
  404. if ($dir[strlen($dir) - 1] != DIRECTORY_SEPARATOR) {
  405. $dir .= DIRECTORY_SEPARATOR;
  406. }
  407. if ($handle = opendir($dir)) {
  408. while ($item = readdir($handle)) {
  409. if (!in_array($item, array('.', '..'))) {
  410. if (is_dir($dir . $item)) {
  411. if (!Auth_OpenID_FileStore::_rmtree($dir . $item)) {
  412. return false;
  413. }
  414. } else if (is_file($dir . $item)) {
  415. if (!unlink($dir . $item)) {
  416. return false;
  417. }
  418. }
  419. }
  420. }
  421. closedir($handle);
  422. if (!@rmdir($dir)) {
  423. return false;
  424. }
  425. return true;
  426. } else {
  427. // Couldn't open directory.
  428. return false;
  429. }
  430. }
  431. /**
  432. * @access private
  433. */
  434. function _mkstemp($dir)
  435. {
  436. foreach (range(0, 4) as $i) {
  437. $name = tempnam($dir, "php_openid_filestore_");
  438. if ($name !== false) {
  439. return $name;
  440. }
  441. }
  442. return false;
  443. }
  444. /**
  445. * @access private
  446. */
  447. function _mkdtemp($dir)
  448. {
  449. foreach (range(0, 4) as $i) {
  450. $name = $dir . strval(DIRECTORY_SEPARATOR) . strval(getmypid()) .
  451. "-" . strval(rand(1, time()));
  452. if (!mkdir($name, 0700)) {
  453. return false;
  454. } else {
  455. return $name;
  456. }
  457. }
  458. return false;
  459. }
  460. /**
  461. * @access private
  462. */
  463. function _listdir($dir)
  464. {
  465. $handle = opendir($dir);
  466. $files = array();
  467. while (false !== ($filename = readdir($handle))) {
  468. if (!in_array($filename, array('.', '..'))) {
  469. $files[] = $dir . DIRECTORY_SEPARATOR . $filename;
  470. }
  471. }
  472. return $files;
  473. }
  474. /**
  475. * @access private
  476. */
  477. function _isFilenameSafe($char)
  478. {
  479. $_Auth_OpenID_filename_allowed = Auth_OpenID_letters .
  480. Auth_OpenID_digits . ".";
  481. return (strpos($_Auth_OpenID_filename_allowed, $char) !== false);
  482. }
  483. /**
  484. * @access private
  485. */
  486. function _safe64($str)
  487. {
  488. $h64 = base64_encode(Auth_OpenID_SHA1($str));
  489. $h64 = str_replace('+', '_', $h64);
  490. $h64 = str_replace('/', '.', $h64);
  491. $h64 = str_replace('=', '', $h64);
  492. return $h64;
  493. }
  494. /**
  495. * @access private
  496. */
  497. function _filenameEscape($str)
  498. {
  499. $filename = "";
  500. $b = Auth_OpenID::toBytes($str);
  501. for ($i = 0; $i < count($b); $i++) {
  502. $c = $b[$i];
  503. if (Auth_OpenID_FileStore::_isFilenameSafe($c)) {
  504. $filename .= $c;
  505. } else {
  506. $filename .= sprintf("_%02X", ord($c));
  507. }
  508. }
  509. return $filename;
  510. }
  511. /**
  512. * Attempt to remove a file, returning whether the file existed at
  513. * the time of the call.
  514. *
  515. * @access private
  516. * @return bool $result True if the file was present, false if not.
  517. */
  518. function _removeIfPresent($filename)
  519. {
  520. return @unlink($filename);
  521. }
  522. function cleanupAssociations()
  523. {
  524. $removed = 0;
  525. foreach ($this->_allAssocs() as $pair) {
  526. list($assoc_filename, $assoc) = $pair;
  527. if ($assoc->getExpiresIn() == 0) {
  528. $this->_removeIfPresent($assoc_filename);
  529. $removed += 1;
  530. }
  531. }
  532. return $removed;
  533. }
  534. }
  535. ?>