From c7cc488415e3d2ba43b33e40b7eb92cb23ac5da6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Andreas=20=C3=85kre=20Solberg?= <andreas.solberg@uninett.no>
Date: Tue, 3 Feb 2009 14:07:42 +0000
Subject: [PATCH] Possibility to debug just one host at a time...

git-svn-id: https://simplesamlphp.googlecode.com/svn/trunk@1232 44740490-163a-0410-bde0-09ae8108e29a
---
 modules/ldapstatus/lib/LDAPTester.php       | 194 ++++++++++++++++++++
 modules/ldapstatus/templates/ldapstatus.php |  15 +-
 modules/ldapstatus/www/index.php            | 187 +++----------------
 3 files changed, 236 insertions(+), 160 deletions(-)
 create mode 100644 modules/ldapstatus/lib/LDAPTester.php

diff --git a/modules/ldapstatus/lib/LDAPTester.php b/modules/ldapstatus/lib/LDAPTester.php
new file mode 100644
index 000000000..f5c1bd72c
--- /dev/null
+++ b/modules/ldapstatus/lib/LDAPTester.php
@@ -0,0 +1,194 @@
+<?php
+
+/**
+ * Test LDAP connection...
+ *
+ * @author Andreas Ă…kre Solberg, UNINETT AS.
+ * @package simpleSAMLphp
+ * @version $Id$
+ */
+class sspmod_ldapstatus_LDAPTester {
+
+
+	private $orgconfig;
+	private $debug;
+	private $debugOutput;
+
+	public function __construct($orgconfig, $debug, $output = FALSE) {
+		$this->orgconfig = $orgconfig;
+		$this->debug = $debug;
+		$this->debugOutput = $output;
+	}
+		
+	private function is_in_array($needles, $haystack) {
+		$needles = SimpleSAML_Utilities::arrayize($needles);
+		foreach($needles AS $needle) {
+			if (array_key_exists($needle, $haystack) && !empty($haystack[$needle])) return TRUE;
+		}
+		return FALSE;
+	}
+	
+	private function checkConfig($conf, $req) {
+		$err = array();
+		foreach($req AS $r) {
+			
+			if (!$this->is_in_array($r, $conf)) {
+				$err[] = 'missing or empty: ' . join(', ', SimpleSAML_Utilities::arrayize($r));
+			}
+		}
+		if (count($err) > 0) {
+			return array(FALSE, 'Missing: ' . join(', ', $err));
+		}
+		return array(TRUE, NULL);	
+	}
+	
+	
+	private function log($str) {
+		if ($this->debugOutput) {
+			echo '<p>' . $str;
+		} else {
+			SimpleSAML_Logger::debug('ldapstatus phpping(): ping [' . $host . ':' . $port . ']' );
+		}
+	}
+	
+	private function phpping($host, $port) {
+	
+		$this->log('ldapstatus phpping(): ping [' . $host . ':' . $port . ']' );
+	
+		$timeout = 1.0;
+		$socket = @fsockopen($host, $port, $errno, $errstr, $timeout);
+		@fclose($socket);
+		if ($errno) {
+			return array(FALSE, $errno . ':' . $errstr . ' [' . $host . ':' . $port . ']');
+		} else {		
+			return array(TRUE,NULL);
+		}
+	}
+	
+	public function test() {
+		$start = microtime(TRUE);
+		
+		$result = array();
+		
+		$this->log('Testing config');
+		$result['config'] = $this->checkConfig($this->orgconfig, array('description', 'searchbase', 'hostname'));
+
+		$this->log('Testing config meta');
+		$result['configMeta'] = $this->checkConfig($this->orgconfig, array(array('contactMail', 'contactURL')));
+
+		$this->log('Testing config testuser');
+		$result['configTest'] = $this->checkConfig($this->orgconfig, array('testUser', 'testPassword'));
+	
+		if (!$result['config'][0]) {
+			$this->log('Skipping because of no configuration');
+			$result['time'] = microtime(TRUE) - $start;
+			return $result;
+		}
+	
+		$urldef = explode(' ', $this->orgconfig['hostname']);
+		$url = parse_url($urldef[0]);
+		$port = 389;
+		if (!empty($url['scheme']) && $url['scheme'] === 'ldaps') $port = 636;
+		if (!empty($url['port'])) $port = $url['port'];
+		
+		$this->log('ldapstatus Url parse [' . $this->orgconfig['hostname'] . '] => [' . $url['host'] . ']:[' . $port . ']' );
+	
+	
+		$result['ping'] = $this->phpping($url['host'], $port);
+	
+		if (!$result['ping'][0]) {
+			$result['time'] = microtime(TRUE) - $start;
+			$this->log('Skipping because of no ping');
+			return $result;
+		}
+		
+		// LDAP Connect
+		try {
+			$ldap = new SimpleSAML_Auth_LDAP($this->orgconfig['hostname'], 
+				(array_key_exists('enable_tls', $this->orgconfig) ? $this->orgconfig['enable_tls'] : FALSE), 
+				$this->debug);
+			
+			if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
+			$result['connect'] = array(TRUE,NULL);
+		} catch (Exception $e) {
+			$this->log('ldapstatus: Connect error() [' .$orgkey . ']: ' . $e->getMessage());
+			$result['connect'] = array(FALSE,$e->getMessage());
+			$result['time'] = microtime(TRUE) - $start;
+			return $result;
+		}
+	
+		// Bind as admin user
+		if (isset($this->orgconfig['adminUser'])) {
+			try {
+				$this->log('ldapstatus: Admin bind() [' .$orgkey . ']');
+				$success = $ldap->bind($this->orgconfig['adminUser'], $this->orgconfig['adminPassword']);
+				if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
+				if ($success) {
+					$result['adminBind'] = array(TRUE,NULL);
+				} else {
+					$result['adminBind'] = array(FALSE,'Could not bind()' );
+				}
+			} catch (Exception $e) {
+				$this->log('admin Bind() error:' . $e->getMessage());
+				$result['adminBind'] = array(FALSE,$e->getMessage());
+				$result['time'] = microtime(TRUE) - $start;
+				return $result;
+			}
+		}
+		
+		
+		$eppn = 'asdasdasdasd@feide.no';
+		// Search for bogus user
+		try {
+			$dn = $ldap->searchfordn($this->orgconfig['searchbase'], 'eduPersonPrincipalName', $eppn, TRUE);
+			if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
+			$result['ldapSearchBogus'] = array(TRUE,NULL);
+		} catch (Exception $e) {
+			$this->log('LDAP Search bogus:' . $e->getMessage());
+			$result['ldapSearchBogus'] = array(FALSE,$e->getMessage());
+			$result['time'] = microtime(TRUE) - $start;
+			return $result;
+		}
+	
+	
+		// If test user is available
+		if (array_key_exists('testUser', $this->orgconfig)) {
+	
+			$this->log('Testuser found in config. Performing test with test user.');
+
+			// Try to search for DN of test account
+			try {
+				$dn = $ldap->searchfordn($this->orgconfig['searchbase'], 'eduPersonPrincipalName', $this->orgconfig['testUser']);
+				if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
+				$result['ldapSearchTestUser'] = array(TRUE,NULL);
+			} catch (Exception $e) {
+				$this->log('LDAP Search test account:' . $e->getMessage());
+				$result['ldapSearchTestUser'] = array(FALSE,$e->getMessage());
+				$result['time'] = microtime(TRUE) - $start;
+				return $result;
+			}
+			
+			if ($ldap->bind($dn, $this->orgconfig['testPassword'])) {
+				$result['ldapBindTestUser'] = array(TRUE,NULL);
+				
+			} else {
+				$this->log('LDAP Test user bind() failed...');
+				$result['ldapBindTestUser'] = array(FALSE,NULL);
+				$result['time'] = microtime(TRUE) - $start;
+				return $result;
+			}
+	
+			try {
+				$attributes = $ldap->getAttributes($dn, $this->orgconfig['attributes']);
+				if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
+				$result['ldapGetAttributesTestUser'] = array(TRUE,NULL);
+			} catch(Exception $e) {
+				$this->log('LDAP Test user attributes failed:' . $e->getMessage());
+				$result['ldapGetAttributesTestUser'] = array(FALSE,$e->getMessage());
+			}
+		}
+		$result['time'] = microtime(TRUE) - $start;
+		return $result;
+	}
+}
+?>
\ No newline at end of file
diff --git a/modules/ldapstatus/templates/ldapstatus.php b/modules/ldapstatus/templates/ldapstatus.php
index af2e191fd..6362e2634 100644
--- a/modules/ldapstatus/templates/ldapstatus.php
+++ b/modules/ldapstatus/templates/ldapstatus.php
@@ -4,7 +4,14 @@ $this->data['head'] = '<style>
 table.statustable td {
 	border-bottom: 1px solid #eee;
 }
