PHP OpenID consumer
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

discoverer.inc.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. <?PHP
  2. /* Poidsy 0.6 - http://chris.smith.name/projects/poidsy
  3. * Copyright (c) 2008-2010 Chris Smith
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. * SOFTWARE.
  22. */
  23. require_once(dirname(__FILE__) . '/logging.inc.php');
  24. class Server {
  25. private $url = null;
  26. private $version = 1;
  27. private $services = array();
  28. public function __construct($url, $version) {
  29. $this->url = $url;
  30. $this->version = $version;
  31. }
  32. public function getURL() {
  33. return $this->url;
  34. }
  35. public function getVersion() {
  36. return $this->version;
  37. }
  38. public function getServices() {
  39. return $this->services;
  40. }
  41. public function addServices($services) {
  42. foreach ($services as $service) {
  43. $this->services[] = $service;
  44. }
  45. }
  46. public function hasService($service) {
  47. return array_search($service, $this->services) !== false;
  48. }
  49. }
  50. class Discoverer {
  51. const ID_SELECT_URL = 'http://specs.openid.net/auth/2.0/identifier_select';
  52. private $version; // OpenID 2 teminology || OpenID 1 terminology
  53. // --------------------- || ----------------------
  54. private $userSuppliedId; // User supplied ID || [Same as Claimed ID]
  55. private $claimedId; // Claimed ID || Claimed ID
  56. private $endpointUrl; // OP Endpoint URL || Identity Provider
  57. private $opLocalId; // OP-local ID || Delegate
  58. private $servers = array();
  59. public function __construct($uri, $normalise = true) {
  60. if ($uri !== null) {
  61. $this->discover($this->userSuppliedId = ($normalise ? $this->normalise($uri) : $uri));
  62. }
  63. }
  64. public function getEndpointUrl() {
  65. return $this->endpointUrl;
  66. }
  67. public function getUserSuppliedId() {
  68. return $this->userSuppliedId;
  69. }
  70. public function getClaimedId() {
  71. return $this->claimedId;
  72. }
  73. public function getOpLocalId() {
  74. return $this->opLocalId;
  75. }
  76. public function getVersion() {
  77. return $this->version;
  78. }
  79. public function hasServer($endpointUrl) {
  80. return isset($this->servers[$endpointUrl]);
  81. }
  82. public static function normalise($uri) {
  83. // Strip xri:// prefix
  84. if (substr($uri, 0, 6) == 'xri://') {
  85. $uri = substr($uri, 6);
  86. }
  87. // If the first char is a global context symbol, treat it as XRI
  88. if (in_array($uri[0], array('=', '@', '+', '$', '!'))) {
  89. // TODO: Implement
  90. throw new Exception('This implementation does not currently support XRI');
  91. }
  92. // Add http:// if needed
  93. if (strpos($uri, '://') === false) {
  94. $uri = 'http://' . $uri;
  95. }
  96. $bits = @parse_url($uri);
  97. $result = $bits['scheme'] . '://';
  98. if (defined('OPENID_ALLOWUSER') && isset($bits['user'])) {
  99. $result .= $bits['user'];
  100. if (isset($bits['pass'])) {
  101. $result .= ':' . $bits['pass'];
  102. }
  103. $result .= '@';
  104. }
  105. $result .= preg_replace('/\.$/', '', $bits['host']);
  106. if (isset($bits['port']) && !empty($bits['port']) &&
  107. (($bits['scheme'] == 'http' && $bits['port'] != '80') ||
  108. ($bits['scheme'] == 'https' && $bits['port'] != '443') ||
  109. ($bits['scheme'] != 'http' && $bits['scheme'] != 'https'))) {
  110. $result .= ':' . $bits['port'];
  111. }
  112. if (isset($bits['path'])) {
  113. do {
  114. $bits['path'] = preg_replace('#/([^/]*)/\.\./#', '/', str_replace('/./', '/', $old = $bits['path']));
  115. } while ($old != $bits['path']);
  116. $result .= $bits['path'];
  117. } else {
  118. $result .= '/';
  119. }
  120. if (defined('OPENID_ALLOWQUERY') && isset($bits['query'])) {
  121. $result .= '?' . $bits['query'];
  122. }
  123. return $result;
  124. }
  125. private function discover($uri) {
  126. Logger::log('Performing discovery for %s', $uri);
  127. if (!$this->yadisDiscover($uri)) {
  128. $this->htmlDiscover($uri);
  129. }
  130. }
  131. private function yadisDiscover($uri, $allowLocation = true) {
  132. Logger::log('Attempting Yadis discovery on %s', $uri);
  133. if ($allowLocation) {
  134. $this->claimedId = $uri;
  135. }
  136. $ctx = stream_context_create(array(
  137. 'http' => array(
  138. 'header' => "Accept: application/xrds+xml\r\n",
  139. )
  140. ));
  141. $fh = @fopen($uri, 'r', false, $ctx);
  142. if (!$fh) {
  143. Logger::log('Unable to open stream');
  144. return false;
  145. }
  146. $details = stream_get_meta_data($fh);
  147. $data = '';
  148. while (!feof($fh) && strpos($data, '</head>') === false) {
  149. $data .= fgets($fh);
  150. }
  151. fclose($fh);
  152. foreach ($details['wrapper_data'] as $line) {
  153. if ($allowLocation && preg_match('/^X-XRDS-Location:\s*(.*?)$/i', $line, $m)) {
  154. // TODO: Allow relative URLs?
  155. $this->handleRedirects($details);
  156. return $this->yadisDiscover($m[1], false);
  157. } else if (preg_match('#^Content-type:\s*application/xrds\+xml(;.*?)?$#i', $line)) {
  158. $this->handleRedirects($details);
  159. return $this->parseYadis($data);
  160. }
  161. }
  162. if (($url = $this->parseYadisHTML($data)) !== false) {
  163. $this->handleRedirects($details);
  164. return $this->yadisDiscover($url, false);
  165. }
  166. }
  167. private function parseYadis($data) {
  168. $sxml = @new SimpleXMLElement($data);
  169. if (!$sxml) {
  170. Logger::log('Failed to parse XRDS data as XML');
  171. // TODO: Die somehow?
  172. return false;
  173. }
  174. // TODO: Better handling of namespaces
  175. $found = false;
  176. foreach ($sxml->XRD->Service as $service) {
  177. $services = array();
  178. $server = null;
  179. foreach ($service->Type as $type) {
  180. Logger::log('Found service of type %s', $type);
  181. if ((String) $type == 'http://specs.openid.net/auth/2.0/server') {
  182. $this->version = 2;
  183. $this->endpointUrl = (String) $service->URI;
  184. $this->claimedId = $this->opLocalId = self::ID_SELECT_URL;
  185. Logger::log('OpenID EP found (server). End point: %s, claimed id: %s, op local id: %s', $this->endpointUrl, $this->claimedId, $this->opLocalId);
  186. $found = true;
  187. $this->servers[$this->endpointUrl] = $server = new Server($this->endpointUrl, $this->version);
  188. } else if ((String) $type == 'http://specs.openid.net/auth/2.0/signon') {
  189. $this->version = 2;
  190. $this->endpointUrl = (String) $service->URI;
  191. if (isset($service->LocalID)) {
  192. $this->opLocalId = (String) $service->LocalID;
  193. } else {
  194. $this->opLocalId = self::ID_SELECT_URL;
  195. $this->claimedId = self::ID_SELECT_URL;
  196. }
  197. Logger::log('OpenID EP found (signon). End point: %s, claimed id: %s, op local id: %s', $this->endpointUrl, $this->claimedId, $this->opLocalId);
  198. $found = true;
  199. $this->servers[$this->endpointUrl] = $server = new Server($this->endpointUrl, $this->version);
  200. } else {
  201. $services[] = (String) $type;
  202. }
  203. }
  204. if ($server != null) {
  205. $server->addServices($services);
  206. }
  207. }
  208. return $found;
  209. }
  210. private function parseYadisHTML($data) {
  211. $meta = self::getMetaTags($data);
  212. if (isset($meta['x-xrds-location'])) {
  213. Logger::log('Found XRDS meta tag: %s', $meta['x-xrds-location']);
  214. // TODO: Allow relative URLs?
  215. return $meta['x-xrds-location'];
  216. }
  217. return false;
  218. }
  219. private function htmlDiscover($uri) {
  220. Logger::log('Performing HTML discovery on %s', $uri);
  221. $fh = @fopen($uri, 'r');
  222. if (!$fh) {
  223. Logger::log('Unable to open stream');
  224. return;
  225. }
  226. $this->claimedId = $uri;
  227. $details = stream_get_meta_data($fh);
  228. $this->handleRedirects($details);
  229. Logger::log('Claimed identity: %s', $this->claimedId);
  230. $data = '';
  231. while (!feof($fh) && strpos($data, '</head>') === false) {
  232. $data .= fgets($fh);
  233. }
  234. fclose($fh);
  235. $this->parseHtml($data);
  236. }
  237. protected function handleRedirects($details) {
  238. foreach ($details['wrapper_data'] as $line) {
  239. if (preg_match('/^Location: (.*?)$/i', $line, $m)) {
  240. if (strpos($m[1], '://') !== false) {
  241. // Fully qualified URL
  242. $this->claimedId = $m[1];
  243. Logger::log('Redirection (fully qualified) to ' . $m[1]);
  244. } else if ($m[1][0] == '/') {
  245. // Absolute URL
  246. $this->claimedId = preg_replace('#^(.*?://.*?)/.*$#', '\1', $this->claimedId) . $m[1];
  247. Logger::log('Redirection (absolute) to ' . $m[1] . ': ' . $this->claimedId);
  248. } else {
  249. // Relative URL
  250. $this->claimedId = preg_replace('#^(.*?://.*/).*?$#', '\1', $this->claimedId) . $m[1];
  251. Logger::log('Redirection (relative) to ' . $m[1] . ': ' . $this->claimedId);
  252. }
  253. }
  254. $this->claimedId = self::normalise($this->claimedId);
  255. }
  256. }
  257. protected static function getLinks($data) {
  258. return self::getTags($data, 'link', 'rel', 'href', true);
  259. }
  260. protected static function getMetaTags($data) {
  261. return self::getTags($data, 'meta', 'http-equiv', 'content');
  262. }
  263. protected static function getTags($data, $tag, $att1, $att2, $split = false) {
  264. preg_match_all('#<' . $tag . '\s*(.*?)\s*/?' . '>#is', $data, $matches);
  265. $links = array();
  266. foreach ($matches[1] as $link) {
  267. $rel = $href = null;
  268. if (preg_match('#' . $att1 . '\s*=\s*(?:([^"\'>\s]*)|"([^">]*)"|\'([^\'>]*)\')(?:\s|$)#is', $link, $m)) {
  269. array_shift($m);
  270. $rel = implode('', $m);
  271. }
  272. if (preg_match('#' . $att2 . '\s*=\s*(?:([^"\'>\s]*)|"([^">]*)"|\'([^\'>]*)\')(?:\s|$)#is', $link, $m)) {
  273. array_shift($m);
  274. $href = implode('', $m);
  275. }
  276. if ($split) {
  277. foreach (explode(' ', strtolower($rel)) as $part) {
  278. $links[$part] = html_entity_decode($href);
  279. }
  280. } else {
  281. $links[strtolower($rel)] = html_entity_decode($href);
  282. }
  283. }
  284. return $links;
  285. }
  286. public function parseHtml($data) {
  287. $links = self::getLinks($data);
  288. if (isset($links['openid2.provider'])) {
  289. $this->version = 2;
  290. $this->endpointUrl = $links['openid2.provider'];
  291. //$this->servers[] = new Server($this->server, 2);
  292. $this->claimedId = $this->userSuppliedId;
  293. $this->opLocalId = isset($links['openid2.local_id']) ? $links['openid2.local_id'] : $this->claimedId;
  294. $this->servers[$this->endpointUrl] = $server = new Server($this->endpointUrl, $this->version);
  295. Logger::log('OpenID EP found. End point: %s, claimed id: %s, op local id: %s', $this->endpointUrl, $this->claimedId, $this->opLocalId);
  296. } else if (isset($links['openid.server'])) {
  297. $this->version = 1;
  298. $this->endpointUrl = $links['openid.server'];
  299. //$this->servers[] = new Server($this->server, 2);
  300. $this->claimedId = $this->userSuppliedId;
  301. if (isset($links['openid.delegate'])) {
  302. $this->opLocalId = $links['openid.delegate'];
  303. }
  304. $this->servers[$this->endpointUrl] = $server = new Server($this->endpointUrl, $this->version);
  305. Logger::log('OpenID EP found. End point: %s, claimed id: %s, op local id: %s', $this->endpointUrl, $this->claimedId, $this->opLocalId);
  306. }
  307. }
  308. }
  309. ?>