4 * This file supplies a Memcached store backend for OpenID servers and
9 * LICENSE: See the COPYING file included in this distribution.
12 * @author JanRain, Inc. <openid@janrain.com>
13 * @copyright 2005-2008 Janrain, Inc.
14 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache
18 * Require base class for creating a new interface.
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';
26 * This is a filesystem-based store for OpenID associations and
27 * nonces. This store should be safe for use in concurrent systems on
28 * both windows and unix (excluding NFS filesystems). There are a
29 * couple race conditions in the system, but those failure cases have
30 * been set up in such a way that the worst-case behavior is someone
31 * having to try to log in a second time.
33 * Most of the methods of this class are implementation details.
34 * People wishing to just use this store need only pay attention to
39 class Auth_OpenID_FileStore extends Auth_OpenID_OpenIDStore {
42 * Initializes a new {@link Auth_OpenID_FileStore}. This
43 * initializes the nonce and association directories, which are
44 * subdirectories of the directory passed in.
46 * @param string $directory This is the directory to put the store
49 function Auth_OpenID_FileStore($directory)
51 if (!Auth_OpenID::ensureDir($directory)) {
52 trigger_error('Not a directory and failed to create: '
53 . $directory, E_USER_ERROR);
55 $directory = realpath($directory);
57 $this->directory = $directory;
60 $this->nonce_dir = $directory . DIRECTORY_SEPARATOR . 'nonces';
62 $this->association_dir = $directory . DIRECTORY_SEPARATOR .
65 // Temp dir must be on the same filesystem as the assciations
67 $this->temp_dir = $directory . DIRECTORY_SEPARATOR . 'temp';
69 $this->max_nonce_age = 6 * 60 * 60; // Six hours, in seconds
71 if (!$this->_setup()) {
72 trigger_error('Failed to initialize OpenID file store in ' .
73 $directory, E_USER_ERROR);
79 Auth_OpenID_FileStore::_rmtree($this->directory);
80 $this->active = false;
84 * Make sure that the directories in which we store our data
91 return (Auth_OpenID::ensureDir($this->nonce_dir) &&
92 Auth_OpenID::ensureDir($this->association_dir) &&
93 Auth_OpenID::ensureDir($this->temp_dir));
97 * Create a temporary file on the same filesystem as
98 * $this->association_dir.
100 * The temporary directory should not be cleaned if there are any
101 * processes using the store. If there is no active process using
102 * the store, it is safe to remove all of the files in the
103 * temporary directory.
105 * @return array ($fd, $filename)
110 $name = Auth_OpenID_FileStore::_mkstemp($dir = $this->temp_dir);
111 $file_obj = @fopen($name, 'wb');
112 if ($file_obj !== false) {
113 return array($file_obj, $name);
115 Auth_OpenID_FileStore::_removeIfPresent($name);
119 function cleanupNonces()
121 global $Auth_OpenID_SKEW;
123 $nonces = Auth_OpenID_FileStore::_listdir($this->nonce_dir);
127 // Check all nonces for expiry
128 foreach ($nonces as $nonce_fname) {
129 $base = basename($nonce_fname);
130 $parts = explode('-', $base, 2);
131 $timestamp = $parts[0];
132 $timestamp = intval($timestamp, 16);
133 if (abs($timestamp - $now) > $Auth_OpenID_SKEW) {
134 Auth_OpenID_FileStore::_removeIfPresent($nonce_fname);
142 * Create a unique filename for a given server url and
143 * handle. This implementation does not assume anything about the
144 * format of the handle. The filename that is returned will
145 * contain the domain name from the server URL for ease of human
146 * inspection of the data directory.
148 * @return string $filename
150 function getAssociationFilename($server_url, $handle)
152 if (!$this->active) {
153 trigger_error("FileStore no longer active", E_USER_ERROR);
157 if (strpos($server_url, '://') === false) {
158 trigger_error(sprintf("Bad server URL: %s", $server_url),
163 list($proto, $rest) = explode('://', $server_url, 2);
164 $parts = explode('/', $rest);
165 $domain = Auth_OpenID_FileStore::_filenameEscape($parts[0]);
166 $url_hash = Auth_OpenID_FileStore::_safe64($server_url);
168 $handle_hash = Auth_OpenID_FileStore::_safe64($handle);
173 $filename = sprintf('%s-%s-%s-%s', $proto, $domain, $url_hash,
176 return $this->association_dir. DIRECTORY_SEPARATOR . $filename;
180 * Store an association in the association directory.
182 function storeAssociation($server_url, $association)
184 if (!$this->active) {
185 trigger_error("FileStore no longer active", E_USER_ERROR);
189 $association_s = $association->serialize();
190 $filename = $this->getAssociationFilename($server_url,
191 $association->handle);
192 list($tmp_file, $tmp) = $this->_mktemp();
195 trigger_error("_mktemp didn't return a valid file descriptor",
200 fwrite($tmp_file, $association_s);
206 if (@rename($tmp, $filename)) {
209 // In case we are running on Windows, try unlinking the
210 // file in case it exists.
213 // Now the target should not exist. Try renaming again,
214 // giving up if it fails.
215 if (@rename($tmp, $filename)) {
220 // If there was an error, don't leave the temporary file
222 Auth_OpenID_FileStore::_removeIfPresent($tmp);
227 * Retrieve an association. If no handle is specified, return the
228 * association with the most recent issue time.
230 * @return mixed $association
232 function getAssociation($server_url, $handle = null)
234 if (!$this->active) {
235 trigger_error("FileStore no longer active", E_USER_ERROR);
239 if ($handle === null) {
243 // The filename with the empty handle is a prefix of all other
244 // associations for the given server URL.
245 $filename = $this->getAssociationFilename($server_url, $handle);
248 return $this->_getAssociation($filename);
251 Auth_OpenID_FileStore::_listdir($this->association_dir);
252 $matching_files = array();
254 // strip off the path to do the comparison
255 $name = basename($filename);
256 foreach ($association_files as $association_file) {
257 $base = basename($association_file);
258 if (strpos($base, $name) === 0) {
259 $matching_files[] = $association_file;
263 $matching_associations = array();
264 // read the matching files and sort by time issued
265 foreach ($matching_files as $full_name) {
266 $association = $this->_getAssociation($full_name);
267 if ($association !== null) {
268 $matching_associations[] = array($association->issued,
275 foreach ($matching_associations as $key => $assoc) {
276 $issued[$key] = $assoc[0];
277 $assocs[$key] = $assoc[1];
280 array_multisort($issued, SORT_DESC, $assocs, SORT_DESC,
281 $matching_associations);
283 // return the most recently issued one.
284 if ($matching_associations) {
285 list($issued, $assoc) = $matching_associations[0];
296 function _getAssociation($filename)
298 if (!$this->active) {
299 trigger_error("FileStore no longer active", E_USER_ERROR);
303 $assoc_file = @fopen($filename, 'rb');
305 if ($assoc_file === false) {
309 $assoc_s = fread($assoc_file, filesize($filename));
317 Auth_OpenID_Association::deserialize('Auth_OpenID_Association',
321 Auth_OpenID_FileStore::_removeIfPresent($filename);
325 if ($association->getExpiresIn() == 0) {
326 Auth_OpenID_FileStore::_removeIfPresent($filename);
334 * Remove an association if it exists. Do nothing if it does not.
336 * @return bool $success
338 function removeAssociation($server_url, $handle)
340 if (!$this->active) {
341 trigger_error("FileStore no longer active", E_USER_ERROR);
345 $assoc = $this->getAssociation($server_url, $handle);
346 if ($assoc === null) {
349 $filename = $this->getAssociationFilename($server_url, $handle);
350 return Auth_OpenID_FileStore::_removeIfPresent($filename);
355 * Return whether this nonce is present. As a side effect, mark it
356 * as no longer present.
358 * @return bool $present
360 function useNonce($server_url, $timestamp, $salt)
362 global $Auth_OpenID_SKEW;
364 if (!$this->active) {
365 trigger_error("FileStore no longer active", E_USER_ERROR);
369 if ( abs($timestamp - time()) > $Auth_OpenID_SKEW ) {
374 list($proto, $rest) = explode('://', $server_url, 2);
380 $parts = explode('/', $rest, 2);
381 $domain = $this->_filenameEscape($parts[0]);
382 $url_hash = $this->_safe64($server_url);
383 $salt_hash = $this->_safe64($salt);
385 $filename = sprintf('%08x-%s-%s-%s-%s', $timestamp, $proto,
386 $domain, $url_hash, $salt_hash);
387 $filename = $this->nonce_dir . DIRECTORY_SEPARATOR . $filename;
389 $result = @fopen($filename, 'x');
391 if ($result === false) {
400 * Remove expired entries from the database. This is potentially
401 * expensive, so only run when it is acceptable to take time.
405 function _allAssocs()
407 $all_associations = array();
409 $association_filenames =
410 Auth_OpenID_FileStore::_listdir($this->association_dir);
412 foreach ($association_filenames as $association_filename) {
413 $association_file = fopen($association_filename, 'rb');
415 if ($association_file !== false) {
416 $assoc_s = fread($association_file,
417 filesize($association_filename));
418 fclose($association_file);
420 // Remove expired or corrupted associations
422 Auth_OpenID_Association::deserialize(
423 'Auth_OpenID_Association', $assoc_s);
425 if ($association === null) {
426 Auth_OpenID_FileStore::_removeIfPresent(
427 $association_filename);
429 if ($association->getExpiresIn() == 0) {
430 $all_associations[] = array($association_filename,
437 return $all_associations;
442 if (!$this->active) {
443 trigger_error("FileStore no longer active", E_USER_ERROR);
447 $nonces = Auth_OpenID_FileStore::_listdir($this->nonce_dir);
450 // Check all nonces for expiry
451 foreach ($nonces as $nonce) {
452 if (!Auth_OpenID_checkTimestamp($nonce, $now)) {
453 $filename = $this->nonce_dir . DIRECTORY_SEPARATOR . $nonce;
454 Auth_OpenID_FileStore::_removeIfPresent($filename);
458 foreach ($this->_allAssocs() as $pair) {
459 list($assoc_filename, $assoc) = $pair;
460 if ($assoc->getExpiresIn() == 0) {
461 Auth_OpenID_FileStore::_removeIfPresent($assoc_filename);
469 function _rmtree($dir)
471 if ($dir[strlen($dir) - 1] != DIRECTORY_SEPARATOR) {
472 $dir .= DIRECTORY_SEPARATOR;
475 if ($handle = opendir($dir)) {
476 while ($item = readdir($handle)) {
477 if (!in_array($item, array('.', '..'))) {
478 if (is_dir($dir . $item)) {
480 if (!Auth_OpenID_FileStore::_rmtree($dir . $item)) {
483 } else if (is_file($dir . $item)) {
484 if (!unlink($dir . $item)) {
499 // Couldn't open directory.
507 function _mkstemp($dir)
509 foreach (range(0, 4) as $i) {
510 $name = tempnam($dir, "php_openid_filestore_");
512 if ($name !== false) {
522 static function _mkdtemp($dir)
524 foreach (range(0, 4) as $i) {
525 $name = $dir . strval(DIRECTORY_SEPARATOR) . strval(getmypid()) .
526 "-" . strval(rand(1, time()));
527 if (!mkdir($name, 0700)) {
539 function _listdir($dir)
541 $handle = opendir($dir);
543 while (false !== ($filename = readdir($handle))) {
544 if (!in_array($filename, array('.', '..'))) {
545 $files[] = $dir . DIRECTORY_SEPARATOR . $filename;
554 function _isFilenameSafe($char)
556 $_Auth_OpenID_filename_allowed = Auth_OpenID_letters .
557 Auth_OpenID_digits . ".";
558 return (strpos($_Auth_OpenID_filename_allowed, $char) !== false);
564 function _safe64($str)
566 $h64 = base64_encode(Auth_OpenID_SHA1($str));
567 $h64 = str_replace('+', '_', $h64);
568 $h64 = str_replace('/', '.', $h64);
569 $h64 = str_replace('=', '', $h64);
576 function _filenameEscape($str)
579 $b = Auth_OpenID::toBytes($str);
581 for ($i = 0; $i < count($b); $i++) {
583 if (Auth_OpenID_FileStore::_isFilenameSafe($c)) {
586 $filename .= sprintf("_%02X", ord($c));
593 * Attempt to remove a file, returning whether the file existed at
594 * the time of the call.
597 * @return bool $result True if the file was present, false if not.
599 function _removeIfPresent($filename)
601 return @unlink($filename);
604 function cleanupAssociations()
607 foreach ($this->_allAssocs() as $pair) {
608 list($assoc_filename, $assoc) = $pair;
609 if ($assoc->getExpiresIn() == 0) {
610 $this->_removeIfPresent($assoc_filename);