PageRenderTime 70ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Auth/OpenID/FileStore.php

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