public function testChangeGroup() { if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') { $this->markTestSkipped("chown tests don't work on Windows"); } $userinfo = posix_getpwuid(posix_geteuid()); $username = $userinfo['name']; //we may change the group only if we belong to it //so find a group that we are in $group = null; foreach (array('users', 'www-data', 'cdrom') as $groupname) { $grpinfo = posix_getgrnam($groupname); if ($grpinfo['gid'] == $userinfo['gid']) { //current group id, the file has that group anyway continue; } if (in_array($username, $grpinfo['members'])) { $group = $grpinfo; break; } } if ($group === null) { $this->markTestSkipped('found no group we can change ownership to'); } $this->project->setUserProperty('targetuser', $username . '.' . $group['name']); $this->executeTarget(__FUNCTION__); $a = stat(PHING_TEST_BASE . '/etc/tasks/system/tmp/chowntestA'); $b = stat(PHING_TEST_BASE . '/etc/tasks/system/tmp/chowntestB'); $this->assertNotEquals($group['gid'], $a['gid'], 'chowntestA group should not have changed'); $this->assertEquals($group['gid'], $b['gid'], 'chowntestB group should have changed'); }
public function preUp() { $this->needed_group_name = 'codendiadm'; $codendi_ugroup = posix_getgrnam($this->needed_group_name); $this->codendi_ugroup_id = $codendi_ugroup['gid']; $this->needed_access_right = '0755'; }
public function import($id_) { Logger::debug('main', 'UserGroupDB::unix::import(' . $id_ . ')'); $tab = posix_getgrnam($id_); if (is_array($tab)) { $id = ''; $name = ''; $description = ''; $published = true; $members = null; if (isset($tab['name'])) { $id = $tab['name']; $name = $tab['name']; } if (isset($tab['members'])) { $members = $tab['members']; } $ug = new UsersGroup($id, $name, $description, $published); if (is_array($members)) { $ug->extras = array('member' => $members); } if ($this->isOK($ug)) { return $ug; } } return NULL; }
protected function setUsersGid() { // figure out the GID for "users" for tests $this->usersGid = 1000; // default if (posix_geteuid() === 0 && function_exists('posix_getgrnam')) { $info = posix_getgrnam('users'); $this->usersGid = $info['gid']; } }
/** * 构造方法 */ public function __construct($setting) { $this->config = $setting['config']; $this->cronPath = $setting['cron_path']; if (isset($setting['group'])) { $groupinfo = posix_getpwnam($setting['group']); posix_setgid($groupinfo['gid']); } if (isset($setting['user'])) { $userinfo = posix_getgrnam($setting['user']); posix_setuid($groupinfo['uid']); } include __DIR__ . '/ParseCrontab.php'; include __DIR__ . '/ParseInterval.php'; }
/** * Change the group of an array of files or directories. * * @param string|array|\Traversable $files A filename, an array of files, or a \Traversable instance to change group * @param string $group The group name * @param bool $recursive Whether change the group recursively or not * * @throws IOException When the change fail */ public function chgrp($files, $group, $recursive = false) { foreach ($this->toIterator($files) as $file) { if ($recursive && is_dir($file) && !is_link($file)) { $this->chgrp(new \FilesystemIterator($file), $group, true); } if (is_link($file) && function_exists('lchgrp')) { if (true !== @lchgrp($file, $group) || defined('HHVM_VERSION') && !posix_getgrnam($group)) { throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file); } } else { if (true !== @chgrp($file, $group)) { throw new IOException(sprintf('Failed to chgrp file "%s".', $file), 0, null, $file); } } } }
public static function setUser($user, $group = null) { if (false === ($info = posix_getpwnam($user))) { throw new Exception("Does not exist operating system user: {$user}"); } $uid = $info['uid']; if ($group) { if (false === ($info = posix_getgrnam($group))) { throw new Exception("Does not exist operating system group: {$group}"); } else { $gid = $info['gid']; } } else { $gid = $info['gid']; } static::setUid($uid, $gid); }
/** * {@inheritDoc} */ public function process(ContainerBuilder $container) { if (!$container->hasParameter('uecode.daemon')) { return; } $config = $container->getParameter('uecode.daemon'); // merges each configured daemon with default configs // and makes sure the pid directory is writable $filesystem = new Filesystem(); foreach ($config['daemons'] as $name => $cnf) { if (null == $cnf) { $cnf = array(); } try { $pidDir = $cnf['appPidDir']; $filesystem->mkdir($pidDir, 0777); } catch (\Exception $e) { echo 'UecodeDaemonBundle exception: ', $e->getMessage(), "\n"; } if (isset($cnf['appUser']) || isset($cnf['appGroup'])) { if (isset($cnf['appUser']) && function_exists('posix_getpwnam')) { $user = posix_getpwnam($cnf['appUser']); if ($user) { $cnf['appRunAsUID'] = $user['uid']; } } if (isset($cnf['appGroup']) && function_exists('posix_getgrnam')) { $group = posix_getgrnam($cnf['appGroup']); if ($group) { $cnf['appRunAsGID'] = $group['gid']; } } if (!isset($cnf['appRunAsGID'])) { $user = posix_getpwuid($cnf['appRunAsUID']); $cnf['appRunAsGID'] = $user['gid']; } } $cnf['logLocation'] = rtrim($cnf['logDir'], '/') . '/' . $cnf['appName'] . 'Daemon.log'; $cnf['appPidLocation'] = rtrim($cnf['appPidDir'], '/') . '/' . $cnf['appName'] . '/' . $cnf['appName'] . '.pid'; unset($cnf['logDir'], $cnf['appPidDir']); $container->setParameter($name . '.daemon.options', $cnf); } }
/** * Handle an event. * * @param \League\Event\EventInterface $event The triggering event * * @return void * @see \League\Event\ListenerInterface::handle() */ public function handle(EventInterface $event) { try { // load the application server instance /** @var \AppserverIo\Appserver\Core\Interfaces\ApplicationServerInterface $applicationServer */ $applicationServer = $this->getApplicationServer(); // write a log message that the event has been invoked $applicationServer->getSystemLogger()->info($event->getName()); // don't do anything under Windows if (FileSystem::getOsIdentifier() === 'WIN') { $applicationServer->getSystemLogger()->info('Don\'t switch UID to \'%s\' because OS is Windows'); return; } // initialize the variable for user/group $uid = 0; $gid = 0; // throw an exception if the POSIX extension is not available if (extension_loaded('posix') === false) { throw new \Exception('Can\'t switch user, because POSIX extension is not available'); } // print a message with the old UID/EUID $applicationServer->getSystemLogger()->info("Running as " . posix_getuid() . "/" . posix_geteuid()); // extract the user and group name as variables extract(posix_getgrnam($applicationServer->getSystemConfiguration()->getGroup())); extract(posix_getpwnam($applicationServer->getSystemConfiguration()->getUser())); // switch the effective GID to the passed group if (posix_setegid($gid) === false) { $applicationServer->getSystemLogger()->error(sprintf('Can\'t switch GID to \'%s\'', $gid)); } // print a message with the new GID/EGID $applicationServer->getSystemLogger()->info("Running as group" . posix_getgid() . "/" . posix_getegid()); // switch the effective UID to the passed user if (posix_seteuid($uid) === false) { $applicationServer->getSystemLogger()->error(sprintf('Can\'t switch UID to \'%s\'', $uid)); } // print a message with the new UID/EUID $applicationServer->getSystemLogger()->info("Running as user " . posix_getuid() . "/" . posix_geteuid()); } catch (\Exception $e) { $applicationServer->getSystemLogger()->error($e->__toString()); } }
function checksADGroup($groupname) { $checked = true; $userinfo = @posix_getgrnam($groupname); if (!isset($userinfo["gid"])) { $checked = false; } if (!is_numeric($userinfo["gid"])) { $checked = false; } if ($userinfo["gid"] < 1) { $checked = false; } $tpl = new templates(); if (!$checked) { $html = $tpl->_ENGINE_parse_body("<table style='border:0px'>\n\t\t<tr>\n\t\t\t<td width=1% style='border:0px;border-left:0px;border-bottom:0px;' valign='top'><img src='img/warning-panneau-24.png'></td>\n\t\t\t<td style='border:0px;border-left:0px;border-bottom:0px;' valign='top'><strong style='font-size:12px'>{this_group_is_not_retranslated_to_the_system}</td>\n\t\t</tr>\n\t\t</table>\n\t\t"); } else { $html = $tpl->_ENGINE_parse_body(count($userinfo["members"]) . " {members}"); } return $html; }
/** * @param Bundle\ServerBundle\EventDispatcher $dispatcher * @param Bundle\ServerBundle\Socket\ServerSocket $server * @param array $options (optional) * * @throws \InvalidArgumentException When an unsupported option is provided * @throws \InvalidArgumentException If provided user does not exist * @throws \InvalidArgumentException If provided group does not exist * @throws \InvalidArgumentException If an invalid socket client class is provided * @throws \InvalidArgumentException If an invalid socket server class is provided * @throws \InvalidArgumentException If an invalid socket server client class is provided */ public function __construct(EventDispatcher $dispatcher, ServerSocket $server, array $options = array()) { $this->dispatcher = $dispatcher; $this->server = $server; $this->console = null; $this->isDaemon = false; $this->clients = array(); $this->shutdown = false; // @see Resources/config/server.xml $this->options = array('pid_file' => null, 'user' => null, 'group' => null, 'umask' => null, 'environment' => 'dev', 'debug' => true, 'kernel_environment' => 'prod', 'kernel_debug' => false, 'address' => '*', 'port' => 1962, 'max_clients' => 100, 'max_requests_per_child' => 1000, 'document_root' => null, 'timeout' => 90, 'keepalive_timeout' => 15); // check option names if ($diff = array_diff(array_keys($options), array_keys($this->options))) { throw new \InvalidArgumentException(sprintf('The Server does not support the following options: \'%s\'.', implode('\', \'', $diff))); } $this->options = array_merge($this->options, $options); // convert user name to user id if (null !== $this->options['user'] && !is_int($this->options['user'])) { $user = posix_getpwnam($this->options['user']); if (false === $user) { throw new \InvalidArgumentException(sprintf('User "%s" does not exist', $this->options['user'])); } $this->options['user'] = $user['uid']; } // convert group name to group id if (null !== $this->options['group'] && !is_int($this->options['group'])) { $group = posix_getgrnam($this->options['group']); if (false === $group) { throw new \InvalidArgumentException(sprintf('Group "%s" does not exist', $this->options['group'])); } $this->options['group'] = $group['gid']; } if (null !== $this->options['umask']) { umask($this->options['umask']); } declare (ticks=1); // pcntl signal handlers pcntl_signal(SIGHUP, array($this, 'signalHandler')); pcntl_signal(SIGINT, array($this, 'signalHandler')); pcntl_signal(SIGTERM, array($this, 'signalHandler')); }
/** * Set unix user and group for current process. * @return void */ public function setUserAndGroup() { // Get uid. $user_info = posix_getpwnam($this->user); if (!$user_info) { return self::log("Waring: User {$this->user} not exsits", true); } $uid = $user_info['uid']; // Get gid. if ($this->group) { $group_info = posix_getgrnam($this->group); if (!$group_info) { return self::log("Waring: Group {$this->group} not exsits", true); } $gid = $group_info['gid']; } else { $gid = $user_info['gid']; } // Set uid and gid. if ($uid != posix_getuid() || $gid != posix_getgid()) { if (!posix_setgid($gid) || !posix_initgroups($user_info['name'], $gid) || !posix_setuid($uid)) { self::log("Waring: change gid or uid fail.", true); } } }
/** * Check and chdir to $_workDir * * @return void */ private function ___init_userGroup() { $this->_debug("-----> " . __CLASS__ . '::' . __FUNCTION__ . '()', 9); // Get current uid and gid $uid_cur = posix_getuid(); $gid_cur = posix_getgid(); // If not root, skip the rest of this procedure if ($uid_cur != 0) { $this->_log("Skipping the setUid/setGid part, because we are not root"); return; } // Get desired uid/gid $r = posix_getpwnam($this->_user); if ($r === false) { throw new A2o_AppSrv_Exception("Unable to get uid for user: {$this->_user}"); } $userData = $r; $r = posix_getgrnam($this->_group); if ($r === false) { throw new A2o_AppSrv_Exception("Unable to get gid for group: {$this->_group}"); } $groupData = $r; $uid_desired = $userData['uid']; $gid_desired = $groupData['gid']; // Change effective uid/gid if required if ($gid_cur != $gid_desired) { $r = posix_setgid($gid_desired); if ($r === false) { throw new A2o_AppSrv_Exception("Unable to setgid: {$gid_cur} -> {$gid_desired}"); } $this->_debug("Group (GID) changed to {$this->_group} ({$gid_desired})"); } if ($uid_cur != $uid_desired) { $r = posix_setuid($uid_desired); if ($r === false) { throw new A2o_AppSrv_Exception("Unable to setuid: {$uid_cur} -> {$uid_desired}"); } $this->_debug("User (UID) changed to {$this->_user} ({$uid_desired})"); } $this->_debug("Setuid/setgid complete"); }
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ***********************************************************/ /** * @file migratetest.php * @brief Test migration function * * @return 0 for success, 1 for failure. **/ /* User must be in group fossy! */ $GID = posix_getgrnam("fossy"); posix_setgid($GID['gid']); $Group = `groups`; if (!preg_match("/\\sfossy\\s/", $Group) && posix_getgid() != $GID['gid']) { print "FATAL: You must be in group 'fossy' to update the FOSSology database.\n"; exit(1); } /* Initialize the program configuration variables */ $SysConf = array(); // fo system configuration variables $PG_CONN = 0; // Database connection $Plugins = array(); /* defaults */ $Verbose = false; $DatabaseName = "fossology";
public function testFork_CloneEmptyToSpecifiedPath() { if (posix_getgrnam('gitolite') == false) { echo "testFork_CloneEmptyToSpecifiedPath: Cannot test 'cause there is no 'gitolite' user on server (CI)"; } else { $name = 'tulip'; $new_ns = 'repos/new/repo/'; $old_ns = 'repos/'; $old_root_dir = $this->repoDir . '/' . $old_ns . $name . '.git'; $new_root_dir = $this->repoDir . '/' . $new_ns . $name . '.git'; mkdir($old_root_dir, 0770, true); exec('GIT_DIR=' . $old_root_dir . ' git init --bare --shared=group'); exec('cd ' . $old_root_dir . ' && touch hooks/gitolite_hook.sh'); $this->assertTrue($this->driver->fork($name, $old_ns, $new_ns)); $this->assertRepoIsClonedWithHooks($new_root_dir); $this->assertWritableByGroup($new_root_dir, 'gitolite'); $this->assertNameSpaceFileHasBeenInitialized($new_root_dir, $new_ns, 'gitolite'); } }
function changeUser() { $username = common_config('daemon', 'user'); if ($username) { $user_info = posix_getpwnam($username); if (!$user_info) { common_log(LOG_WARNING, 'Ignoring unknown user for daemon: ' . $username); } else { common_log(LOG_INFO, "Setting user to " . $username); posix_setuid($user_info['uid']); } } $groupname = common_config('daemon', 'group'); if ($groupname) { $group_info = posix_getgrnam($groupname); if (!$group_info) { common_log(LOG_WARNING, 'Ignoring unknown group for daemon: ' . $groupname); } else { common_log(LOG_INFO, "Setting group to " . $groupname); posix_setgid($group_info['gid']); } } }
/** * Entry-point for Erebot. * * \return * This method never returns. * Instead, the program exits with an appropriate * return code when Erebot is stopped. */ public static function run() { // Apply patches. \Erebot\Patches::patch(); // Load the configuration for the Dependency Injection Container. $dic = new \Symfony\Component\DependencyInjection\ContainerBuilder(); $dic->setParameter('Erebot.src_dir', __DIR__); $loader = new \Symfony\Component\DependencyInjection\Loader\XmlFileLoader($dic, new \Symfony\Component\Config\FileLocator(getcwd())); $dicConfig = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'data' . DIRECTORY_SEPARATOR . 'defaults.xml'; $dicCwdConfig = getcwd() . DIRECTORY_SEPARATOR . 'defaults.xml'; if (!strncasecmp(__FILE__, 'phar://', 7)) { if (!file_exists($dicCwdConfig)) { copy($dicConfig, $dicCwdConfig); } $dicConfig = $dicCwdConfig; } elseif (file_exists($dicCwdConfig)) { $dicConfig = $dicCwdConfig; } $loader->load($dicConfig); // Determine availability of PHP extensions // needed by some of the command-line options. $hasPosix = in_array('posix', get_loaded_extensions()); $hasPcntl = in_array('pcntl', get_loaded_extensions()); $logger = $dic->get('logging'); $localeGetter = $dic->getParameter('i18n.default_getter'); $coreTranslatorCls = $dic->getParameter('core.classes.i18n'); $translator = new $coreTranslatorCls("Erebot\\Core"); $categories = array('LC_MESSAGES', 'LC_MONETARY', 'LC_TIME', 'LC_NUMERIC'); foreach ($categories as $category) { $locales = call_user_func($localeGetter); $locales = empty($locales) ? array() : array($locales); $localeSources = array('LANGUAGE' => true, 'LC_ALL' => false, $category => false, 'LANG' => false); foreach ($localeSources as $source => $multiple) { if (!isset($_SERVER[$source])) { continue; } if ($multiple) { $locales = explode(':', $_SERVER[$source]); } else { $locales = array($_SERVER[$source]); } break; } $translator->setLocale($translator->nameToCategory($category), $locales); } // Also, include some information about the version // of currently loaded PHAR modules, if any. $version = 'dev-master'; if (!strncmp(__FILE__, 'phar://', 7)) { $phar = new \Phar(\Phar::running(true)); $md = $phar->getMetadata(); $version = $md['version']; } if (defined('Erebot_PHARS')) { $phars = unserialize(Erebot_PHARS); ksort($phars); foreach ($phars as $module => $metadata) { if (strncasecmp($module, 'Erebot_Module_', 14)) { continue; } $version .= "\n with {$module} version {$metadata['version']}"; } } \Console_CommandLine::registerAction('StoreProxy', '\\Erebot\\Console\\StoreProxyAction'); $parser = new \Console_CommandLine(array('name' => 'Erebot', 'description' => $translator->gettext('A modular IRC bot written in PHP'), 'version' => $version, 'add_help_option' => true, 'add_version_option' => true, 'force_posix' => false)); $parser->accept(new \Erebot\Console\MessageProvider()); $parser->renderer->options_on_different_lines = true; $defaultConfigFile = getcwd() . DIRECTORY_SEPARATOR . 'Erebot.xml'; $parser->addOption('config', array('short_name' => '-c', 'long_name' => '--config', 'description' => $translator->gettext('Path to the configuration file to use instead ' . 'of "Erebot.xml", relative to the current ' . 'directory.'), 'help_name' => 'FILE', 'action' => 'StoreString', 'default' => $defaultConfigFile)); $parser->addOption('daemon', array('short_name' => '-d', 'long_name' => '--daemon', 'description' => $translator->gettext('Run the bot in the background (daemon).' . ' [requires the POSIX and pcntl extensions]'), 'action' => 'StoreTrue')); $noDaemon = new \Erebot\Console\ParallelOption('no_daemon', array('short_name' => '-n', 'long_name' => '--no-daemon', 'description' => $translator->gettext('Do not run the bot in the background. ' . 'This is the default, unless the -d option ' . 'is used or the bot is configured otherwise.'), 'action' => 'StoreProxy', 'action_params' => array('option' => 'daemon'))); $parser->addOption($noDaemon); $parser->addOption('pidfile', array('short_name' => '-p', 'long_name' => '--pidfile', 'description' => $translator->gettext("Store the bot's PID in this file."), 'help_name' => 'FILE', 'action' => 'StoreString', 'default' => null)); $parser->addOption('group', array('short_name' => '-g', 'long_name' => '--group', 'description' => $translator->gettext('Set group identity to this GID/group during ' . 'startup. The default is to NOT change group ' . 'identity, unless configured otherwise.' . ' [requires the POSIX extension]'), 'help_name' => 'GROUP/GID', 'action' => 'StoreString', 'default' => null)); $parser->addOption('user', array('short_name' => '-u', 'long_name' => '--user', 'description' => $translator->gettext('Set user identity to this UID/username during ' . 'startup. The default is to NOT change user ' . 'identity, unless configured otherwise.' . ' [requires the POSIX extension]'), 'help_name' => 'USER/UID', 'action' => 'StoreString', 'default' => null)); try { $parsed = $parser->parse(); } catch (\Exception $exc) { $parser->displayError($exc->getMessage()); exit(1); } // Parse the configuration file. $config = new \Erebot\Config\Main($parsed->options['config'], \Erebot\Config\Main::LOAD_FROM_FILE, $translator); $coreCls = $dic->getParameter('core.classes.core'); $bot = new $coreCls($config, $translator); $dic->set('bot', $bot); // Use values from the XML configuration file // if there is no override from the command line. $overrides = array('daemon' => 'mustDaemonize', 'group' => 'getGroupIdentity', 'user' => 'getUserIdentity', 'pidfile' => 'getPidfile'); foreach ($overrides as $option => $func) { if ($parsed->options[$option] === null) { $parsed->options[$option] = $config->{$func}(); } } /* Handle daemonization. * See also: * - http://www.itp.uzh.ch/~dpotter/howto/daemonize * - http://andytson.com/blog/2010/05/daemonising-a-php-cli-script */ if ($parsed->options['daemon']) { if (!$hasPosix) { $logger->error($translator->gettext('The posix extension is required in order ' . 'to start the bot in the background')); exit(1); } if (!$hasPcntl) { $logger->error($translator->gettext('The pcntl extension is required in order ' . 'to start the bot in the background')); exit(1); } foreach (array('SIGCHLD', 'SIGUSR1', 'SIGALRM') as $signal) { if (defined($signal)) { pcntl_signal(constant($signal), array(__CLASS__, 'startupSighandler')); } } $logger->info($translator->gettext('Starting the bot in the background...')); $pid = pcntl_fork(); if ($pid < 0) { $logger->error($translator->gettext('Could not start in the background (unable to fork)')); exit(1); } if ($pid > 0) { pcntl_wait($dummy, WUNTRACED); pcntl_alarm(2); pcntl_signal_dispatch(); exit(1); } $parent = posix_getppid(); // Ignore some of the signals. foreach (array('SIGTSTP', 'SIGTOU', 'SIGTIN', 'SIGHUP') as $signal) { if (defined($signal)) { pcntl_signal(constant($signal), SIG_IGN); } } // Restore the signal handlers we messed with. foreach (array('SIGCHLD', 'SIGUSR1', 'SIGALRM') as $signal) { if (defined($signal)) { pcntl_signal(constant($signal), SIG_DFL); } } umask(0); if (umask() != 0) { $logger->warning($translator->gettext('Could not change umask')); } if (posix_setsid() == -1) { $logger->error($translator->gettext('Could not start in the background (unable to setsid)')); exit(1); } // Prevent the child from ever acquiring a controlling terminal. // Not required under Linux, but required by at least System V. $pid = pcntl_fork(); if ($pid < 0) { $logger->error($translator->gettext('Could not start in the background (unable to fork)')); exit(1); } if ($pid > 0) { exit(0); } // Avoid locking up the current directory. if (!chdir(DIRECTORY_SEPARATOR)) { $logger->error($translator->gettext('Could not chdir to "%(path)s"'), array('path' => DIRECTORY_SEPARATOR)); } // Explicitly close the magic stream-constants (just in case). foreach (array('STDIN', 'STDOUT', 'STDERR') as $stream) { if (defined($stream)) { fclose(constant($stream)); } } // Re-open them with the system's blackhole. /** * \todo * should be made portable, but the requirement on the POSIX * extension prevents this, so this is okay for now. */ $stdin = fopen('/dev/null', 'r'); $stdout = fopen('/dev/null', 'w'); $stderr = fopen('/dev/null', 'w'); if (defined('SIGUSR1')) { posix_kill($parent, SIGUSR1); } $logger->info($translator->gettext('Successfully started in the background')); } try { /// @TODO: Check the interface or something like that. $identd = $dic->get('identd'); } catch (\InvalidArgumentException $e) { $identd = null; } try { /// @TODO: Check the interface or something like that. $prompt = $dic->get('prompt'); } catch (\InvalidArgumentException $e) { $prompt = null; } // Change group identity if necessary. if ($parsed->options['group'] !== null && $parsed->options['group'] != '') { if (!$hasPosix) { $logger->warning($translator->gettext('The posix extension is needed in order ' . 'to change group identity.')); } elseif (posix_getuid() !== 0) { $logger->warning($translator->gettext('Only root can change group identity! ' . 'Your current UID is %(uid)d'), array('uid' => posix_getuid())); } else { if (ctype_digit($parsed->options['group'])) { $info = posix_getgrgid((int) $parsed->options['group']); } else { $info = posix_getgrnam($parsed->options['group']); } if ($info === false) { $logger->error($translator->gettext('No such group "%(group)s"'), array('group' => $parsed->options['group'])); exit(1); } if (!posix_setgid($info['gid'])) { $logger->error($translator->gettext('Could not set group identity ' . 'to "%(name)s" (%(id)d)'), array('id' => $info['gid'], 'name' => $info['name'])); exit(1); } $logger->debug($translator->gettext('Successfully changed group identity ' . 'to "%(name)s" (%(id)d)'), array('name' => $info['name'], 'id' => $info['gid'])); } } // Change user identity if necessary. if ($parsed->options['user'] !== null || $parsed->options['user'] != '') { if (!$hasPosix) { $logger->warning($translator->gettext('The posix extension is needed in order ' . 'to change user identity.')); } elseif (posix_getuid() !== 0) { $logger->warning($translator->gettext('Only root can change user identity! ' . 'Your current UID is %(uid)d'), array('uid' => posix_getuid())); } else { if (ctype_digit($parsed->options['user'])) { $info = posix_getpwuid((int) $parsed->options['user']); } else { $info = posix_getpwnam($parsed->options['user']); } if ($info === false) { $logger->error($translator->gettext('No such user "%(user)s"'), array('user' => $parsed->options['user'])); exit(1); } if (!posix_setuid($info['uid'])) { $logger->error($translator->gettext('Could not set user identity ' . 'to "%(name)s" (%(id)d)'), array('name' => $info['name'], 'id' => $info['uid'])); exit(1); } $logger->debug($translator->gettext('Successfully changed user identity ' . 'to "%(name)s" (%(id)d)'), array('name' => $info['name'], 'id' => $info['uid'])); } } // Write new pidfile. if ($parsed->options['pidfile'] !== null && $parsed->options['pidfile'] != '') { $pid = @file_get_contents($parsed->options['pidfile']); // If the file already existed, the bot may already be started // or it may contain data not related to Erebot at all. if ($pid !== false) { $pid = (int) rtrim($pid); if (!$pid) { $logger->error($translator->gettext('The pidfile (%(pidfile)s) contained garbage. ' . 'Exiting'), array('pidfile' => $parsed->options['pidfile'])); exit(1); } else { posix_kill($pid, 0); $res = posix_errno(); switch ($res) { case 0: // No error. $logger->error($translator->gettext('Erebot is already running ' . 'with PID %(pid)d'), array('pid' => $pid)); exit(1); case 3: // ESRCH. $logger->warning($translator->gettext('Found stalled PID %(pid)d in pidfile ' . '"%(pidfile)s". Removing it'), array('pidfile' => $parsed->options['pidfile'], 'pid' => $pid)); @unlink($parsed->options['pidfile']); break; case 1: // EPERM. $logger->error($translator->gettext('Found another program\'s PID %(pid)d in ' . 'pidfile "%(pidfile)s". Exiting'), array('pidfile' => $parsed->options['pidfile'], 'pid' => $pid)); exit(1); default: $logger->error($translator->gettext('Unknown error while checking for ' . 'the existence of another running ' . 'instance of Erebot (%(error)s)'), array('error' => posix_get_last_error())); exit(1); } } } $pidfile = fopen($parsed->options['pidfile'], 'wt'); flock($pidfile, LOCK_EX | LOCK_NB, $wouldBlock); if ($wouldBlock) { $logger->error($translator->gettext('Could not lock pidfile (%(pidfile)s). ' . 'Is the bot already running?'), array('pidfile' => $parsed->options['pidfile'])); exit(1); } $pid = sprintf("%u\n", getmypid()); $res = fwrite($pidfile, $pid); if ($res !== strlen($pid)) { $logger->error($translator->gettext('Unable to write PID to pidfile (%(pidfile)s)'), array('pidfile' => $parsed->options['pidfile'])); exit(1); } $logger->debug($translator->gettext('PID (%(pid)d) written into %(pidfile)s'), array('pidfile' => $parsed->options['pidfile'], 'pid' => getmypid())); // Register a callback to remove the pidfile upon exit. register_shutdown_function(array(__CLASS__, 'cleanupPidfile'), $pidfile, $parsed->options['pidfile']); } // Display a desperate warning when run as user root. if ($hasPosix && posix_getuid() === 0) { $logger->warning($translator->gettext('You SHOULD NOT run Erebot as root!')); } if ($identd !== null) { $identd->connect(); } if ($prompt !== null) { $prompt->connect(); } // This doesn't return until we purposely // make the bot drop all active connections. $bot->start($dic->get('factory.connection')); exit(0); }
/** * Sets the current filesystem object group, updates $_group property on success. * * For POSIX systems. * * Asserts that group exists before process if posix_ functions are available. * * @param string|int $group New group name or ID * @param bool $recursive Apply group to directory contents flag. * @return CFile|bool Current CFile object on success, 'False' on fail. * @throws CFileException When the given group is not found, if posix_ functions are available. */ public function setGroup($group, $recursive = False) { if (function_exists('posix_getgrnam') && function_exists('posix_getgrgid')) { if (posix_getgrnam($group) == False xor is_numeric($group) && posix_getgrgid($group) == False) { throw new CFileException('Unable to set group for filesystem object. Group "' . $group . '" is not found.'); } } if ($this->getExists()) { $success = @chgrp($this->_realpath, $group); if ($success) { $this->_group = $group; } if ($success && $this->getIsDir() && $recursive) { $contents = $this->getContents(True); foreach ($contents as $filepath) { if (!@chgrp($filepath, $group)) { $this->addLog('Unable to set group for "' . $filepath . '" to "' . $group . '"'); $success = False; } } } if ($success) { return $this; } } $this->addLog('Unable to set group for filesystem object to "' . $group . '"'); return False; }
/** * Return info about a group by name * */ function posix_getgrnam($group) { if (!function_exists('posix_getgrnam')) { $group_datei = $this->server_conf['group_datei']; $cmd = 'grep -m 1 "^' . $group . ':" ' . $group_datei; exec($cmd, $output, $return_var); if ($return_var != 0 || !$output[0]) { return false; } list($f1, $f2, $f3, $f4) = explode(':', $output[0]); $f2 = trim($f2); $f3 = trim($f3); $f4 = trim($f4); if ($f4 != '') { $members = explode(',', $f4); } else { $members = array(); } $group_details = array('name' => $group, 'passwd' => $f2, 'members' => $members, 'gid' => $f3); return $group_details; } else { return posix_getgrnam($group); } }
/** * Will attempt to change the group of the given file system path (*nix only) * * @param string $path The path to change the group of. * @param string $group The new group name. * @param bool $recursive If the path is a directory, whether to recursively change the group of the child * files and folders. * @param bool $suppressErrors Whether to suppress any PHP Notices/Warnings/Errors (usually permissions related). * * @return bool 'true' if successful, 'false' if not, or the given path does not exist. */ public static function changeGroup($path, $group, $recursive = false, $suppressErrors = false) { $path = static::normalizePathSeparators($path); if (posix_getgrnam($group) == false xor is_numeric($group) && posix_getgrgid($group) == false) { Craft::log('Tried to change the group of ' . $path . ', but the group name "' . $group . '" does not exist.', LogLevel::Error); return false; } if (static::fileExists($path, $suppressErrors) || static::folderExists($path, $suppressErrors)) { $success = $suppressErrors ? @chgrp($path, $group) : chgrp($path, $group); if ($success && static::folderExists($path, $suppressErrors) && $recursive) { $contents = static::getFolderContents($path, true, null, false, $suppressErrors); foreach ($contents as $path) { $path = static::normalizePathSeparators($path); if ($suppressErrors ? !@chgrp($path, $group) : chgrp($path, $group)) { $success = false; } } } if (!$success) { Craft::log('Tried to change the group of ' . $path . ', but could not.', LogLevel::Error); return false; } return true; } else { Craft::log('Tried to change group of ' . $path . ', but that path does not exist.', LogLevel::Error); } return false; }
static function getGroupByName($name) { return posix_getgrnam($name); }
/** * Runs the server. Loads the listener using XPClass::forName() * so that the class is loaded within the thread's process space * and will be recompiled whenever the thread is restarted. * * @throws lang.XPException in case initializing the server fails * @throws lang.SystemException in case setuid fails */ public function run() { try { with($class = XPClass::forName('peer.ftp.server.FtpProtocol'), $cl = ClassLoader::getDefault()); // Add listener $this->server->setProtocol($proto = $class->newInstance($storage = Proxy::newProxyInstance($cl, array(XPClass::forName('peer.ftp.server.storage.Storage')), $this->storageHandler), Proxy::newProxyInstance($cl, array(XPClass::forName('security.auth.Authenticator')), $this->authenticatorHandler))); // Copy interceptors to connection listener $proto->interceptors = $this->interceptors; // Enable debugging if ($this->cat) { $proto->setTrace($this->cat); $this->server instanceof Traceable && $this->server->setTrace($this->cat); } // Try to start the server $this->server->init(); } catch (Throwable $e) { $this->server->shutdown(); throw $e; } // Check if we should run child processes // with another uid/pid if (isset($this->processGroup)) { $group = posix_getgrnam($this->processGroup); $this->cat && $this->cat->debugf('Setting group to: %s (GID: %d)', $group['name'], $group['uid']); if (!posix_setgid($group['gid'])) { throw new SystemException('Could not set GID'); } } if (isset($this->processOwner)) { $user = posix_getpwnam($this->processOwner); $this->cat && $this->cat->debugf('Setting user to: %s (UID: %d)', $user['name'], $user['uid']); if (!posix_setuid($user['uid'])) { throw new SystemException('Could not set UID'); } } $this->server->service(); }
$uid = $_POST['uid']; } if (isset($_POST['gid'])) { $gid = $_POST['gid']; } if ($userinfo = @posix_getpwuid($uid)) { $uid = $userinfo['uid']; } elseif ($userinfo = @posix_getpwnam($uid)) { $uid = $userinfo['uid']; } else { header("Location: site.php?failuidguid={$_POST['domain']}"); die; } if ($groupinfo = @posix_getgrgid($gid)) { $gid = $groupinfo['gid']; } elseif ($groupinfo = @posix_getgrnam($gid)) { $gid = $groupinfo['gid']; } else { header("Location: site.php?failuidguid={$_POST['domain']}"); die; } if (isset($_POST['maildir']) && isset($_POST['localpart'])) { if (substr($_POST['maildir'], 0, 1) !== '/') { header("Location: site.php?failmaildirnonabsolute={$_POST['maildir']}"); die; } if ($testmailroot && is_dir(realpath($_POST['maildir'])) === false) { header("Location: site.php?failmaildirmissing={$_POST['maildir']}"); die; } $domainpath = $_POST['maildir'];
/** * Setup settings on start. * @return void */ protected function prepareSystemEnv() { proc_nice(Daemon::$config->workerpriority->value); register_shutdown_function(function () { $this->shutdown(true); }); $this->setTitle(Daemon::$runName . ': worker process' . (Daemon::$config->pidfile->value !== Daemon::$config->defaultpidfile->value ? ' (' . Daemon::$config->pidfile->value . ')' : '')); if (isset(Daemon::$config->group->value)) { $sg = posix_getgrnam(Daemon::$config->group->value); } if (isset(Daemon::$config->user->value)) { $su = posix_getpwnam(Daemon::$config->user->value); } $flushCache = false; if (Daemon::$config->chroot->value !== '/') { if (posix_getuid() != 0) { Daemon::log('You must have the root privileges to change root.'); exit(0); } elseif (!chroot(Daemon::$config->chroot->value)) { Daemon::log('Couldn\'t change root to \'' . Daemon::$config->chroot->value . '\'.'); exit(0); } $flushCache = true; } if (isset(Daemon::$config->group->value)) { if ($sg === FALSE) { Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . '\'. You must replace config-variable \'group\' with existing group.'); exit(0); } elseif ($sg['gid'] != posix_getgid() && !posix_setgid($sg['gid'])) { Daemon::log('Couldn\'t change group to \'' . Daemon::$config->group->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno)); exit(0); } $flushCache = true; } if (isset(Daemon::$config->user->value)) { if ($su === FALSE) { Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . '\', user not found. You must replace config-variable \'user\' with existing username.'); exit(0); } elseif ($su['uid'] != posix_getuid() && !posix_setuid($su['uid'])) { Daemon::log('Couldn\'t change user to \'' . Daemon::$config->user->value . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno)); exit(0); } $flushCache = true; } if ($flushCache) { clearstatcache(true); } if (Daemon::$config->cwd->value !== '.') { if (!@chdir(Daemon::$config->cwd->value)) { Daemon::log('Couldn\'t change directory to \'' . Daemon::$config->cwd->value . '.'); } clearstatcache(true); } }
} } function VERIFY($x) { VS($x != false, true); } ////////////////////////////////////////////////////////////////////// VERIFY(posix_access(__DIR__ . "/ext_posix.php")); VERIFY(strlen(posix_ctermid())); VERIFY(strlen(posix_getcwd())); $ret = posix_getgrgid(posix_getgid()); VERIFY($ret != false); VERIFY(count((array) $ret) != 0); $bynam = posix_getgrnam($ret['name']); VS($ret, $bynam); $ret = posix_getgrnam("root"); VERIFY($ret != false); VERIFY(count((array) $ret) != 0); $bygid = posix_getgrgid($ret['gid']); VS($ret, $bygid); // $ret = posix_getgroups(); // VERIFY($ret != false); // VERIFY(count((array)$ret) != 0); VERIFY(posix_getpgid(0)); VERIFY(posix_getpgrp()); VERIFY(posix_getpid()); VERIFY(posix_getppid()); $ret = posix_getpwnam("root"); VERIFY($ret != false); VERIFY(count((array) $ret) != 0); VS(posix_getpwnam(""), false);
public function run() { proc_nice(Daemon::$settings['workerpriority']); Daemon::$worker = $this; $this->microsleep = Daemon::$settings['microsleep']; $this->autoReloadLast = time(); $this->reloadDelay = Daemon::$parsedSettings['mpmdelay'] + 2; $this->setStatus(4); Thread::setproctitle(Daemon::$runName . ': worker process' . (Daemon::$settings['pidfile'] !== Daemon::$settings['defaultpidfile'] ? ' (' . Daemon::$settings['pidfile'] . ')' : '')); register_shutdown_function(array($this, 'shutdown')); if (Daemon::$settings['autogc'] > 0) { gc_enable(); } else { gc_disable(); } if (isset(Daemon::$settings['group'])) { $sg = posix_getgrnam(Daemon::$settings['group']); } if (isset(Daemon::$settings['user'])) { $su = posix_getpwnam(Daemon::$settings['user']); } if (Daemon::$settings['chroot'] !== '/') { if (posix_getuid() != 0) { Daemon::log('You must have the root privileges to change root.'); exit(0); } elseif (!chroot(Daemon::$settings['chroot'])) { Daemon::log('Couldn\'t change root to \'' . Daemon::$settings['chroot'] . '\'.'); exit(0); } } if (isset(Daemon::$settings['group'])) { if ($sg === FALSE) { Daemon::log('Couldn\'t change group to \'' . Daemon::$settings['group'] . '\'. You must replace config-variable \'group\' with existing group.'); exit(0); } elseif ($sg['gid'] != posix_getgid() && !posix_setgid($sg['gid'])) { Daemon::log('Couldn\'t change group to \'' . Daemon::$settings['group'] . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno)); exit(0); } } if (isset(Daemon::$settings['user'])) { if ($su === FALSE) { Daemon::log('Couldn\'t change user to \'' . Daemon::$settings['user'] . '\', user not found. You must replace config-variable \'user\' with existing username.'); exit(0); } elseif ($su['uid'] != posix_getuid() && !posix_setuid($su['uid'])) { Daemon::log('Couldn\'t change user to \'' . Daemon::$settings['user'] . "'. Error (" . ($errno = posix_get_last_error()) . '): ' . posix_strerror($errno)); exit(0); } } if (Daemon::$settings['cwd'] !== '.') { if (!@chdir(Daemon::$settings['cwd'])) { Daemon::log('WORKER ' . $this->pid . '] Couldn\'t change directory to \'' . Daemon::$settings['cwd'] . '.'); } } $this->setStatus(6); $this->eventBase = event_base_new(); Daemon::$appResolver->preload(); foreach (Daemon::$appInstances as $app) { foreach ($app as $appInstance) { if (!$appInstance->ready) { $this->ready = TRUE; $appInstance->onReady(); } } } $this->setStatus(1); $ev = event_new(); event_set($ev, STDIN, EV_TIMEOUT, function () { }, array()); event_base_set($ev, $this->eventBase); $this->timeoutEvent = $ev; while (TRUE) { pcntl_signal_dispatch(); if (($s = $this->checkState()) !== TRUE) { $this->closeSockets(); if (sizeof($this->queue) === 0) { return $s; } } event_add($this->timeoutEvent, $this->microsleep); event_base_loop($this->eventBase, EVLOOP_ONCE); do { for ($i = 0, $s = sizeof($this->eventsToAdd); $i < $s; ++$i) { event_add($this->eventsToAdd[$i]); unset($this->eventsToAdd[$i]); } $this->readPool(); $processed = $this->runQueue(); } while ($processed || $this->readPoolState || $this->eventsToAdd); } }
/** * Check if visibility should be changed * @param SimpleXMLElement $order * @return int 0|-1 */ private function _checkVisibility($order) { $attributes = array(); foreach ($order->attributes() as $key => $value) { $attributes[(string) $key] = $this->_parseContent(trim((string) $value)); } $order = $this->_parseContent(trim((string) $order)); if (!array_key_exists('mode', $attributes)) { throw new \Exception('"<visibility>' . $order . '</visibility>" is missing mode'); } $return = 0; switch ($attributes['mode']) { case "isfile": if (!is_file($order)) { $return = -1; } break; case "notisfile": if (is_file($order)) { $return = -1; } break; case "isdir": if (!is_dir($order)) { $return = -1; } break; case "notisdir": if (is_dir($order)) { $return = -1; } break; case "false": if ($order == true) { $return = -1; } break; case "true": if ($order == false) { $return = -1; } break; case "notempty": if ($order == "") { $return = -1; } break; case "userexists": if (posix_getpwnam($order) === false) { $return = -1; } break; case "groupexists": if (posix_getgrnam($order) === false) { $return = -1; } break; case "usernotexists": if (is_array(posix_getpwnam($order))) { $return = -1; } break; case "groupnotexists": if (is_array(posix_getgrnam($order))) { $return = -1; } break; case "equals": $return = isset($attributes['value']) && $attributes['value'] == $order ? 0 : -1; break; } return $return; }
public function setGroupAndUser() { $this->group = posix_getgrnam('www-data')['gid']; $this->user = posix_getpwnam('www-data')['uid']; }
/** * Get file owner * * @param string $filename * @access protected * @return string */ protected function _getFileOwner($filename) { if (!function_exists('posix_getpwuid')) { return 'n/a'; } $owner = posix_getpwuid(fileowner($filename)); $groupinfo = posix_getgrnam(filegroup($filename)); return $owner['name'] . ' / ' . $groupinfo; }
/** * Actions on early startup. * @return void */ public static function init() { Daemon::initSettings(); Daemon::$runName = basename($_SERVER['argv'][0]); $error = FALSE; $argv = $_SERVER['argv']; $runmode = isset($argv[1]) ? str_replace('-', '', $argv[1]) : ''; $args = Daemon_Bootstrap::getArgs($argv); if (!isset(self::$params[$runmode]) && !in_array($runmode, self::$commands)) { if ('' !== $runmode) { echo 'Unrecognized command: ' . $runmode . "\n"; } self::printUsage(); exit; } elseif ('help' === $runmode) { self::printHelp(); exit; } if (isset($args['configfile'])) { Daemon::$config->configfile->setHumanValue($args['configfile']); } if (!Daemon::$config->loadCmdLineArgs($args)) { $error = TRUE; } if (!Daemon::loadConfig(Daemon::$config->configfile->value)) { $error = TRUE; } if (version_compare(PHP_VERSION, '5.3.0', '>=') === 1) { Daemon::log('PHP >= 5.3.0 required.'); $error = TRUE; } if (!Daemon::$useSockets) { Daemon::log('Cannot use socket extension, using stream_* instead. Non-critical error, but the performance compromised.'); } if (isset(Daemon::$config->locale->value) && Daemon::$config->locale->value !== '') { setlocale(LC_ALL, explode(',', Daemon::$config->locale->value)); } if (Daemon::$config->autoreimport->value && !is_callable('runkit_import')) { Daemon::log('runkit extension not found. You should install it or disable --auto-reimport.'); $error = TRUE; } if (!is_callable('posix_kill')) { Daemon::log('Posix not found. You should compile PHP without \'--disable-posix\'.'); $error = TRUE; } if (!is_callable('pcntl_signal')) { Daemon::log('PCNTL not found. You should compile PHP with \'--enable-pcntl\'.'); $error = TRUE; } if (!is_callable('event_base_new')) { Daemon::log('libevent extension not found. You have to install libevent from pecl (http://pecl.php.net/package/libevent). `svn checkout http://svn.php.net/repository/pecl/libevent pecl-libevent`.'); $error = TRUE; } if (!is_callable('socket_create')) { Daemon::log('Sockets extension not found. You should compile PHP with \'--enable-sockets\'.'); $error = TRUE; } if (!is_callable('shmop_open')) { Daemon::log('Shmop extension not found. You should compile PHP with \'--enable-shmop\'.'); $error = TRUE; } if (!isset(Daemon::$config->user)) { Daemon::log('You must set \'user\' parameter.'); $error = TRUE; } if (!isset(Daemon::$config->path)) { Daemon::log('You must set \'path\' parameter (path to your application resolver).'); $error = TRUE; } if (!file_exists(Daemon::$config->pidfile->value)) { if (!touch(Daemon::$config->pidfile->value)) { Daemon::log('Couldn\'t create pid-file \'' . Daemon::$config->pidfile->value . '\'.'); $error = TRUE; } Daemon_Bootstrap::$pid = 0; } elseif (!is_file(Daemon::$config->pidfile->value)) { Daemon::log('Pid-file \'' . Daemon::$config->pidfile->value . '\' must be a regular file.'); Daemon_Bootstrap::$pid = FALSE; $error = TRUE; } elseif (!is_writable(Daemon::$config->pidfile->value)) { Daemon::log('Pid-file \'' . Daemon::$config->pidfile->value . '\' must be writable.'); $error = TRUE; } elseif (!is_readable(Daemon::$config->pidfile->value)) { Daemon::log('Pid-file \'' . Daemon::$config->pidfile->value . '\' must be readable.'); Daemon_Bootstrap::$pid = FALSE; $error = TRUE; } else { Daemon_Bootstrap::$pid = (int) file_get_contents(Daemon::$config->pidfile->value); } if (Daemon::$config->chroot->value !== '/') { if (posix_getuid() != 0) { Daemon::log('You must have the root privileges to change root.'); $error = TRUE; } } if (!@is_file(Daemon::$config->path->value)) { Daemon::log('Your application resolver \'' . Daemon::$config->path->value . '\' is not available.'); $error = TRUE; } if (isset(Daemon::$config->group->value) && is_callable('posix_getgid')) { if (($sg = posix_getgrnam(Daemon::$config->group->value)) === FALSE) { Daemon::log('Unexisting group \'' . Daemon::$config->group->value . '\'. You have to replace config-variable \'group\' with existing group-name.'); $error = TRUE; } elseif ($sg['gid'] != posix_getgid() && posix_getuid() != 0) { Daemon::log('You must have the root privileges to change group.'); $error = TRUE; } } if (isset(Daemon::$config->user->value) && is_callable('posix_getuid')) { if (($su = posix_getpwnam(Daemon::$config->user->value)) === FALSE) { Daemon::log('Unexisting user \'' . Daemon::$config->user->value . '\', user not found. You have to replace config-variable \'user\' with existing username.'); $error = TRUE; } elseif ($su['uid'] != posix_getuid() && posix_getuid() != 0) { Daemon::log('You must have the root privileges to change user.'); $error = TRUE; } } if (isset(Daemon::$config->minspareworkers->value) && isset(Daemon::$config->maxspareworkers->value)) { if (Daemon::$config->minspareworkers->value > Daemon::$config->maxspareworkers->value) { Daemon::log('\'minspareworkers\' cannot be greater than \'maxspareworkers\'.'); $error = TRUE; } } if (isset(Daemon::$config->minworkers->value) && isset(Daemon::$config->maxworkers->value)) { if (Daemon::$config->minworkers->value > Daemon::$config->maxworkers->value) { Daemon::$config->minworkers->value = Daemon::$config->maxworkers->value; } } if ($runmode == 'start') { if ($error === FALSE) { Daemon_Bootstrap::start(); } } elseif ($runmode == 'status' || $runmode == 'fullstatus') { $status = Daemon_Bootstrap::$pid && posix_kill(Daemon_Bootstrap::$pid, SIGTTIN); echo '[STATUS] phpDaemon ' . Daemon::$version . ' is ' . ($status ? 'running' : 'NOT running') . ' (' . Daemon::$config->pidfile->value . ").\n"; if ($status && $runmode == 'fullstatus') { echo 'Uptime: ' . Daemon::date_period_text(filemtime(Daemon::$config->pidfile->value), time()) . "\n"; Daemon::$shm_wstate = Daemon::shmop_open(Daemon::$config->pidfile->value, 0, 'wstate', FALSE); $stat = Daemon::getStateOfWorkers(); echo "State of workers:\n"; echo "\tTotal: " . $stat['alive'] . "\n"; echo "\tIdle: " . $stat['idle'] . "\n"; echo "\tBusy: " . $stat['busy'] . "\n"; echo "\tShutdown: " . $stat['shutdown'] . "\n"; echo "\tPre-init: " . $stat['preinit'] . "\n"; echo "\tWait-init: " . $stat['waitinit'] . "\n"; echo "\tInit: " . $stat['init'] . "\n"; } echo "\n"; } elseif ($runmode == 'update') { if (!Daemon_Bootstrap::$pid || !posix_kill(Daemon_Bootstrap::$pid, SIGHUP)) { echo '[UPDATE] ERROR. It seems that phpDaemon is not running' . (Daemon_Bootstrap::$pid ? ' (PID ' . Daemon_Bootstrap::$pid . ')' : '') . ".\n"; } } elseif ($runmode == 'reopenlog') { if (!Daemon_Bootstrap::$pid || !posix_kill(Daemon_Bootstrap::$pid, SIGUSR1)) { echo '[REOPEN-LOG] ERROR. It seems that phpDaemon is not running' . (Daemon_Bootstrap::$pid ? ' (PID ' . Daemon_Bootstrap::$pid . ')' : '') . ".\n"; } } elseif ($runmode == 'reload') { if (!Daemon_Bootstrap::$pid || !posix_kill(Daemon_Bootstrap::$pid, SIGUSR2)) { echo '[RELOAD] ERROR. It seems that phpDaemon is not running' . (Daemon_Bootstrap::$pid ? ' (PID ' . Daemon_Bootstrap::$pid . ')' : '') . ".\n"; } } elseif ($runmode == 'restart') { if ($error === FALSE) { Daemon_Bootstrap::stop(2); Daemon_Bootstrap::start(); } } elseif ($runmode == 'hardrestart') { Daemon_Bootstrap::stop(3); Daemon_Bootstrap::start(); } elseif ($runmode == 'configtest') { $term = new Terminal(); $term->enable_color = TRUE; echo "\n"; $rows = array(); $rows[] = array('parameter' => 'PARAMETER', 'value' => 'VALUE', '_color' => '37', '_bold' => TRUE); foreach (Daemon::$config as $name => $entry) { if (!$entry instanceof Daemon_ConfigEntry) { continue; } $row = array('parameter' => $name, 'value' => var_export($entry->humanValue, TRUE)); if ($entry->defaultValue != $entry->humanValue) { $row['value'] .= ' (' . var_export($entry->defaultValue, TRUE) . ')'; } $rows[] = $row; } $term->drawtable($rows); echo "\n"; } elseif ($runmode == 'stop') { Daemon_Bootstrap::stop(); } elseif ($runmode == 'hardstop') { echo '[HARDSTOP] Sending SIGINT to ' . Daemon_Bootstrap::$pid . '... '; $ok = Daemon_Bootstrap::$pid && posix_kill(Daemon_Bootstrap::$pid, SIGINT); echo $ok ? 'OK.' : 'ERROR. It seems that phpDaemon is not running.'; if ($ok) { $i = 0; while ($r = posix_kill(Daemon_Bootstrap::$pid, SIGTTIN)) { usleep(500000); if ($i == 9) { echo "\nphpDaemon master-process hasn't finished. Sending SIGKILL... "; posix_kill(Daemon_Bootstrap::$pid, SIGKILL); if (!posix_kill(Daemon_Bootstrap::$pid, SIGTTIN)) { echo " Oh, his blood is on my hands :'("; } else { echo "ERROR: Process alive. Permissions?"; } break; } ++$i; } } echo "\n"; } }