Commit 1a029c27 authored by Sebastian Kummer's avatar Sebastian Kummer

Merge pull request #92 in ZP/z-push from feature/ZP-765-zlog-syslog-refactor to develop

* commit '701c5142':
  ZP-765 Some tweaks on the config file.
  ZP-765 Revert the delete of variable as they will used in a near future. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Add cache value for the check of the AuthUser in the SpecialLogUser array. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Add AfterInitialization function called in the ZLog static class. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Added a cache value for IsUserInSpecialLogUsers. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 AuthUser is now an instance class variable. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Remove unused parameters. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Moved the content of AuthenticationInfo into the initialize section of the Request static class. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 We should not use array deference because it might not be safe yet. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Removed unused variable. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Use PHP_EOL instead of \n. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Code formatting. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Adding the licence on top of the new files. Released under the Affero GNU General Public License (AGPL) version 3.
  ZP-765 Logging system now uses instance instead of static files. Released under the Affero GNU General Public License (AGPL) version 3.
parents f0543584 701c5142
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* *
* Created : 01.10.2007 * Created : 01.10.2007
* *
* Copyright 2007 - 2013 Zarafa Deutschland GmbH * Copyright 2007 - 2016 Zarafa Deutschland GmbH
* *
* This program is free software: you can redistribute it and/or modify * This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3, * it under the terms of the GNU Affero General Public License, version 3,
...@@ -78,6 +78,12 @@ ...@@ -78,6 +78,12 @@
/********************************************************************************** /**********************************************************************************
* Logging settings * Logging settings
*
* The LOGBACKEND specifies where the logs are sent to.
* Either to file ("filelog") or to a "syslog" server or a custom log class in core/log/logclass.
* filelog and syslog have several options that can be set below.
* For more information about the syslog configuration, see https://wiki.z-hub.io/x/HIAT
* Possible LOGLEVEL and LOGUSERLEVEL values are: * Possible LOGLEVEL and LOGUSERLEVEL values are:
* LOGLEVEL_OFF - no logging * LOGLEVEL_OFF - no logging
* LOGLEVEL_FATAL - log only critical errors * LOGLEVEL_FATAL - log only critical errors
...@@ -92,14 +98,13 @@ ...@@ -92,14 +98,13 @@
* The verbosity increases from top to bottom. More verbose levels include less verbose * The verbosity increases from top to bottom. More verbose levels include less verbose
* ones, e.g. setting to LOGLEVEL_DEBUG will also output LOGLEVEL_FATAL, LOGLEVEL_ERROR, * ones, e.g. setting to LOGLEVEL_DEBUG will also output LOGLEVEL_FATAL, LOGLEVEL_ERROR,
* LOGLEVEL_WARN and LOGLEVEL_INFO level entries. * LOGLEVEL_WARN and LOGLEVEL_INFO level entries.
*
* LOGAUTHFAIL is logged to the LOGBACKEND.
*/ */
define('LOGFILEDIR', '/var/log/z-push/'); define('LOGBACKEND', 'filelog');
define('LOGFILE', LOGFILEDIR . 'z-push.log');
define('LOGERRORFILE', LOGFILEDIR . 'z-push-error.log');
define('LOGLEVEL', LOGLEVEL_WBXML); define('LOGLEVEL', LOGLEVEL_WBXML);
define('LOGAUTHFAIL', false); define('LOGAUTHFAIL', false);
// To save e.g. WBXML data only for selected users, add the usernames to the array // To save e.g. WBXML data only for selected users, add the usernames to the array
// The data will be saved into a dedicated file per user in the LOGFILEDIR // The data will be saved into a dedicated file per user in the LOGFILEDIR
// Users have to be encapusulated in quotes, several users are comma separated, like: // Users have to be encapusulated in quotes, several users are comma separated, like:
...@@ -107,15 +112,20 @@ ...@@ -107,15 +112,20 @@
define('LOGUSERLEVEL', LOGLEVEL_DEVICEID); define('LOGUSERLEVEL', LOGLEVEL_DEVICEID);
$specialLogUsers = array(); $specialLogUsers = array();
// If you want to disable log to file, and log to syslog instead // Filelog settings
define('LOG_SYSLOG_ENABLED', false); define('LOGFILEDIR', '/var/log/z-push/');
define('LOGFILE', LOGFILEDIR . 'z-push.log');
define('LOGERRORFILE', LOGFILEDIR . 'z-push-error.log');
// Syslog settings
// false will log to local syslog, otherwise put the remote syslog IP here // false will log to local syslog, otherwise put the remote syslog IP here
define('LOG_SYSLOG_HOST', false); define('LOG_SYSLOG_HOST', false);
// Syslog port // Syslog port
define('LOG_SYSLOG_PORT', 514); define('LOG_SYSLOG_PORT', 514);
// Program showed in the syslog. Useful if you have more than one instance login to the same syslog // Program showed in the syslog. Useful if you have more than one instance login to the same syslog
define('LOG_SYSLOG_PROGRAM', '[z-push]'); define('LOG_SYSLOG_PROGRAM', 'z-push');
// Syslog facility - use LOG_USER when running on Windows
define('LOG_SYSLOG_FACILITY', LOG_LOCAL0);
// Location of the trusted CA, e.g. '/etc/ssl/certs/EmailCA.pem' // Location of the trusted CA, e.g. '/etc/ssl/certs/EmailCA.pem'
// Uncomment and modify the following line if the validation of the certificates fails. // Uncomment and modify the following line if the validation of the certificates fails.
......
<?php
/*
* Copyright 2015 Leon van Kammen / Coder of Salvation. All rights reserved.
* Modifications 2015 - Francisco Miguel Biete
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY Leon van Kammen / Coder of Salvation AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Leon van Kammen / Coder of Salvation OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of Leon van Kammen / Coder of Salvation
*
* https://github.com/coderofsalvation/syslog-flexible
*/
class ZSyslog {
private static $hostname = false;
private static $port = 514;
private static $program = "[z-push]";
/**
* Initializes the logging
*
* @access public
* @return boolean
*/
public static function Initialize() {
if (defined('LOG_SYSLOG_HOST'))
self::$hostname = LOG_SYSLOG_HOST;
if (defined('LOG_SYSLOG_PORT'))
self::$port = LOG_SYSLOG_PORT;
if (defined('LOG_SYSLOG_PROGRAM'))
self::$program = LOG_SYSLOG_PROGRAM;
}
/**
* Send a message in the syslog facility.
*
* @params int $zlog_level Z-Push LogLevel
* @params string $message
*
* @access public
* @return boolean
*/
public static function send($zlog_level, $message) {
$level = self::zlogLevel2SyslogLevel($zlog_level);
if ($level === false) {
return false;
}
if (self::$hostname === false) {
return syslog($level, $message);
}
else {
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$facility = 1; // user level
$pri = ($facility*8) + $level; // multiplying the Facility number by 8 + adding the level
foreach (explode("\n", $message) as $line) {
if (strlen(trim($line)) > 0) {
$syslog_message = "<{$pri}>" . date('M d H:i:s ') . self::$program . ': ' . $line;
socket_sendto($sock, $syslog_message, strlen($syslog_message), 0, self::$hostname, self::$port);
}
}
socket_close($sock);
}
return true;
}
/**
* Converts the ZLog level to SYSLOG level.
*
* @params int $loglevel Z-Push LogLevel
*
* @access private
* @return SYSLOG_LEVEL or false
*/
private static function zlogLevel2SyslogLevel($loglevel) {
switch($loglevel) {
case LOGLEVEL_OFF: return false; break;
case LOGLEVEL_FATAL: return LOG_ALERT; break;
case LOGLEVEL_ERROR: return LOG_ERR; break;
case LOGLEVEL_WARN: return LOG_WARNING; break;
case LOGLEVEL_INFO: return LOG_INFO; break;
case LOGLEVEL_DEBUG: return LOG_DEBUG; break;
case LOGLEVEL_WBXML: return LOG_DEBUG; break;
case LOGLEVEL_DEVICEID: return LOG_DEBUG; break;
case LOGLEVEL_WBXMLSTACK: return LOG_DEBUG; break;
}
}
}
...@@ -69,8 +69,10 @@ include_once('lib/core/asdevice.php'); ...@@ -69,8 +69,10 @@ include_once('lib/core/asdevice.php');
include_once('lib/core/statemanager.php'); include_once('lib/core/statemanager.php');
include_once('lib/core/devicemanager.php'); include_once('lib/core/devicemanager.php');
include_once('lib/core/zpush.php'); include_once('lib/core/zpush.php');
include_once('include/z_syslog.php');
include_once('lib/core/zlog.php'); include_once('lib/core/zlog.php');
include_once('lib/log/log.php');
include_once('lib/log/filelog.php');
include_once('lib/log/syslog.php');
include_once('lib/interface/ibackend.php'); include_once('lib/interface/ibackend.php');
include_once('lib/interface/ichanges.php'); include_once('lib/interface/ichanges.php');
include_once('lib/interface/iexportchanges.php'); include_once('lib/interface/iexportchanges.php');
...@@ -165,7 +167,7 @@ include_once('version.php'); ...@@ -165,7 +167,7 @@ include_once('version.php');
$backend = ZPush::GetBackend(); $backend = ZPush::GetBackend();
// always request the authorization header // always request the authorization header
if (! Request::AuthenticationInfo() || !Request::GetGETUser()) if (! Request::HasAuthenticationInfo() || !Request::GetGETUser())
throw new AuthenticationRequiredException("Access denied. Please send authorisation information"); throw new AuthenticationRequiredException("Access denied. Please send authorisation information");
// check the provisioning information // check the provisioning information
......
...@@ -42,15 +42,13 @@ ...@@ -42,15 +42,13 @@
************************************************/ ************************************************/
class ZLog { class ZLog {
static private $devid = '';
static private $user = '';
static private $authUser = false;
static private $pidstr;
static private $wbxmlDebug = ''; static private $wbxmlDebug = '';
static private $lastLogs = array(); static private $lastLogs = array();
static private $userLog = false; static private $userLog = false;
static private $unAuthCache = array(); /**
static private $syslogEnabled = false; * @var Log $logger
*/
static private $logger = null;
/** /**
* Initializes the logging * Initializes the logging
...@@ -59,12 +57,7 @@ class ZLog { ...@@ -59,12 +57,7 @@ class ZLog {
* @return boolean * @return boolean
*/ */
static public function Initialize() { static public function Initialize() {
global $specialLogUsers; $logger = self::getLogger();
if (defined('LOG_SYSLOG_ENABLED') && LOG_SYSLOG_ENABLED) {
self::$syslogEnabled = true;
ZSyslog::Initialize();
}
// define some constants for the logging // define some constants for the logging
if (!defined('LOGUSERLEVEL')) if (!defined('LOGUSERLEVEL'))
...@@ -73,27 +66,14 @@ class ZLog { ...@@ -73,27 +66,14 @@ class ZLog {
if (!defined('LOGLEVEL')) if (!defined('LOGLEVEL'))
define('LOGLEVEL', LOGLEVEL_OFF); define('LOGLEVEL', LOGLEVEL_OFF);
list($user,) = Utils::SplitDomainUser(strtolower(Request::GetGETUser())); if (!defined('WBXML_DEBUG')) {
self::$userLog = in_array($user, $specialLogUsers);
if (!defined('WBXML_DEBUG') && $user) {
// define the WBXML_DEBUG mode on user basis depending on the configurations // define the WBXML_DEBUG mode on user basis depending on the configurations
if (LOGLEVEL >= LOGLEVEL_WBXML || (LOGUSERLEVEL >= LOGLEVEL_WBXML && self::$userLog)) if (LOGLEVEL >= LOGLEVEL_WBXML || (LOGUSERLEVEL >= LOGLEVEL_WBXML && $logger->HasSpecialLogUsers()))
define('WBXML_DEBUG', true); define('WBXML_DEBUG', true);
else else
define('WBXML_DEBUG', false); define('WBXML_DEBUG', false);
} }
if ($user)
self::$user = '['. $user .'] ';
else
self::$user = '';
// log the device id if the global loglevel is set to log devid or the user is in and has the right log level
if (Request::GetDeviceID() != "" && (LOGLEVEL >= LOGLEVEL_DEVICEID || (LOGUSERLEVEL >= LOGLEVEL_DEVICEID && self::$userLog)))
self::$devid = '['. Request::GetDeviceID() .'] ';
else
self::$devid = '';
return true; return true;
} }
...@@ -114,39 +94,17 @@ class ZLog { ...@@ -114,39 +94,17 @@ class ZLog {
$message = substr($message, 0, 10240) . sprintf(" <log message with %d bytes truncated>", $messagesize); $message = substr($message, 0, 10240) . sprintf(" <log message with %d bytes truncated>", $messagesize);
self::$lastLogs[$loglevel] = $message; self::$lastLogs[$loglevel] = $message;
$data = self::buildLogString($loglevel) . $message . "\n";
if ($loglevel <= LOGLEVEL) { try {
self::writeToLog($loglevel, $data, LOGFILE); self::getLogger()->Log($loglevel, $message);
}
// should we write this into the user log?
if ($loglevel <= LOGUSERLEVEL && self::$userLog) {
// padd level for better reading
$data = str_replace(self::getLogLevelString($loglevel), self::getLogLevelString($loglevel,true), $data);
// is the user authenticated?
if (self::logToUserFile()) {
// something was logged before the user was authenticated, write this to the log
if (!empty(self::$unAuthCache)) {
self::writeToLog($loglevel, implode('', self::$unAuthCache), LOGFILEDIR . self::logToUserFile() . ".log");
self::$unAuthCache = array();
}
// only use plain old a-z characters for the generic log file
self::writeToLog($loglevel, $data, LOGFILEDIR . self::logToUserFile() . ".log");
}
// the user is not authenticated yet, we save the log into memory for now
else {
self::$unAuthCache[] = $data;
}
} }
catch (\Exception $e) {
if (($loglevel & LOGLEVEL_FATAL) || ($loglevel & LOGLEVEL_ERROR)) { //@TODO How should we handle logging error ?
self::writeToLog($loglevel, $data, LOGERRORFILE); // Ignore any error.
} }
if ($loglevel & LOGLEVEL_WBXMLSTACK) { if ($loglevel & LOGLEVEL_WBXMLSTACK) {
self::$wbxmlDebug .= $message. "\n"; self::$wbxmlDebug .= $message . PHP_EOL;
} }
} }
...@@ -193,101 +151,38 @@ class ZLog { ...@@ -193,101 +151,38 @@ class ZLog {
} }
} }
/**----------------------------------------------------------------------------------------------------------
* private log stuff
*/
/** /**
* Returns the filename logs for a WBXML debug log user should be saved to * Returns the logger object. If no logger has been initialized, FileLog will be initialized and returned.
* *
* @access private * @access private
* @return string * @return Log
* @throws Exception thrown if the logger class cannot be instantiated.
*/ */
static private function logToUserFile() { static private function getLogger() {
global $specialLogUsers; if (!self::$logger) {
global $specialLogUsers; // This variable comes from the configuration file (config.php)
if (self::$authUser === false) { $logger = LOGBACKEND;
if (RequestProcessor::isUserAuthenticated()) { if (!class_exists($logger)) {
$authuser = Request::GetAuthUser(); throw new \Exception('The class `'.$logger.'` does not exist.');
if ($authuser && in_array($authuser, $specialLogUsers))
self::$authUser = preg_replace('/[^a-z0-9]/', '_', strtolower($authuser));
} }
}
return self::$authUser;
}
/** list($user) = Utils::SplitDomainUser(strtolower(Request::GetGETUser()));
* Returns the string to be logged $user = '['.$user.']';
*
* @access private
* @return string
*/
static private function buildLogString($loglevel) {
if (!isset(self::$pidstr))
self::$pidstr = '[' . str_pad(@getmypid(),5," ",STR_PAD_LEFT) . '] ';
if (!isset(self::$user))
self::$user = '';
if (!isset(self::$devid))
self::$devid = '';
if (self::$syslogEnabled)
return self::$pidstr . self::getLogLevelString($loglevel, (LOGLEVEL > LOGLEVEL_INFO)) . " " . self::$user . self::$devid;
else
return Utils::GetFormattedTime() . " " . self::$pidstr . self::getLogLevelString($loglevel, (LOGLEVEL > LOGLEVEL_INFO)) . " " . self::$user . self::$devid;
}
/** self::$logger = new $logger();
* Returns the string representation of the LOGLEVEL. self::$logger->SetUser($user);
* String can be padded self::$logger->SetAuthUser(Request::GetAuthUser());
* self::$logger->SetSpecialLogUsers($specialLogUsers);
* @param int $loglevel one of the LOGLEVELs self::$logger->SetDevid('['. Request::GetDeviceID() .']');
* @param boolean $pad self::$logger->SetPidstr('[' . str_pad(@getmypid(),5," ",STR_PAD_LEFT) . ']');
* self::$logger->AfterInitialize();
* @access private
* @return string
*/
static private function getLogLevelString($loglevel, $pad = false) {
if ($pad) $s = " ";
else $s = "";
switch($loglevel) {
case LOGLEVEL_OFF: return ""; break;
case LOGLEVEL_FATAL: return "[FATAL]"; break;
case LOGLEVEL_ERROR: return "[ERROR]"; break;
case LOGLEVEL_WARN: return "[".$s."WARN]"; break;
case LOGLEVEL_INFO: return "[".$s."INFO]"; break;
case LOGLEVEL_DEBUG: return "[DEBUG]"; break;
case LOGLEVEL_WBXML: return "[WBXML]"; break;
case LOGLEVEL_DEVICEID: return "[DEVICEID]"; break;
case LOGLEVEL_WBXMLSTACK: return "[WBXMLSTACK]"; break;
} }
return self::$logger;
} }
/** /**----------------------------------------------------------------------------------------------------------
* Write the message to the log facility. * private log stuff
*
* @param int $loglevel
* @param string $data
* @param string $logfile
*
* @access private
* @return void
*/ */
static private function writeToLog($loglevel, $data, $logfile = null) {
if (self::$syslogEnabled) {
if (ZSyslog::send($loglevel, $data) === false) {
error_log("Unable to send to syslog");
error_log($data);
}
}
else {
if (@file_put_contents($logfile, $data, FILE_APPEND) === false) {
error_log(sprintf("Unable to write in %s", $logfile));
error_log($data);
}
}
}
} }
/**---------------------------------------------------------------------------------------------------------- /**----------------------------------------------------------------------------------------------------------
......
...@@ -220,24 +220,57 @@ class ZPush { ...@@ -220,24 +220,57 @@ class ZPush {
else else
define('REAL_BASE_PATH', BASE_PATH); define('REAL_BASE_PATH', BASE_PATH);
if (!defined('LOGFILEDIR')) if (!defined('LOGBACKEND')) {
throw new FatalMisconfigurationException("The LOGFILEDIR is not configured. Check if the config.php file is in place."); define('LOGBACKEND', 'filelog');
}
if (substr(LOGFILEDIR, -1,1) != "/") if (LOGBACKEND == 'syslog') {
throw new FatalMisconfigurationException("The LOGFILEDIR should terminate with a '/'");
if (!file_exists(LOGFILEDIR)) if (!defined('LOG_SYSLOG_FACILITY')) {
throw new FatalMisconfigurationException("The configured LOGFILEDIR does not exist or can not be accessed."); define('LOG_SYSLOG_FACILITY', LOG_LOCAL0);
}
if ((!file_exists(LOGFILE) && !touch(LOGFILE)) || !is_writable(LOGFILE)) if (!defined('LOG_SYSLOG_HOST')) {
throw new FatalMisconfigurationException("The configured LOGFILE can not be modified."); define('LOG_SYSLOG_HOST', false);
}
if ((!file_exists(LOGERRORFILE) && !touch(LOGERRORFILE)) || !is_writable(LOGERRORFILE)) if (!defined('LOG_SYSLOG_PORT')) {
throw new FatalMisconfigurationException("The configured LOGERRORFILE can not be modified."); define('LOG_SYSLOG_PORT', 514);
}
// check ownership on the (eventually) just created files if (!defined('LOG_SYSLOG_PROGRAM')) {
Utils::FixFileOwner(LOGFILE); define('LOG_SYSLOG_PROGRAM', 'z-push');
Utils::FixFileOwner(LOGERRORFILE); }
if (!is_numeric(LOG_SYSLOG_PORT)) {
throw new FatalMisconfigurationException("The LOG_SYSLOG_PORT must a be a number.");
}
if (LOG_SYSLOG_HOST && LOG_SYSLOG_PORT <= 0) {
throw new FatalMisconfigurationException("LOG_SYSLOG_HOST is defined but the LOG_SYSLOG_PORT does not seem to be valid.");
}
}
elseif (LOGBACKEND == 'filelog') {
if (!defined('LOGFILEDIR'))
throw new FatalMisconfigurationException("The LOGFILEDIR is not configured. Check if the config.php file is in place.");
if (substr(LOGFILEDIR, -1,1) != "/")
throw new FatalMisconfigurationException("The LOGFILEDIR should terminate with a '/'");
if (!file_exists(LOGFILEDIR))
throw new FatalMisconfigurationException("The configured LOGFILEDIR does not exist or can not be accessed.");
if ((!file_exists(LOGFILE) && !touch(LOGFILE)) || !is_writable(LOGFILE))
throw new FatalMisconfigurationException("The configured LOGFILE can not be modified.");
if ((!file_exists(LOGERRORFILE) && !touch(LOGERRORFILE)) || !is_writable(LOGERRORFILE))
throw new FatalMisconfigurationException("The configured LOGERRORFILE can not be modified.");
// check ownership on the (eventually) just created files
Utils::FixFileOwner(LOGFILE);
Utils::FixFileOwner(LOGERRORFILE);
}
// set time zone // set time zone
// code contributed by Robert Scheck (rsc) // code contributed by Robert Scheck (rsc)
......
<?php
/***********************************************
* File : filelog.php
* Project : Z-Push
* Descr : Logging functionalities
*
* Created : 13.11.2015
*
* Copyright 2007 - 2015 Zarafa Deutschland GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation with the following additional
* term according to sec. 7:
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "Zarafa" is a registered trademark of Zarafa B.V.
* "Z-Push" is a registered trademark of Zarafa Deutschland GmbH
* The licensing of the Program under the AGPL does not imply a trademark license.
* Therefore any rights, title and interest in our trademarks remain entirely with us.
*
* However, if you propagate an unmodified version of the Program you are
* allowed to use the term "Z-Push" to indicate that you distribute the Program.
* Furthermore you may use our trademarks where it is necessary to indicate
* the intended purpose of a product or service provided you use it in accordance
* with honest practices in industrial or commercial matters.
* If you want to propagate modified versions of the Program under the name "Z-Push",
* you may only do so if you have a written permission by Zarafa Deutschland GmbH
* (to acquire a permission please contact Zarafa at trademark@zarafa.com).
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Consult LICENSE file for details
************************************************/
class FileLog extends Log {
/**
* @var string|bool
*/
private $log_to_user_file = false;
/**
* Get the log user file.
*
* @access private
* @return string
*/
private function getLogToUserFile() {
if ($this->log_to_user_file === false) {
$this->setLogToUserFile(preg_replace('/[^a-z0-9]/', '_', strtolower($this->GetAuthUser())) . '.log');
}
return $this->log_to_user_file;
}
/**
* @param string $value
*/
private function setLogToUserFile($value) {
$this->log_to_user_file = $value;
}
public function __construct() {
}
/**
* Returns the string to be logged
*
* @param int $loglevel
* @param string $message
*
* @access public
* @return string
*/
public function BuildLogString($loglevel, $message) {
$log = Utils::GetFormattedTime() . $this->GetPidstr() . $this->GetLogLevelString($loglevel, $loglevel >= LOGLEVEL_INFO) . ' ' . $this->GetUser();
if ($loglevel >= LOGLEVEL_DEVICEID) {
$log .= $this->GetDevid();
}
$log .= ' ' . $message;
return $log;
}
//
// Implementation of Log
//
protected function Write($loglevel, $message) {
$data = $this->buildLogString($loglevel, $message) . PHP_EOL;
@file_put_contents(LOGFILE, $data, FILE_APPEND);
if (($loglevel & LOGLEVEL_FATAL) || ($loglevel & LOGLEVEL_ERROR)) {
@file_put_contents(LOGERRORFILE, $data, FILE_APPEND);
}
}
public function WriteForUser($loglevel, $message) {
$data = $this->buildLogString($loglevel, $message) . PHP_EOL;
@file_put_contents(LOGFILEDIR . $this->getLogToUserFile(), $data, FILE_APPEND);
}
protected function afterLog($loglevel, $message) {
if (($loglevel & LOGLEVEL_FATAL) || ($loglevel & LOGLEVEL_ERROR)) {
$data = $this->buildLogString($loglevel, $message) . PHP_EOL;
@file_put_contents(LOGERRORFILE, $data, FILE_APPEND);
}
}
}
<?php
/***********************************************
* File : log.php
* Project : Z-Push
* Descr : Logging functionalities
*
* Created : 13.11.2015
*
* Copyright 2007 - 2015 Zarafa Deutschland GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation with the following additional
* term according to sec. 7:
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "Zarafa" is a registered trademark of Zarafa B.V.
* "Z-Push" is a registered trademark of Zarafa Deutschland GmbH
* The licensing of the Program under the AGPL does not imply a trademark license.
* Therefore any rights, title and interest in our trademarks remain entirely with us.
*
* However, if you propagate an unmodified version of the Program you are
* allowed to use the term "Z-Push" to indicate that you distribute the Program.
* Furthermore you may use our trademarks where it is necessary to indicate
* the intended purpose of a product or service provided you use it in accordance
* with honest practices in industrial or commercial matters.
* If you want to propagate modified versions of the Program under the name "Z-Push",
* you may only do so if you have a written permission by Zarafa Deutschland GmbH
* (to acquire a permission please contact Zarafa at trademark@zarafa.com).
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Consult LICENSE file for details
************************************************/
abstract class Log {
/**
* @var string
*/
protected $user = '';
/**
* @var string
*/
protected $authUser = '';
/**
* @var string
*/
protected $devid = '';
/**
* @var string
*/
protected $pidstr = '';
/**
* @var array
*/
protected $specialLogUsers = array();
/**
* Only used as a cache value for IsUserInSpecialLogUsers.
* @var array
*/
private $isUserInSpecialLogUsers = array();
/**
* Only used as a cache value for IsAuthUserInSpecialLogUsers function
* @var bool
*/
private $isAuthUserInSpecialLogUsers = false;
/**
* @var array
*/
private $unauthMessageCache = array();
/**
* @access public
* @return string
*/
public function GetUser() {
return $this->user;
}
/**
* @param string $value
*
* @access public
*/
public function SetUser($value) {
$this->user = $value;
}
/**
* @access public
* @return string
*/
public function GetAuthUser() {
return $this->authUser;
}
/**
* @param string $value
*
* @access public
*/
public function SetAuthUser($value) {
$this->isAuthUserInSpecialLogUsers = false;
$this->authUser = $value;
}
/**
* Check that the current authUser ($this->GetAuthUser) is in the special log user array.
* This call is equivalent to `$this->IsUserInSpecialLogUsers($this->GetAuthUser())` at the exception that this
* call uses cache so there won't be more than one check to the specialLogUser for the AuthUser.
*
* @access public
* @return bool
*/
public function IsAuthUserInSpecialLogUsers(){
if ($this->isAuthUserInSpecialLogUsers) {
return true;
}
if($this->IsUserInSpecialLogUsers($this->GetAuthUser())){
$this->isAuthUserInSpecialLogUsers = true;
return true;
}
return false;
}
/**
* @access public
* @return string
*/
public function GetDevid() {
return $this->devid;
}
/**
* @param string $value
*
* @access public
*/
public function SetDevid($value) {
$this->devid = $value;
}
/**
* @access public
* @return string
*/
public function GetPidstr() {
return $this->pidstr;
}
/**
* @param string $value
*
* @access public
*/
public function SetPidstr($value) {
$this->pidstr = $value;
}
/**
* @access public
* @return bool True if we do have to log some specific user. False otherwise.
*/
public function HasSpecialLogUsers() {
return !empty($this->specialLogUsers);
}
/**
* @param string $user
*
* @acces public
* @return bool
*/
public function IsUserInSpecialLogUsers($user) {
if (isset($this->isUserInSpecialLogUsers[$user])) {
return true;
}
if ($this->HasSpecialLogUsers() && in_array($user, $this->GetSpecialLogUsers())) {
$this->isUserInSpecialLogUsers[$user] = true;
return true;
}
return false;
}
/**
* @access public
* @return array
*/
public function GetSpecialLogUsers() {
return $this->specialLogUsers;
}
/**
* @param array $value
*
* @access public
*/
public function SetSpecialLogUsers(array $value) {
$this->isUserInSpecialLogUsers = array(); // reset cache
$this->specialLogUsers = $value;
}
public function __construct() {
}
/**
* @param int $loglevel
* @param string $message
*/
public function Log($loglevel, $message) {
if ($loglevel <= LOGLEVEL) {
$this->Write($loglevel, $message);
}
if ($loglevel <= LOGUSERLEVEL && $this->IsAuthUserInSpecialLogUsers()) {
if (RequestProcessor::isUserAuthenticated()) {
// something was logged before the user was authenticated, write this to the log
if (!empty($this->unauthMessageCache)) {
foreach ($this->unauthMessageCache as $authcache) {
$this->WriteForUser($authcache[0], $authcache[1]);
}
self::$unAuthCache = array();
}
$this->WriteForUser($loglevel, $message);
}
else {
$this->unauthMessageCache[] = array($loglevel, $message);
}
}
$this->afterLog($loglevel, $message);
}
/**
* This function is used as an event for log implementer.
* It happens when the ZLog static class is finished with the initialization of this instance.
*/
public function AfterInitialize() {
}
/**
* This function is used as an event for log implementer.
* It happens when the a call to the Log function is finished.
*/
protected function afterLog($loglevel, $message) {
}
/**
* Returns the string representation of the given $loglevel.
* String can be padded
*
* @param int $loglevel one of the LOGLEVELs
* @param boolean $pad
*
* @access protected
* @return string
*/
protected function GetLogLevelString($loglevel, $pad = false) {
if ($pad)
$s = " ";
else
$s = "";
switch($loglevel) {
case LOGLEVEL_OFF: return ""; break;
case LOGLEVEL_FATAL: return "[FATAL]"; break;
case LOGLEVEL_ERROR: return "[ERROR]"; break;
case LOGLEVEL_WARN: return "[".$s."WARN]"; break;
case LOGLEVEL_INFO: return "[".$s."INFO]"; break;
case LOGLEVEL_DEBUG: return "[DEBUG]"; break;
case LOGLEVEL_WBXML: return "[WBXML]"; break;
case LOGLEVEL_DEVICEID: return "[DEVICEID]"; break;
case LOGLEVEL_WBXMLSTACK: return "[WBXMLSTACK]"; break;
}
}
/**
* @param int $loglevel
* @param string $message
*
* @access public
* @return null
*/
abstract protected function Write($loglevel, $message);
/**
* @param int $loglevel
* @param string $message
*
* @access public
* @return null
*/
abstract public function WriteForUser($loglevel, $message);
}
\ No newline at end of file
<?php
/***********************************************
* File : syslog.php
* Project : Z-Push
* Descr : Logging functionalities
*
* Created : 13.11.2015
*
* Copyright 2007 - 2015 Zarafa Deutschland GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation with the following additional
* term according to sec. 7:
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "Zarafa" is a registered trademark of Zarafa B.V.
* "Z-Push" is a registered trademark of Zarafa Deutschland GmbH
* The licensing of the Program under the AGPL does not imply a trademark license.
* Therefore any rights, title and interest in our trademarks remain entirely with us.
*
* However, if you propagate an unmodified version of the Program you are
* allowed to use the term "Z-Push" to indicate that you distribute the Program.
* Furthermore you may use our trademarks where it is necessary to indicate
* the intended purpose of a product or service provided you use it in accordance
* with honest practices in industrial or commercial matters.
* If you want to propagate modified versions of the Program under the name "Z-Push",
* you may only do so if you have a written permission by Zarafa Deutschland GmbH
* (to acquire a permission please contact Zarafa at trademark@zarafa.com).
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Consult LICENSE file for details
************************************************/
class Syslog extends Log {
protected $program_name = '';
protected $host;
protected $port;
/**
* @access public
* @return string
*/
public function GetProgramName() {
return $this->program_name;
}
/**
* @param string $value
*
* @access public
*/
public function SetProgramName($value) {
$this->program_name = $value;
}
/**
* @access public
* @return string
*/
public function GetHost() {
return $this->host;
}
/**
* @param string $value
*
* @access public
*/
public function SetHost($value) {
$this->host = $value;
}
/**
* @access public
* @return int
*/
public function GetPort() {
return $this->port;
}
/**
* @param int $value
*
* @access public
*/
public function SetPort($value) {
if (is_numeric($value)) {
$this->port = (int)$value;
}
}
public function __construct($program_name = null, $host = null, $port = null) {
parent::__construct();
if (is_null($program_name)) $program_name = LOG_SYSLOG_PROGRAM;
if (is_null($host)) $host = LOG_SYSLOG_HOST;
if (is_null($port)) $port = LOG_SYSLOG_PORT;
$this->SetProgramName($program_name);
$this->SetHost($host);
$this->SetPort($port);
}
/**
* Return the full program name for syslog.
* The name can be z-push/core or z-push/{backend} where backend is the backend that initiated the log.
*
* @access protected
* @return string
*/
protected function GenerateProgramName() {
// @TODO Use another mechanism than debug_backtrace to determine to origin of the log
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
// Shift the "syslog.php" entry.
array_shift($backtrace);
foreach ($backtrace as $trace) {
if (!isset($trace['file'])) {
continue;
}
if (strpos($trace['file'], REAL_BASE_PATH . 'backend/') !== false) {
preg_match('/\/backend\/([a-zA-Z]*)/', $trace['file'], $match);
if (isset($match[1])) {
return $this->GetProgramName() . '/' . $match[1];
}
} elseif (basename($trace['file'], '.php') != 'zlog') {
return $this->GetProgramName() . '/core';
}
}
return $this->GetProgramName() . '/core';
}
/**
* Maps the z-push loglevel with those of syslog.
*
* @access protected
* @param int $loglevel
* @return int One of many LOG_* syslog level.
*/
protected function GetZpushLogLevelToSyslogLogLevel($loglevel) {
switch ($loglevel) {
case LOGLEVEL_FATAL: return LOG_ALERT; break;
case LOGLEVEL_ERROR: return LOG_ERR; break;
case LOGLEVEL_WARN: return LOG_WARNING; break;
case LOGLEVEL_INFO: return LOG_INFO; break;
case LOGLEVEL_DEBUG: return LOG_DEBUG; break;
case LOGLEVEL_WBXML: return LOG_DEBUG; break;
case LOGLEVEL_DEVICEID: return LOG_DEBUG; break;
case LOGLEVEL_WBXMLSTACK: return LOG_DEBUG; break;
}
return null;
}
/**
* Build the log string for syslog.
*
* @param int $loglevel
* @param string $message
*
* @access public
* @return string
*/
public function BuildLogString($loglevel, $message) {
$log = $this->GetLogLevelString($loglevel); // Never pad syslog log because syslog log are usually read with a software.
$log .= $this->GetUser();
if ($loglevel >= LOGLEVEL_DEVICEID) {
$log .= $this->GetDevid();
}
$log .= ' ' . $message;
return $log;
}
//
// Implementation of Log
//
protected function Write($loglevel, $message) {
if ($this->GetHost() && $this->GetPort()) {
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
$facility = 1; // user level
$pri = ($facility * 8) + $loglevel; // multiplying the Facility number by 8 + adding the level
$data = $this->buildLogString($loglevel, $message);
if (strlen(trim($data)) > 0) {
$syslog_message = "<{$pri}>" . date('M d H:i:s ') . '[' . $this->GetProgramName() . ']: ' . $data;
socket_sendto($sock, $syslog_message, strlen($syslog_message), 0, $this->GetHost(), $this->GetPort());
}
socket_close($sock);
} else {
openlog($this->GenerateProgramName(), LOG_PID, LOG_SYSLOG_FACILITY);
syslog(
$this->GetZpushLogLevelToSyslogLogLevel($loglevel),
$this->buildLogString($loglevel, $message)
);
}
}
public function WriteForUser($loglevel, $message) {
$this->Write(LOGLEVEL_DEBUG, $message); // Always pass the logleveldebug so it uses syslog level LOG_DEBUG
}
}
\ No newline at end of file
...@@ -74,9 +74,7 @@ class Request { ...@@ -74,9 +74,7 @@ class Request {
static private $input; static private $input;
static private $output; static private $output;
static private $headers; static private $headers;
static private $getparameters;
static private $command; static private $command;
static private $device;
static private $method; static private $method;
static private $remoteAddr; static private $remoteAddr;
static private $getUser; static private $getUser;
...@@ -91,7 +89,7 @@ class Request { ...@@ -91,7 +89,7 @@ class Request {
static private $attachmentName; static private $attachmentName;
static private $collectionId; static private $collectionId;
static private $itemId; static private $itemId;
static private $longId; //TODO static private $longId; // TODO
static private $occurence; //TODO static private $occurence; //TODO
static private $saveInSent; static private $saveInSent;
static private $acceptMultipart; static private $acceptMultipart;
...@@ -186,6 +184,16 @@ class Request { ...@@ -186,6 +184,16 @@ class Request {
self::$getUser = Utils::GetLocalPartFromEmail(self::$getUser); self::$getUser = Utils::GetLocalPartFromEmail(self::$getUser);
} }
} }
// authUser & authPassword are unfiltered!
// split username & domain if received as one
if (isset($_SERVER['PHP_AUTH_USER'])) {
list(self::$authUser, self::$authDomain) = Utils::SplitDomainUser($_SERVER['PHP_AUTH_USER']);
self::$authPassword = (isset($_SERVER['PHP_AUTH_PW']))?$_SERVER['PHP_AUTH_PW'] : "";
}
if(defined('USE_FULLEMAIL_FOR_LOGIN') && ! USE_FULLEMAIL_FOR_LOGIN) {
self::$authUser = Utils::GetLocalPartFromEmail(self::$authUser);
}
} }
/** /**
...@@ -234,21 +242,10 @@ class Request { ...@@ -234,21 +242,10 @@ class Request {
} }
/** /**
* Reads and parses the HTTP-Basic-Auth data
*
* @access public * @access public
* @return boolean data sent or not * @return boolean data sent or not
*/ */
static public function AuthenticationInfo() { static public function HasAuthenticationInfo() {
// split username & domain if received as one
if (isset($_SERVER['PHP_AUTH_USER'])) {
list(self::$authUser, self::$authDomain) = Utils::SplitDomainUser($_SERVER['PHP_AUTH_USER']);
self::$authPassword = (isset($_SERVER['PHP_AUTH_PW']))?$_SERVER['PHP_AUTH_PW'] : "";
}
if(defined('USE_FULLEMAIL_FOR_LOGIN') && ! USE_FULLEMAIL_FOR_LOGIN) {
self::$authUser = Utils::GetLocalPartFromEmail(self::$authUser);
}
// authUser & authPassword are unfiltered!
return (self::$authUser != "" && self::$authPassword != ""); return (self::$authUser != "" && self::$authPassword != "");
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment