From 8db5b121ff0ac7a7f218605e039ad8f273f18ae3 Mon Sep 17 00:00:00 2001 From: Michael Date: Sat, 9 Dec 2017 09:46:21 +0000 Subject: [PATCH 1/3] Prevent the running of multiple xmpp auth daemons at a time --- doc/htconfig.md | 1 + src/Util/ExAuth.php | 659 +++++++++++++++++++++++-------------------- src/Util/Pidfile.php | 48 ++-- 3 files changed, 385 insertions(+), 323 deletions(-) diff --git a/doc/htconfig.md b/doc/htconfig.md index 4d7816f49a..34045e5c12 100644 --- a/doc/htconfig.md +++ b/doc/htconfig.md @@ -19,6 +19,7 @@ Example: To set the directory value please add this line to your .htconfig.php: ## jabber ## * **debug** (Boolean) - Enable debug level for the jabber account synchronisation. +* **lockpath** - Must be writable by the ejabberd process. if set then it will prevent the running of multiple processes. ## system ## diff --git a/src/Util/ExAuth.php b/src/Util/ExAuth.php index f4dc7c052b..c68cd41166 100644 --- a/src/Util/ExAuth.php +++ b/src/Util/ExAuth.php @@ -1,306 +1,353 @@ - - * modified for Friendica by Michael Vogel - * published under GPL - * - * Latest version of the original script for joomla is available at: - * http://87.230.15.86/~dado/ejabberd/joomla-login - * - * Installation: - * - * - Change it's owner to whichever user is running the server, ie. ejabberd - * $ chown ejabberd:ejabberd /path/to/friendica/scripts/auth_ejabberd.php - * - * - Change the access mode so it is readable only to the user ejabberd and has exec - * $ chmod 700 /path/to/friendica/scripts/auth_ejabberd.php - * - * - Edit your ejabberd.cfg file, comment out your auth_method and add: - * {auth_method, external}. - * {extauth_program, "/path/to/friendica/script/auth_ejabberd.php"}. - * - * - Restart your ejabberd service, you should be able to login with your friendica auth info - * - * Other hints: - * - if your users have a space or a @ in their nickname, they'll run into trouble - * registering with any client so they should be instructed to replace these chars - * " " (space) is replaced with "%20" - * "@" is replaced with "(a)" - * - */ - -namespace Friendica\Util; - -use Friendica\Core\Config; -use Friendica\Core\PConfig; -use Friendica\Database\DBM; -use Friendica\Model\User; -use dba; - -require_once 'include/dba.php'; - -class ExAuth -{ - private $bDebug; - - /** - * @brief Create the class - * - * @param boolean $bDebug Debug mode - */ - public function __construct() - { - $this->bDebug = (int) Config::get('jabber', 'debug'); - - openlog('auth_ejabberd', LOG_PID, LOG_USER); - - $this->writeLog(LOG_NOTICE, 'start'); - } - - /** - * @brief Standard input reading function, executes the auth with the provided - * parameters - * - * @return null - */ - public function readStdin() - { - while (!feof(STDIN)) { - // Quit if the database connection went down - if (!dba::connected()) { - $this->writeLog(LOG_ERR, 'the database connection went down'); - return; - } - - $iHeader = fgets(STDIN, 3); - $aLength = unpack('n', $iHeader); - $iLength = $aLength['1']; - - // No data? Then quit - if ($iLength == 0) { - $this->writeLog(LOG_ERR, 'we got no data, quitting'); - return; - } - - // Fetching the data - $sData = fgets(STDIN, $iLength + 1); - $this->writeLog(LOG_DEBUG, 'received data: ' . $sData); - $aCommand = explode(':', $sData); - if (is_array($aCommand)) { - switch ($aCommand[0]) { - case 'isuser': - // Check the existance of a given username - $this->isUser($aCommand); - break; - case 'auth': - // Check if the givven password is correct - $this->auth($aCommand); - break; - case 'setpass': - // We don't accept the setting of passwords here - $this->writeLog(LOG_NOTICE, 'setpass command disabled'); - fwrite(STDOUT, pack('nn', 2, 0)); - break; - default: - // We don't know the given command - $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]); - fwrite(STDOUT, pack('nn', 2, 0)); - break; - } - } else { - $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData); - fwrite(STDOUT, pack('nn', 2, 0)); - } - } - } - - /** - * @brief Check if the given username exists - * - * @param array $aCommand The command array - */ - private function isUser(array $aCommand) - { - $a = get_app(); - - // Check if there is a username - if (!isset($aCommand[1])) { - $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given'); - fwrite(STDOUT, pack('nn', 2, 0)); - return; - } - - // Now we check if the given user is valid - $sUser = str_replace(array('%20', '(a)'), array(' ', '@'), $aCommand[1]); - - // Does the hostname match? So we try directly - if ($a->get_hostname() == $aCommand[2]) { - $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]); - $found = dba::exists('user', ['nickname' => $sUser]); - } else { - $found = false; - } - - // If the hostnames doesn't match or there is some failure, we try to check remotely - if (!$found) { - $found = $this->checkUser($aCommand[2], $aCommand[1], true); - } - - if ($found) { - // The user is okay - $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser); - fwrite(STDOUT, pack('nn', 2, 1)); - } else { - // The user isn't okay - $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser); - fwrite(STDOUT, pack('nn', 2, 0)); - } - } - - /** - * @brief Check remote user existance via HTTP(S) - * - * @param string $host The hostname - * @param string $user Username - * @param boolean $ssl Should the check be done via SSL? - * - * @return boolean Was the user found? - */ - private function checkUser($host, $user, $ssl) - { - $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host); - - $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user; - - $data = z_fetch_url($url); - - if (!is_array($data)) { - return false; - } - - if ($data['return_code'] != '200') { - return false; - } - - $json = @json_decode($data['body']); - if (!is_object($json)) { - return false; - } - - return $json->nick == $user; - } - - /** - * @brief Authenticate the given user and password - * - * @param array $aCommand The command array - */ - private function auth(array $aCommand) - { - $a = get_app(); - - // check user authentication - if (sizeof($aCommand) != 4) { - $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing'); - fwrite(STDOUT, pack('nn', 2, 0)); - return; - } - - // We now check if the password match - $sUser = str_replace(array('%20', '(a)'), array(' ', '@'), $aCommand[1]); - - // Does the hostname match? So we try directly - if ($a->get_hostname() == $aCommand[2]) { - $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]); - - $aUser = dba::select('user', ['uid', 'password'], ['nickname' => $sUser], ['limit' => 1]); - if (DBM::is_result($aUser)) { - $uid = User::authenticate($aUser, $aCommand[3]); - $Error = $uid === false; - } else { - $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser); - $Error = true; - $uid = -1; - } - if ($Error) { - $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]); - $sPassword = PConfig::get($uid, 'xmpp', 'password', null, true); - $Error = ($aCommand[3] != $sPassword); - } - } else { - $Error = true; - } - - // If the hostnames doesn't match or there is some failure, we try to check remotely - if ($Error) { - $Error = !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true); - } - - if ($Error) { - $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]); - fwrite(STDOUT, pack('nn', 2, 0)); - } else { - $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]); - fwrite(STDOUT, pack('nn', 2, 1)); - } - } - - /** - * @brief Check remote credentials via HTTP(S) - * - * @param string $host The hostname - * @param string $user Username - * @param string $password Password - * @param boolean $ssl Should the check be done via SSL? - * - * @return boolean Are the credentials okay? - */ - private function checkCredentials($host, $user, $password, $ssl) - { - $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json'; - - $ch = curl_init(); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); - curl_setopt($ch, CURLOPT_HEADER, true); - curl_setopt($ch, CURLOPT_NOBODY, true); - curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); - curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password); - - curl_exec($ch); - $curl_info = @curl_getinfo($ch); - $http_code = $curl_info['http_code']; - curl_close($ch); - - $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code); - - return $http_code == 200; - } - - /** - * @brief write data to the syslog - * - * @param integer $loglevel The syslog loglevel - * @param string $sMessage The syslog message - */ - private function writeLog($loglevel, $sMessage) - { - if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) { - return; - } - syslog($loglevel, $sMessage); - } - - /** - * @brief destroy the class, close the syslog connection. - */ - public function __destruct() - { - $this->writeLog(LOG_NOTICE, 'stop'); - closelog(); - } -} + + * modified for Friendica by Michael Vogel + * published under GPL + * + * Latest version of the original script for joomla is available at: + * http://87.230.15.86/~dado/ejabberd/joomla-login + * + * Installation: + * + * - Change it's owner to whichever user is running the server, ie. ejabberd + * $ chown ejabberd:ejabberd /path/to/friendica/scripts/auth_ejabberd.php + * + * - Change the access mode so it is readable only to the user ejabberd and has exec + * $ chmod 700 /path/to/friendica/scripts/auth_ejabberd.php + * + * - Edit your ejabberd.cfg file, comment out your auth_method and add: + * {auth_method, external}. + * {extauth_program, "/path/to/friendica/script/auth_ejabberd.php"}. + * + * - Restart your ejabberd service, you should be able to login with your friendica auth info + * + * Other hints: + * - if your users have a space or a @ in their nickname, they'll run into trouble + * registering with any client so they should be instructed to replace these chars + * " " (space) is replaced with "%20" + * "@" is replaced with "(a)" + * + */ + +namespace Friendica\Util; + +use Friendica\Core\Config; +use Friendica\Core\PConfig; +use Friendica\Database\DBM; +use Friendica\Model\User; +use dba; + +require_once 'include/dba.php'; + +class ExAuth +{ + private $bDebug; + private $host; + private $pidfile; + + /** + * @brief Create the class + * + * @param boolean $bDebug Debug mode + */ + public function __construct() + { + $this->bDebug = (int) Config::get('jabber', 'debug'); + + openlog('auth_ejabberd', LOG_PID, LOG_USER); + + $this->writeLog(LOG_NOTICE, 'start'); + } + + /** + * @brief Standard input reading function, executes the auth with the provided + * parameters + * + * @return null + */ + public function readStdin() + { + while (!feof(STDIN)) { + // Quit if the database connection went down + if (!dba::connected()) { + $this->writeLog(LOG_ERR, 'the database connection went down'); + return; + } + + $iHeader = fgets(STDIN, 3); + $aLength = unpack('n', $iHeader); + $iLength = $aLength['1']; + + // No data? Then quit + if ($iLength == 0) { + $this->writeLog(LOG_ERR, 'we got no data, quitting'); + return; + } + + // Fetching the data + $sData = fgets(STDIN, $iLength + 1); + $this->writeLog(LOG_DEBUG, 'received data: ' . $sData); + $aCommand = explode(':', $sData); + if (is_array($aCommand)) { + switch ($aCommand[0]) { + case 'isuser': + // Check the existance of a given username + $this->isUser($aCommand); + break; + case 'auth': + // Check if the givven password is correct + $this->auth($aCommand); + break; + case 'setpass': + // We don't accept the setting of passwords here + $this->writeLog(LOG_NOTICE, 'setpass command disabled'); + fwrite(STDOUT, pack('nn', 2, 0)); + break; + default: + // We don't know the given command + $this->writeLog(LOG_NOTICE, 'unknown command ' . $aCommand[0]); + fwrite(STDOUT, pack('nn', 2, 0)); + break; + } + } else { + $this->writeLog(LOG_NOTICE, 'invalid command string ' . $sData); + fwrite(STDOUT, pack('nn', 2, 0)); + } + } + } + + /** + * @brief Check if the given username exists + * + * @param array $aCommand The command array + */ + private function isUser(array $aCommand) + { + $a = get_app(); + + // Check if there is a username + if (!isset($aCommand[1])) { + $this->writeLog(LOG_NOTICE, 'invalid isuser command, no username given'); + fwrite(STDOUT, pack('nn', 2, 0)); + return; + } + + // We only allow one process per hostname. So we set a lock file + // Problem: We get the firstname after the first auth - not before + $this->setHost($aCommand[2]); + + // Now we check if the given user is valid + $sUser = str_replace(array('%20', '(a)'), array(' ', '@'), $aCommand[1]); + + // Does the hostname match? So we try directly + if ($a->get_hostname() == $aCommand[2]) { + $this->writeLog(LOG_INFO, 'internal user check for ' . $sUser . '@' . $aCommand[2]); + $found = dba::exists('user', ['nickname' => $sUser]); + } else { + $found = false; + } + + // If the hostnames doesn't match or there is some failure, we try to check remotely + if (!$found) { + $found = $this->checkUser($aCommand[2], $aCommand[1], true); + } + + if ($found) { + // The user is okay + $this->writeLog(LOG_NOTICE, 'valid user: ' . $sUser); + fwrite(STDOUT, pack('nn', 2, 1)); + } else { + // The user isn't okay + $this->writeLog(LOG_WARNING, 'invalid user: ' . $sUser); + fwrite(STDOUT, pack('nn', 2, 0)); + } + } + + /** + * @brief Check remote user existance via HTTP(S) + * + * @param string $host The hostname + * @param string $user Username + * @param boolean $ssl Should the check be done via SSL? + * + * @return boolean Was the user found? + */ + private function checkUser($host, $user, $ssl) + { + $this->writeLog(LOG_INFO, 'external user check for ' . $user . '@' . $host); + + $url = ($ssl ? 'https' : 'http') . '://' . $host . '/noscrape/' . $user; + + $data = z_fetch_url($url); + + if (!is_array($data)) { + return false; + } + + if ($data['return_code'] != '200') { + return false; + } + + $json = @json_decode($data['body']); + if (!is_object($json)) { + return false; + } + + return $json->nick == $user; + } + + /** + * @brief Authenticate the given user and password + * + * @param array $aCommand The command array + */ + private function auth(array $aCommand) + { + $a = get_app(); + + // check user authentication + if (sizeof($aCommand) != 4) { + $this->writeLog(LOG_NOTICE, 'invalid auth command, data missing'); + fwrite(STDOUT, pack('nn', 2, 0)); + return; + } + + // We only allow one process per hostname. So we set a lock file + // Problem: We get the firstname after the first auth - not before + $this->setHost($aCommand[2]); + + // We now check if the password match + $sUser = str_replace(array('%20', '(a)'), array(' ', '@'), $aCommand[1]); + + // Does the hostname match? So we try directly + if ($a->get_hostname() == $aCommand[2]) { + $this->writeLog(LOG_INFO, 'internal auth for ' . $sUser . '@' . $aCommand[2]); + + $aUser = dba::select('user', ['uid', 'password'], ['nickname' => $sUser], ['limit' => 1]); + if (DBM::is_result($aUser)) { + $uid = User::authenticate($aUser, $aCommand[3]); + $Error = $uid === false; + } else { + $this->writeLog(LOG_WARNING, 'user not found: ' . $sUser); + $Error = true; + $uid = -1; + } + if ($Error) { + $this->writeLog(LOG_INFO, 'check against alternate password for ' . $sUser . '@' . $aCommand[2]); + $sPassword = PConfig::get($uid, 'xmpp', 'password', null, true); + $Error = ($aCommand[3] != $sPassword); + } + } else { + $Error = true; + } + + // If the hostnames doesn't match or there is some failure, we try to check remotely + if ($Error) { + $Error = !$this->checkCredentials($aCommand[2], $aCommand[1], $aCommand[3], true); + } + + if ($Error) { + $this->writeLog(LOG_WARNING, 'authentification failed for user ' . $sUser . '@' . $aCommand[2]); + fwrite(STDOUT, pack('nn', 2, 0)); + } else { + $this->writeLog(LOG_NOTICE, 'authentificated user ' . $sUser . '@' . $aCommand[2]); + fwrite(STDOUT, pack('nn', 2, 1)); + } + } + + /** + * @brief Check remote credentials via HTTP(S) + * + * @param string $host The hostname + * @param string $user Username + * @param string $password Password + * @param boolean $ssl Should the check be done via SSL? + * + * @return boolean Are the credentials okay? + */ + private function checkCredentials($host, $user, $password, $ssl) + { + $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json'; + + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); + curl_setopt($ch, CURLOPT_HEADER, true); + curl_setopt($ch, CURLOPT_NOBODY, true); + curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $password); + + curl_exec($ch); + $curl_info = @curl_getinfo($ch); + $http_code = $curl_info['http_code']; + curl_close($ch); + + $this->writeLog(LOG_INFO, 'external auth for ' . $user . '@' . $host . ' returned ' . $http_code); + + return $http_code == 200; + } + + /** + * @brief Set the hostname for this process + * + * @param string $host The hostname + */ + private function setHost($host) + { + if (!empty($this->host)) { + return; + } + + $this->writeLog(LOG_INFO, 'Hostname for process ' . getmypid() . ' is ' . $host); + + $this->host = $host; + + $lockpath = Config::get('jabber', 'lockpath'); + if (is_null($lockpath)) { + return; + } + + $this->pidfile = new Pidfile($lockpath, $host); + if ($this->pidfile->isRunning()) { + $oldpid = $this->pidfile->pid(); + $this->writeLog(LOG_INFO, 'Process ' . $oldpid . ' was running for ' . $this->pidfile->runningTime() . ' seconds and will now be killed'); + $this->pidfile->kill(); + + // Wait until the other process is hopefully killed + sleep(2); + + $this->pidfile = new Pidfile($lockpath, $host); + if ($oldpid == $this->pidfile->pid()) { + $this->writeLog(LOG_ERR, 'Process ' . $oldpid . "wasn't killed in time. We now quit our process."); + die(); + } + } + } + + /** + * @brief write data to the syslog + * + * @param integer $loglevel The syslog loglevel + * @param string $sMessage The syslog message + */ + private function writeLog($loglevel, $sMessage) + { + if (!$this->bDebug && ($loglevel >= LOG_DEBUG)) { + return; + } + syslog($loglevel, $sMessage); + } + + /** + * @brief destroy the class, close the syslog connection. + */ + public function __destruct() + { + $this->writeLog(LOG_NOTICE, 'stop'); + closelog(); + } +} diff --git a/src/Util/Pidfile.php b/src/Util/Pidfile.php index a5d1171e7b..6d940c6469 100644 --- a/src/Util/Pidfile.php +++ b/src/Util/Pidfile.php @@ -11,6 +11,7 @@ class Pidfile { private $file; private $running; + private $pid; /** * @param string $dir path @@ -19,18 +20,19 @@ class Pidfile */ public function __construct($dir, $name) { - $this->_file = "$dir/$name.pid"; + $this->file = "$dir/$name"; + $this->running = false; - if (file_exists($this->_file)) { - $pid = trim(@file_get_contents($this->file)); - if (($pid != "") && posix_kill($pid, 0)) { + if (file_exists($this->file)) { + $this->pid = trim(@file_get_contents($this->file)); + if (($this->pid != "") && posix_kill($this->pid, 0)) { $this->running = true; } } - if (! $this->running) { - $pid = getmypid(); - file_put_contents($this->file, $pid); + if (!$this->running) { + $this->pid = getmypid(); + file_put_contents($this->file, $this->pid); } } @@ -39,34 +41,46 @@ class Pidfile */ public function __destruct() { - if ((! $this->running) && file_exists($this->file)) { + if (!$this->running && file_exists($this->file)) { @unlink($this->file); } } /** - * @return boolean + * @brief Check if a process with this pid file is already running + * @return boolean Is it running? */ - public static function isRunning() + public function isRunning() { - return self::$running; + return $this->running; } /** - * @return object + * @brief Return the pid of the process + * @return boolean process id */ - public static function runningTime() + public function pid() { - return time() - @filectime(self::$file); + return $this->pid; } /** + * @brief Returns the seconds that the old process was running + * @return integer run time of the old process + */ + public function runningTime() + { + return time() - @filectime($this->file); + } + + /** + * @brief Kills the old process * @return boolean */ - public static function kill() + public function kill() { - if (file_exists(self::$file)) { - return posix_kill(file_get_contents(self::$file), SIGTERM); + if (!empty($this->pid)) { + return posix_kill($this->pid, SIGTERM); } } } From 0f149a691e4059e3faf20937b471a0d5b3d363d7 Mon Sep 17 00:00:00 2001 From: Michael Date: Sat, 9 Dec 2017 12:23:15 +0000 Subject: [PATCH 2/3] Faster credentials check --- src/Util/ExAuth.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Util/ExAuth.php b/src/Util/ExAuth.php index c68cd41166..973969678b 100644 --- a/src/Util/ExAuth.php +++ b/src/Util/ExAuth.php @@ -270,7 +270,9 @@ class ExAuth */ private function checkCredentials($host, $user, $password, $ssl) { - $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json'; + $this->writeLog(LOG_INFO, 'external credential check for ' . $user . '@' . $host); + + $url = ($ssl ? 'https' : 'http') . '://' . $host . '/api/account/verify_credentials.json?skip_status=true'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); From 38d5932156fb0de4116de042f55df23cbbe7dff1 Mon Sep 17 00:00:00 2001 From: Michael Date: Sat, 9 Dec 2017 17:49:11 +0000 Subject: [PATCH 3/3] Reworked the pidfile class --- src/Util/ExAuth.php | 22 +++---- src/Util/Pidfile.php | 146 +++++++++++++++++++++++++------------------ 2 files changed, 93 insertions(+), 75 deletions(-) diff --git a/src/Util/ExAuth.php b/src/Util/ExAuth.php index 973969678b..f83901e989 100644 --- a/src/Util/ExAuth.php +++ b/src/Util/ExAuth.php @@ -46,7 +46,6 @@ class ExAuth { private $bDebug; private $host; - private $pidfile; /** * @brief Create the class @@ -313,21 +312,18 @@ class ExAuth return; } - $this->pidfile = new Pidfile($lockpath, $host); - if ($this->pidfile->isRunning()) { - $oldpid = $this->pidfile->pid(); - $this->writeLog(LOG_INFO, 'Process ' . $oldpid . ' was running for ' . $this->pidfile->runningTime() . ' seconds and will now be killed'); - $this->pidfile->kill(); - - // Wait until the other process is hopefully killed - sleep(2); - - $this->pidfile = new Pidfile($lockpath, $host); - if ($oldpid == $this->pidfile->pid()) { - $this->writeLog(LOG_ERR, 'Process ' . $oldpid . "wasn't killed in time. We now quit our process."); + $file = $lockpath . DIRECTORY_SEPARATOR . $host; + if (Pidfile::isRunningProcess($file)) { + if (PidFile::killProcess($file)) { + $this->writeLog(LOG_INFO, 'Old process was successfully killed'); + } else { + $this->writeLog(LOG_ERR, "The old Process wasn't killed in time. We now quit our process."); die(); } } + + // Now it is safe to create the pid file + Pidfile::create($file); } /** diff --git a/src/Util/Pidfile.php b/src/Util/Pidfile.php index 6d940c6469..9d12b0bd25 100644 --- a/src/Util/Pidfile.php +++ b/src/Util/Pidfile.php @@ -9,78 +9,100 @@ namespace Friendica\Util; */ class Pidfile { - private $file; - private $running; - private $pid; - /** - * @param string $dir path - * @param string $name filename - * @return void + * @brief Read the pid from a given pid file + * + * @param string $file Filename of pid file + * + * @return boolean|string PID or "false" if not existent */ - public function __construct($dir, $name) - { - $this->file = "$dir/$name"; - $this->running = false; - - if (file_exists($this->file)) { - $this->pid = trim(@file_get_contents($this->file)); - if (($this->pid != "") && posix_kill($this->pid, 0)) { - $this->running = true; - } + static private function pidFromFile($file) { + if (!file_exists($file)) { + return false; } - if (!$this->running) { - $this->pid = getmypid(); - file_put_contents($this->file, $this->pid); - } + return trim(@file_get_contents($file)); } /** - * @return void - */ - public function __destruct() - { - if (!$this->running && file_exists($this->file)) { - @unlink($this->file); - } - } - - /** - * @brief Check if a process with this pid file is already running + * @brief Is there a running process with the given pid file + * + * @param string $file Filename of pid file + * * @return boolean Is it running? */ - public function isRunning() - { - return $this->running; - } + static public function isRunningProcess($file) { + $pid = self::pidFromFile($file); - /** - * @brief Return the pid of the process - * @return boolean process id - */ - public function pid() - { - return $this->pid; - } - - /** - * @brief Returns the seconds that the old process was running - * @return integer run time of the old process - */ - public function runningTime() - { - return time() - @filectime($this->file); - } - - /** - * @brief Kills the old process - * @return boolean - */ - public function kill() - { - if (!empty($this->pid)) { - return posix_kill($this->pid, SIGTERM); + if (!$pid) { + return false; } + + // Is the process running? + $running = posix_kill($pid, 0); + + // If not, then we will kill the stale file + if (!$running) { + self::delete($file); + } + return $running; + } + + /** + * @brief Kills a process from a given pid file + * + * @param string $file Filename of pid file + * + * @return boolean Was it killed successfully? + */ + static public function killProcess($file) { + $pid = self::pidFromFile($file); + + // We don't have a process id? then we quit + if (!$pid) { + return false; + } + + // We now kill the process + $killed = posix_kill($pid, SIGTERM); + + // If we killed the process successfully, we can remove the pidfile + if ($killed) { + self::delete($file); + } + return $killed; + } + + /** + * @brief Creates a pid file + * + * @param string $file Filename of pid file + * + * @return boolean|string PID or "false" if not created + */ + static public function create($file) { + $pid = self::pidFromFile($file); + + // We have a process id? then we quit + if ($pid) { + return false; + } + + $pid = getmypid(); + file_put_contents($file, $pid); + + // Now we check if everything is okay + return self::pidFromFile($file); + } + + /** + * @brief Deletes a given pid file + * + * @param string $file Filename of pid file + * + * @return boolean Is it running? + */ + static public function delete($file) { + return @unlink($file); } }