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

/inc/lib/Auth/OpenID/FileStore.php

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