*/ class ParTCP_Key_Storage_Fs { public static $storageDir; public static function store_pubkey( $id, $pubKey ){ $file = self::id2path( $id ); $data = $pubKey; self::store_file( $file, $data ); } public static function get_pubkey( $id ){ $file = self::id2path( $id ); if ( ! file_exists( $file ) ){ return FALSE; } return trim( file_get_contents( $file ) ); } public static function list_pubkeys( $server = NULL ){ $dir = self::$storageDir . '/public' . ( $server ? "/{$server}" : '' ); if ( ! is_dir( $dir ) ){ return []; } $list = array_filter( scandir( $dir ), function( $file ) use ( $dir ){ return $file[0] != '.' && is_file( "{$dir}/{$file}" ); }); return array_map( function( $f ){ return basename( $f, '.key' ); }, $list ); } public static function delete_pubkey( $id ){ $file = self::id2path( $id ); if ( ! file_exists( $file ) ){ return FALSE; } return unlink( $file ); } public static function store_keypair( $id, $pubKey, $privKey ){ $file = self::id2path( $id, TRUE ); if ( ! $file ){ return FALSE; } $data = [ $pubKey, $privKey ]; self::store_file( $file, json_encode( $data ) ); } public static function exists_keypair( $id ){ $file = self::id2path( $id, TRUE ); return $file && file_exists( $file ); } public static function get_keypair( $id ){ $file = self::id2path( $id, TRUE ); if ( ! $file || ! file_exists( $file ) ){ return FALSE; } return json_decode( file_get_contents( $file ) ); } public static function list_keypairs( $server = NULL ){ $dir = self::$storageDir . '/private'; if ( $server ){ $dir .= '/' . trim( $server, '/' ); if ( ! is_dir( $dir ) ){ return []; } chdir( $dir ); $list = glob( '*.keys' ); return array_map( function( $file ) use ( $server ){ $file = basename( $file, PATHINFO_FILENAME ); return "{$file}@{$server}"; }, $list ); } else { chdir( $dir ); $list = glob( '**/*.keys' ); return array_map( function( $file ) use ( $server ){ $parts = explode( '/', $file ); $name = basename( $parts[1], '.keys' ); return "{$name}@{$parts[0]}"; }, $list ); } } public static function delete_keypair( $id ){ $file = self::id2path( $id, TRUE ); if ( ! file_exists( $file ) ){ return FALSE; } return unlink( $file ); } private static function id2path( $id, $private = FALSE ){ $parts = explode( '@', $id ); $path = $private ? '/private/' : '/public/'; if ( ! empty( $parts[1] ) ){ $path .= "{$parts[1]}/"; } $path .= str_replace( '/', '|', $parts[0] ); $path .= $private ? '.keys' : '.key'; return self::$storageDir . $path; } private static function store_file( $file, $data ){ $dir = dirname( $file ); if ( ! file_exists( $dir ) && ! mkdir( $dir, 0700, TRUE ) ){ throw new Exception( "Could not create directory {$dir}" ); } if ( ! file_put_contents( $file, $data ) ){ throw new Exception( "Could not write file {$file}" ); } chmod( $file, 0600 ); } } // end of file key_storage_fs.class.php