<?php
/*****************************************************************************
 *
 * CoreLogonMultisite.php - Module for handling cookie based logins as
 *                          generated by multisite
 *
 * Copyright (c) 2004-2011 NagVis Project (Contact: info@nagvis.org)
 *
 * License:
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *****************************************************************************/

class CoreLogonMultisite extends CoreLogonModule {
    private   $htpasswdPath;
    private   $secretPath;

    public function __construct() {
        $this->htpasswdPath = cfg('global', 'logon_multisite_htpasswd');
        $this->secretPath   = cfg('global', 'logon_multisite_secret');

        if(!file_exists($this->htpasswdPath)) {
            throw new NagVisException(l('LogonMultisite: The htpasswd file &quot;[PATH]&quot; does not exist.',
                          array('PATH' => $this->htpasswdPath)));
        }
        if(!file_exists($this->secretPath)) {
            $this->redirectToLogin();
            //throw new NagVisException(l('LogonMultisite: The auth secret file &quot;[PATH]&quot; does not exist.',
            //              array('PATH' => $this->secretPath)));
        }
    }

    private function loadHtpasswd() {
        $creds = array();
        foreach(file($this->htpasswdPath) AS $line) {
            list($username, $pwhash) = explode(':', $line, 2);
            $creds[$username] = rtrim($pwhash);
        }
        return $creds;
    }

    private function loadSecret() {
        return trim(file_get_contents($this->secretPath));
    }

    private function generateHash($username, $now, $pwhash) {
        $secret = $this->loadSecret();
        return md5($username . $now . $pwhash . $secret);
    }

    private function checkAuthCookie($cookieName) {
        if(!isset($_COOKIE[$cookieName]) || $_COOKIE[$cookieName] == '') {
            throw new Exception();
        }

        list($username, $issueTime, $cookieHash) = explode(':', $_COOKIE[$cookieName], 3);

        // FIXME: Check expire time?
        
        $users = $this->loadHtpasswd();
        if(!isset($users[$username])) {
            throw new Exception();
        }
        $pwhash = $users[$username];

        // Validate the hash
        if($cookieHash != $this->generateHash($username, $issueTime, $pwhash)) {
            throw new Exception();
        }

        // FIXME: Maybe renew the cookie here too

        return $username;
    }

    private function checkAuth() {
        // Loop all cookies trying to fetch a valid authentication
        // cookie for this installation
        foreach(array_keys($_COOKIE) AS $cookieName) {
            if(substr($cookieName, 0, 5) != 'auth_') {
                continue;
            }
            try {
                $name = $this->checkAuthCookie($cookieName);

                session_start();
                $_SESSION['multisiteLogonCookie'] = $cookieName;
                session_write_close();

                return $name;
            } catch(Exception $e) {}
        }
        return '';
    }

    private function redirectToLogin() {
        // Do not redirect on ajax calls. Print out errors instead
        if(CONST_AJAX) {
            throw new NagVisException(l('LogonMultisite: Not authenticated.'));
        }
        // FIXME: Get the real path to multisite
        header('Location:../../../check_mk/login.py?_origtarget=' . $_SERVER['REQUEST_URI']);
    }

    public function check($printErr = true) {
        global $AUTH, $CORE;

        $username = $this->checkAuth();
        if($username === '') {
            $this->redirectToLogin();
            return false;
        }

        // Check if the user exists
        if($this->verifyUserExists($username,
                        cfg('global', 'logon_multisite_createuser'),
                        cfg('global', 'logon_multisite_createrole'),
                        $printErr) === false) {
            return false;
        }

        $AUTH->setTrustUsername(true);
        $AUTH->setLogoutPossible(false);
        $AUTH->passCredentials(Array('user' => $username));
        return $AUTH->isAuthenticated();
    }
}

?>
