From ca71bc8df8999a94253e2939e4344c5311b1ea06 Mon Sep 17 00:00:00 2001 From: DL6ER Date: Thu, 29 Apr 2021 09:28:12 +0200 Subject: [PATCH] Check if we can get a host name from the database when looking up the MAC address of this client instead Signed-off-by: DL6ER --- scripts/pi-hole/php/groups.php | 40 ++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/scripts/pi-hole/php/groups.php b/scripts/pi-hole/php/groups.php index af138d9c..efc84815 100644 --- a/scripts/pi-hole/php/groups.php +++ b/scripts/pi-hole/php/groups.php @@ -203,9 +203,45 @@ if ($_POST['action'] == 'get_groups') { throw new Exception('While executing network table statement: ' . $db->lastErrorMsg()); } - // There will always be a result. Unknown host names are NULL + // Check if got a hostname from the database. This may not be the case if the client is + // specified by MAC address, a hostname or via a more general selector like an interface. $name_result = $result->fetchArray(SQLITE3_ASSOC); - $res['name'] = $name_result['name']; + if(!is_bool($name_result)) + { + $res['name'] = $name_result['name']; + error_log("IP: ".$name_result['name']); + } + else + { + // Check if we can get a host name from the database when looking up the MAC + // address of this client instead. + $stmt = $FTLdb->prepare('SELECT name FROM network n JOIN network_addresses na ON na.network_id = n.id WHERE hwaddr=:hwaddr COLLATE NOCASE AND name IS NOT NULL;'); + if (!$stmt) { + throw new Exception('Error while preparing network table statement: ' . $db->lastErrorMsg()); + } + + if (!$stmt->bindValue(':hwaddr', $res['ip'], SQLITE3_TEXT)) { + throw new Exception('While binding to network table statement: ' . $db->lastErrorMsg()); + } + + $result = $stmt->execute(); + if (!$result) { + throw new Exception('While executing network table statement: ' . $db->lastErrorMsg()); + } + + // Check if we found a result. There may be multiple entries for + // this client in the network_addresses table. We use the first + // hostname we find for the sake of simplicity. + $name_result = $result->fetchArray(SQLITE3_ASSOC); + if(!is_bool($name_result)) + { + $res['name'] = $name_result['name']; + } + else + { + $res['name'] = null; + } + } $groups = array(); while ($gres = $group_query->fetchArray(SQLITE3_ASSOC)) {