-
+a {
+	color: #333;
+	text-decoration: none;
+	border-bottom: 1px dotted #aaa;
+}
+a:hover {
+	border-bottom: 1px solid #aaa;
+}
 </style>';
 $this->includeAtTemplateBase('includes/header.php');
 
@@ -60,11 +67,13 @@ foreach($this->data['sortedOrgIndex'] as $orgkey) {
 	$res = $this->data['results'][$orgkey];
 	echo('<tr class="' . ($classes[($i++ % 2)]) . '">');
 	if (array_key_exists('description', $this->data['orgconfig'][$orgkey])) {
-		echo('<td>' . htmlspecialchars(
+		echo('<td><a href="?orgtest=' . htmlentities($orgkey) . '">');
+		echo htmlspecialchars(
 			$this->getTranslation(
 					SimpleSAML_Utilities::arrayize($this->data['orgconfig'][$orgkey]['description'], 'en')
 				)
-			) . '</td>');
+			);
+		echo('</a></td>');
 	} else {
 		echo('<td><span style="color: #b4b4b4; font-size: x-small">NA</span> <tt>' . $orgkey . '</tt></td>');
 	}
diff --git a/modules/ldapstatus/www/index.php b/modules/ldapstatus/www/index.php
index 2ddd5779c..97afc2620 100644
--- a/modules/ldapstatus/www/index.php
+++ b/modules/ldapstatus/www/index.php
@@ -15,75 +15,42 @@ function myErrorHandler($errno, $errstr, $errfile, $errline) {
 
     switch ($errno) {
     case E_USER_ERROR:
-    	SimpleSAML_Logger::error('PHP_ERROR   : [' . $errno . '] ' . $errstr . '. Fatal error on line ' . $errline . ' in file ' . $errfile);
+    	echo('<p>PHP_ERROR   : [' . $errno . '] ' . $errstr . '. Fatal error on line ' . $errline . ' in file ' . $errfile);
     	break;
 
     case E_USER_WARNING:
-    	SimpleSAML_Logger::error('PHP_WARNING : [' . $errno . '] ' . $errstr . '. Warning on line ' . $errline . ' in file ' . $errfile);
+    	echo('<p>PHP_WARNING : [' . $errno . '] ' . $errstr . '. Warning on line ' . $errline . ' in file ' . $errfile);
     	break;
 
     case E_USER_NOTICE:
-    	SimpleSAML_Logger::error('PHP_WARNING : [' . $errno . '] ' . $errstr . '. Warning on line ' . $errline . ' in file ' . $errfile);        
+    	echo('<p>PHP_WARNING : [' . $errno . '] ' . $errstr . '. Warning on line ' . $errline . ' in file ' . $errfile);        
     	break;
 
     default:
-    	SimpleSAML_Logger::error('PHP_UNKNOWN : [' . $errno . '] ' . $errstr . '. Unknown error on line ' . $errline . ' in file ' . $errfile);        
+    	echo('<p>PHP_UNKNOWN : [' . $errno . '] ' . $errstr . '. Unknown error on line ' . $errline . ' in file ' . $errfile);        
         break;
     }
 
     /* Don't execute PHP internal error handler */
     return true;
 }
-$old_error_handler = set_error_handler("myErrorHandler");
+
+
+
 
 $ldapconfig = $config->copyFromBase('loginfeide', 'config-login-feide.php');
 $ldapStatusConfig = $config->copyFromBase('ldapstatus', 'module_ldapstatus.php');
 
-$pingcommand = $ldapStatusConfig->getValue('ping');
-
 $debug = $ldapconfig->getValue('ldapDebug', FALSE);
-
 $orgs = $ldapconfig->getValue('orgldapconfig');
 
 #echo '<pre>'; print_r($orgs); exit;
 
 
 
-function phpping($host, $port) {
-
-	SimpleSAML_Logger::debug('ldapstatus phpping(): ping [' . $host . ':' . $port . ']' );
 
-	$timeout = 1.0;
-	$socket = @fsockopen($host, $port, $errno, $errstr, $timeout);
-	@fclose($socket);
-	if ($errno) {
-		return array(FALSE, $errno . ':' . $errstr . ' [' . $host . ':' . $port . ']');
-	} else {		
-		return array(TRUE,NULL);
-	}
-}
 
-function is_in_array($needles, $haystack) {
-	$needles = SimpleSAML_Utilities::arrayize($needles);
-	foreach($needles AS $needle) {
-		if (array_key_exists($needle, $haystack) && !empty($haystack[$needle])) return TRUE;
-	}
-	return FALSE;
-}
 
-function checkConfig($conf, $req) {
-	$err = array();
-	foreach($req AS $r) {
-		
-		if (!is_in_array($r, $conf)) {
-			$err[] = 'missing or empty: ' . join(', ', SimpleSAML_Utilities::arrayize($r));
-		}
-	}
-	if (count($err) > 0) {
-		return array(FALSE, 'Missing: ' . join(', ', $err));
-	}
-	return array(TRUE, NULL);	
-}
 
 $results = NULL;
 
@@ -103,131 +70,40 @@ $previous = microtime(TRUE);
 $maxtime = $ldapStatusConfig->getValue('maxExecutionTime', 15); 
 
 
-foreach ($orgs AS $orgkey => $orgconfig) {
-	
-	$previous = microtime(TRUE);
+if (array_key_exists('orgtest', $_REQUEST)) {
+	$old_error_handler = set_error_handler("myErrorHandler");
 	
-	if ((microtime(TRUE) - $start) > $maxtime) {
-		SimpleSAML_Logger::debug('ldapstatus: Completing execution after maxtime [' .(microtime(TRUE) - $start) . ' of maxtime ' . $maxtime . ']');
-		break;
-	}
-	if (array_key_exists($orgkey, $results)) {
-		SimpleSAML_Logger::debug('ldapstatus: Skipping org already tested [' .$orgkey. ']');
-		continue;
-	} else {
-		SimpleSAML_Logger::debug('ldapstatus: Not Skipping org: [' .$orgkey. ']');
+	echo('<html><head><style>
+	p {
+		font-family: monospace; color: #333;
 	}
-
-	SimpleSAML_Logger::debug('ldapstatus: Executing test on [' .$orgkey . ']');
-
-
-	$results[$orgkey] = array();
-
-	$results[$orgkey]['config'] = checkConfig($orgconfig, array('description', 'searchbase', 'hostname'));
-	$results[$orgkey]['configMeta'] = checkConfig($orgconfig, array(array('contactMail', 'contactURL')));
-	$results[$orgkey]['configTest'] = checkConfig($orgconfig, array('testUser', 'testPassword'));
-
-	if (!$results[$orgkey]['config'][0]) {
-		$results[$orgkey]['time'] = microtime(TRUE) - $previous;
-		continue;
-	}
-
-	$urldef = explode(' ', $orgconfig['hostname']);
-	$url = parse_url($urldef[0]);
-	$port = 389;
-	if (!empty($url['scheme']) && $url['scheme'] === 'ldaps') $port = 636;
-	if (!empty($url['port'])) $port = $url['port'];
 	
-	SimpleSAML_Logger::debug('ldapstatus Url parse [' . $orgconfig['hostname'] . '] => [' . $url['host'] . ']:[' . $port . ']' );
-
+	</style></head><body><h1>Test connection to [' . $_REQUEST['orgtest'] . ']</h1>');
+	$tester = new sspmod_ldapstatus_LDAPTester($orgs[$_REQUEST['orgtest']], $debug, TRUE);
+	$res = $tester->test();
+	echo('<pre>');
+	print_r($res);
+	echo('</p>');
+	echo('</body>');
+	exit;
+}
 
-	$results[$orgkey]['ping'] = phpping($url['host'], $port);
 
-	if (!$results[$orgkey]['ping'][0]) {
-		$results[$orgkey]['time'] = microtime(TRUE) - $previous;
-		continue;
-	}
-	
-	// LDAP Connect
-	try {
-		$ldap = new SimpleSAML_Auth_LDAP($orgconfig['hostname'], (array_key_exists('enable_tls', $orgconfig) ? $orgconfig['enable_tls'] : FALSE), $debug);
-		if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
-		$results[$orgkey]['connect'] = array(TRUE,NULL);
-	} catch (Exception $e) {
-		SimpleSAML_Logger::debug('ldapstatus: Connect error() [' .$orgkey . ']: ' . $e->getMessage());
-		$results[$orgkey]['connect'] = array(FALSE,$e->getMessage());
-		$results[$orgkey]['time'] = microtime(TRUE) - $previous;
-		continue;
-	}
+// Traverse and execute tests for each entry...
+foreach ($orgs AS $orgkey => $orgconfig) {
+	if (array_key_exists($orgkey, $results)) continue;
 
-	// Bind as admin user
-	if (isset($orgconfig['adminUser'])) {
-		try {
-			SimpleSAML_Logger::debug('ldapstatus: Admin bind() [' .$orgkey . ']');
-			$success = $ldap->bind($orgconfig['adminUser'], $orgconfig['adminPassword']);
-			if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
-			if ($success) {
-				$results[$orgkey]['adminBind'] = array(TRUE,NULL);
-			} else {
-				$results[$orgkey]['adminBind'] = array(FALSE,'Could not bind()' );
-			}
-		} catch (Exception $e) {
-			$results[$orgkey]['adminBind'] = array(FALSE,$e->getMessage());
-			$results[$orgkey]['time'] = microtime(TRUE) - $previous;
-			continue;
-		}
-	}
+	SimpleSAML_Logger::debug('ldapstatus: Executing test on ' . $orgkey);
 	
+	$tester = new sspmod_ldapstatus_LDAPTester($orgconfig, $debug);
+	$results[$orgkey] = $tester->test();
 	
-	$eppn = 'asdasdasdasd@feide.no';
-	// Search for bogus user
-	try {
-		$dn = $ldap->searchfordn($orgconfig['searchbase'], 'eduPersonPrincipalName', $eppn, TRUE);
-		if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
-		$results[$orgkey]['ldapSearchBogus'] = array(TRUE,NULL);
-	} catch (Exception $e) {
-		$results[$orgkey]['ldapSearchBogus'] = array(FALSE,$e->getMessage());
-		$results[$orgkey]['time'] = microtime(TRUE) - $previous;
-		continue;
-	}
-
-
-	// If test user is available
-	if (array_key_exists('testUser', $orgconfig)) {
-
-		// Try to search for DN of test account
-		try {
-			$dn = $ldap->searchfordn($orgconfig['searchbase'], 'eduPersonPrincipalName', $orgconfig['testUser']);
-			if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
-			$results[$orgkey]['ldapSearchTestUser'] = array(TRUE,NULL);
-		} catch (Exception $e) {
-			$results[$orgkey]['ldapSearchTestUser'] = array(FALSE,$e->getMessage());
-			$results[$orgkey]['time'] = microtime(TRUE) - $previous;
-			continue;
-		}
-		
-		if ($ldap->bind($dn, $orgconfig['testPassword'])) {
-			$results[$orgkey]['ldapBindTestUser'] = array(TRUE,NULL);
-			
-		} else {
-			$results[$orgkey]['ldapBindTestUser'] = array(FALSE,NULL);
-			$results[$orgkey]['time'] = microtime(TRUE) - $previous;
-			continue;
-		}
-
-		try {
-			$attributes = $ldap->getAttributes($dn, $orgconfig['attributes'], $ldapconfig->getValue('attributesize.max', NULL));
-			if ($ldap->getLastError()) throw new Exception('LDAP warning: ' . $ldap->getLastError());
-			$results[$orgkey]['ldapGetAttributesTestUser'] = array(TRUE,NULL);
-		} catch(Exception $e) {
-			$results[$orgkey]['ldapGetAttributesTestUser'] = array(FALSE,$e->getMessage());
-		}
+	if ((microtime(TRUE) - $start) > $maxtime) {
+		SimpleSAML_Logger::debug('ldapstatus: Completing execution after maxtime [' .(microtime(TRUE) - $start) . ' of maxtime ' . $maxtime . ']');
+		break;
 	}
-	$results[$orgkey]['time'] = microtime(TRUE) - $previous;
 }
 
-$_SESSION['_ldapstatus_results'] = $results;
-
 $session->setData('module:ldapstatus', 'results', $results);
 
 #echo '<pre>'; print_r($results); exit;
@@ -255,9 +131,6 @@ function resultCode($res) {
 	}
 	return $code;
 }
-
-
-
 	
 	
 $ressortable = array();
-- 
GitLab