formatBytes...

main
Robert 8 months ago
parent a6c5bb1cc5
commit 3a224569de
  1. 9
      app/OS/neato_Alpine.php
  2. 9
      app/OS/neato_Linux_Generic.php
  3. 9
      app/OS/neato_Ubuntu.php
  4. 23
      app/init_systems/systemd.php
  5. 2
      app/neato_colors.php
  6. 12
      app/neato_common.php
  7. 2
      app/neato_fns.php
  8. 9
      app/neato_init.php
  9. 4
      app/neato_registry.php
  10. 15
      app/traits/init_systems.php
  11. 53
      app/traits/linux_core.php
  12. 102
      app/traits/su.php
  13. 60
      build/view_phar_file_contents.php
  14. 4
      deploy_files/deploy_mysql_ex1.php
  15. 4
      deploy_files/deploy_podman.php
  16. 2
      static_tests.sh
  17. 2
      testing.md

@ -2,6 +2,7 @@
final class neato {
use \traits\su;
use \traits\linux_core;
use \traits\packages;
use \traits\init_systems;
@ -14,6 +15,14 @@ final class neato {
const get_super_user_bin = '/usr/sbin/';
const get_user_local_bin = '/usr/local/bin/';
public static $init_systems = [
'/etc/systemd'=>'systemd',
'/etc/init.d'=>'sys_v_init',
'/etc/init'=>'upstart',
'/etc/runlevels'=>'open_rc',
'/etc/runit'=>'runit',
];
protected function __construct() { }
}

@ -2,6 +2,7 @@
final class neato {
use \traits\su;
use \traits\linux_core;
use \traits\packages;
use \traits\init_systems;
@ -14,6 +15,14 @@ final class neato {
const get_super_user_bin = '/usr/sbin/';
const get_user_local_bin = '/usr/local/bin/';
public static $init_systems = [
'/etc/systemd'=>'systemd',
'/etc/init.d'=>'sys_v_init',
'/etc/init'=>'upstart',
'/etc/runlevels'=>'open_rc',
'/etc/runit'=>'runit',
];
protected function __construct() { }
}

@ -2,6 +2,7 @@
final class neato {
use \traits\su;
use \traits\linux_core;
use \traits\packages;
use \traits\init_systems;
@ -14,6 +15,14 @@ final class neato {
const get_super_user_bin = '/usr/sbin/';
const get_user_local_bin = '/usr/local/bin/';
public static $init_systems = [
'/etc/systemd'=>'systemd',
'/etc/init.d'=>'sys_v_init',
'/etc/init'=>'upstart',
'/etc/runlevels'=>'open_rc',
'/etc/runit'=>'runit',
];
protected function __construct() { }
}

@ -6,7 +6,18 @@ namespace init_systems;
class systemd {
private static function get_valid_action_for_service(string $action): string|false {
private static function _doRoot(): string {
$root = \neato::becomeRoot();
if ($root === true) {
return "";
}
if ($root === false) {
throw new \Exception("Unable to su as root");
}
return $root . " ";
}
private static function getValidActionForService(string $action): string|false {
return match($action) {
'start'=>'start',
'stop'=>'stop',
@ -28,7 +39,7 @@ class systemd {
};
}
private static function get_valid_action_for_system_ctl(string $action): string|false {
private static function getValidActionForSystemCtl(string $action): string|false {
return match($action) {
'start'=>'start',
'stop'=>'stop',
@ -42,16 +53,16 @@ class systemd {
}
public static function service(string $name, string $action = 'restart') {
$my_action = self::get_valid_action_for_service($action);
exec(\neato::get_super_user_bin . 'service ' . safeCmd($name, $my_action), $output, $exit_code);
$my_action = self::getValidActionForService($action);
exec(self::_doRoot() . \neato::get_super_user_bin . 'service ' . safeCmd($name, $my_action), $output, $exit_code);
display($output);
checkForError($exit_code, "Unable to {$action} Service called: {$name}");
return $exit_code;
}
public static function systemctl(string $name, string $action = 'enable') {
$my_action = self::get_valid_action_for_system_ctl($action);
exec(\neato::get_bin . 'systemctl ' . safeCmd($my_action, $name), $output, $exit_code);
$my_action = self::getValidActionForSystemCtl($action);
exec(self::_doRoot() . \neato::get_bin . 'systemctl ' . safeCmd($my_action, $name), $output, $exit_code);
checkForError($exit_code, "Unable to {$action} Service called: {$name}");
return $exit_code;
}

@ -78,7 +78,7 @@ function getTermColors(array|string $input, $options): string
$colored_string .= "\033[" . $bg_colors[$bg_color] . "m";
}
$str = '';
$str = '';
if (is_array($input)) {
foreach ($input as $s) {
$str .= $s . PHP_EOL;

@ -24,12 +24,12 @@ require 'neato_enc.php';
Configure::set('logger_time_zone', 'America/Detroit');
Neato_Registry::set('loader', new \Neato_Auto_Loader);
Neato_Registry::get('loader')->register();
Neato_Registry::get('loader')->addNamespace('utils', 'utils');
Neato_Registry::get('loader')->addNamespace('traits', 'traits');
Neato_Registry::get('loader')->addNamespace('package_managers', 'package_managers');
Neato_Registry::get('loader')->addNamespace('init_systems', 'init_systems');
Registry::set('loader', new \Neato_Auto_Loader);
Registry::get('loader')->register();
Registry::get('loader')->addNamespace('utils', 'utils');
Registry::get('loader')->addNamespace('traits', 'traits');
Registry::get('loader')->addNamespace('package_managers', 'package_managers');
Registry::get('loader')->addNamespace('init_systems', 'init_systems');
/**
* Force script to require being root to run

@ -257,7 +257,7 @@ function stdErr(): string
}
/**
* Force and script to only Run One time...!
* Force the script to only Run One time...!
*
* @param bool $output Display? Will it say Script was run once before...
* @param bool $halt Will exit(1)

@ -41,6 +41,15 @@ if (isCLI() === false) {
exit(1);
}
function formatBytes(int $bytes, int $precision = 2): string {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow)); // Calculation: 1024^$pow
return round($bytes, $precision) . ' ' . $units[$pow];
}
/**
* Grabs the Kernel and System Architecture using PHP uname.
*

@ -20,7 +20,7 @@
* @license https://mit-license.org/ MIT License
* @link https://git.mysnippetsofcode.com/tts/neatoDeploy
*/
final class Neato_Registry
final class Registry
{
private static $_registry = [];
@ -167,7 +167,7 @@ final class Di
}
// Initialize our Dependency Injector
Neato_Registry::set('di', new Di());
Registry::set('di', new Di());
// Setup php for working with Unicode data, if possible
if (extension_loaded('mbstring')) {

@ -4,15 +4,8 @@ namespace traits;
trait init_systems {
private static function get_init_system(): string|false {
$a_init_systems = [
'/etc/systemd'=>'systemd',
'/etc/init.d'=>'sys_v_init',
'/etc/init'=>'upstart',
'/etc/runlevels'=>'open_rc',
'/etc/runit'=>'runit',
];
foreach($a_init_systems as $init_dir=>$init_system_name) {
private static function getInitSystem(): string|false {
foreach(\neato::$init_systems as $init_dir=>$init_system_name) {
if (file_exists($init_dir) && is_dir($init_dir)) {
return $init_system_name;
}
@ -21,7 +14,7 @@ trait init_systems {
}
public static function service(string $name, string $action = 'restart') {
$my_init = self::get_init_system();
$my_init = self::getInitSystem();
if ($my_init === false) {
return false;
}
@ -30,7 +23,7 @@ trait init_systems {
}
public static function systemctl(string $name, string $action = 'enable') {
$my_init = self::get_init_system();
$my_init = self::getInitSystem();
if ($my_init === false) {
return false;
}

@ -4,11 +4,36 @@ namespace traits;
trait linux_core {
public static function no_sticky_bit(string $file) {
public static bool $linuxRoot = false;
private static function _doRoot(): string {
if (self::$linuxRoot === false) {
return "";
}
$root = \neato::becomeRoot();
if ($root === true) {
return "";
}
if ($root === false) {
throw new \Exception("Unable to su as root");
}
return $root . " ";
}
public static function removeStickyBits(string $file) {
if (! file_exists($file)) {
return true;
}
exec(self::_doRoot().self::get_user_bin . 'chmod -s ' . safeCmd($file), $output, $exit_code);
checkForError($exit_code, "Unable to remove sticky bit with chmod: {$file}");
return $exit_code;
}
public static function removeSUID_Bit(string $file) {
if (! file_exists($file)) {
return true;
}
exec(self::get_user_bin . 'chmod -s ' . safeCmd($file), $output, $exit_code);
exec(self::_doRoot().self::get_user_bin . 'chmod u-s ' . safeCmd($file), $output, $exit_code);
checkForError($exit_code, "Unable to remove sticky bit with chmod: {$file}");
return $exit_code;
}
@ -18,7 +43,7 @@ trait linux_core {
$exit_code = false;
} else {
$perm = getPerms($kind);
exec(self::get_user_bin . 'find ' . safeCmd($dir) . ' -type d -exec ' . self::get_bin . 'chmod ' . $perm . ' {} \;', $output, $exit_code);
exec(self::_doRoot().self::get_user_bin . 'find ' . safeCmd($dir) . ' -type d -exec ' . self::get_bin . 'chmod ' . $perm . ' {} \;', $output, $exit_code);
}
checkForError($exit_code, "Unable to chmod folders in: {$dir}");
return $exit_code;
@ -29,7 +54,7 @@ trait linux_core {
$exit_code = false;
} else {
$perm = getPerms($kind);
exec(self::get_user_bin . 'find ' . safeCmd($dir) . ' -type f -exec ' . self::get_bin . 'chmod ' . $perm . ' {} \;', $output, $exit_code);
exec(self::_doRoot().self::get_user_bin . 'find ' . safeCmd($dir) . ' -type f -exec ' . self::get_bin . 'chmod ' . $perm . ' {} \;', $output, $exit_code);
}
checkForError($exit_code, "Unable to chmod files in: {$dir}");
return $exit_code;
@ -39,7 +64,7 @@ trait linux_core {
if (!is_file($file)) {
$exit_code = false;
} else {
exec(self::get_user_bin . 'chattr +i ' . safeCmd($file), $output, $exit_code);
exec(self::_doRoot().self::get_user_bin . 'chattr +i ' . safeCmd($file), $output, $exit_code);
}
checkForError($exit_code, "Unable to write protect: {$file}");
return $exit_code;
@ -49,7 +74,7 @@ trait linux_core {
if (!is_file($file)) {
$exit_code = false;
} else {
exec(self::get_user_bin . 'chattr -i ' . safeCmd($file), $output, $exit_code);
exec(self::_doRoot().self::get_user_bin . 'chattr -i ' . safeCmd($file), $output, $exit_code);
}
checkForError($exit_code, "Unable to un-write protect: {$file}");
return $exit_code;
@ -57,7 +82,7 @@ trait linux_core {
public static function groupadd(string $groupname, int $gid = 0) {
$group_id = ($gid > 0) ? "-g {$gid} " : "";
exec(self::get_super_user_bin . 'groupadd '. $group_id . safeCmd($groupname), $output, $exit_code);
exec(self::_doRoot().self::get_super_user_bin . 'groupadd '. $group_id . safeCmd($groupname), $output, $exit_code);
if ($exit_code === 0) {
display(getTermColors("Added new group named: $groupname", ['color'=>'green']));
}
@ -66,7 +91,7 @@ trait linux_core {
}
public static function userdel(string $username) {
exec(self::get_super_user_bin . 'userdel ' . safeCmd($username), $output, $exit_code);
exec(self::_doRoot().self::get_super_user_bin . 'userdel ' . safeCmd($username), $output, $exit_code);
if ($exit_code === 0) {
display(getTermColors("Deleted user account named: $username", ['color'=>'green']));
}
@ -77,7 +102,7 @@ trait linux_core {
public static function useradd(string $username, int $uid = 0, string $shell="/bin/bash", string $comment = "", string $groups="", string $homedir="") {
$user_id = ($uid > 0) ? "-u {$uid} " : "";
$dir = (empty($homedir)) ? " -m " : " -d " . safeCmd($homedir);
exec(self::get_super_user_bin . 'useradd '. $user_id . '-s '. safeCmd($shell) . $dir . ' -c '. safeCmd($comment) .'-G'. safeCmd($groups) . ' ' . safeCmd($username), $output, $exit_code);
exec(self::_doRoot().self::get_super_user_bin . 'useradd '. $user_id . '-s '. safeCmd($shell) . $dir . ' -c '. safeCmd($comment) .'-G'. safeCmd($groups) . ' ' . safeCmd($username), $output, $exit_code);
if ($exit_code === 0) {
display(getTermColors("Added new user account named: $username", ['color'=>'green']));
}
@ -86,7 +111,7 @@ trait linux_core {
}
public static function lock_status(string $username) {
exec(self::get_user_bin . 'passwd -S ' . safeCmd($username) . " | awk '{print $2}'", $output, $exit_code);
exec(self::_doRoot().self::get_user_bin . 'passwd -S ' . safeCmd($username) . " | awk '{print $2}'", $output, $exit_code);
$sw = $output[0] ?? "";
switch ($sw) {
case "P": echo "Account is not locked"; break;
@ -99,28 +124,28 @@ trait linux_core {
}
public static function passwd(string $username) {
exec(self::get_user_bin . 'passwd ' . safeCmd($username), $output, $exit_code);
exec(self::_doRoot().self::get_user_bin . 'passwd ' . safeCmd($username), $output, $exit_code);
checkForError($exit_code, "Unable to set user password: {$username}");
return $exit_code;
}
// Details about age of passwords
public static function chage(string $username) {
exec(self::get_user_bin . 'chage -l ' . safeCmd($username), $output, $exit_code);
exec(self::_doRoot().self::get_user_bin . 'chage -l ' . safeCmd($username), $output, $exit_code);
checkForError($exit_code, "Unable to view user password changes: {$username}");
return $exit_code;
}
// yyyy-mm-dd
public static function lock(string $username, string $expires_on="") {
$exp = (! empty($expires_on)) ? "--expiredate ". safeCmd($expires_on) . " " : "";
exec(self::get_super_user_bin . 'usermod -L '. $exp . safeCmd($username), $output, $exit_code);
exec(self::_doRoot().self::get_super_user_bin . 'usermod -L '. $exp . safeCmd($username), $output, $exit_code);
checkForError($exit_code, "Unable to Lock user account: {$username}");
return $exit_code;
}
public static function unlock(string $username, string $expires_on="") {
$exp = (! empty($expires_on)) ? "--expiredate ". safeCmd($expires_on) . " " : "--expiredate '' ";
exec(self::get_super_user_bin . 'usermod -U ' . $exp . safeCmd($username), $output, $exit_code);
exec(self::_doRoot().self::get_super_user_bin . 'usermod -U ' . $exp . safeCmd($username), $output, $exit_code);
checkForError($exit_code, "Unable to Unlock user account: {$username}");
return $exit_code;
}

@ -0,0 +1,102 @@
<?php
namespace traits;
trait su {
/**
* Returns which if found or command -v to give Executable
* details such as path detected for program.
*
* @return string /usr/bin/which or command -v
*/
public static function getExecutableDetails(): string
{
$witch_exec = \neato::get_user_bin . "which";
if (file_exists($witch_exec) && is_executable($witch_exec)) {
return $witch_exec;
}
return "command -v";
}
/**
* gets BIN paths that are trusted by the system
*
* @param string $executable_file path+executable
*
* @return string|false trusted bin or false is not trustworthy
*/
public static function getTrustedPath(string $executable_file): string|false
{
$dir = dirname($executable_file);
$prog = basename($executable_file);
return match($dir."/") {
\neato::get_user_bin => \neato::get_user_bin.$prog,
\neato::get_super_user_bin => \neato::get_super_user_bin.$prog,
\neato::get_bin => \neato::get_bin.$prog,
\neato::get_super_bin => \neato::get_super_bin.$prog,
default => false,
};
}
/**
* becomeRoot user
*
* @return string|bool sudo or doas, or true is root, false unknown su root
*
* @throws \Exception upon un-trusted BIN path
*/
public static function becomeRoot(): string|bool
{
if (posix_getuid() === 0) {
return true;
}
$use_find_exec = self::getExecutableDetails();
exec($use_find_exec . ' doas', $output, $exit_code);
if ($exit_code === 0) {
$trusted = self::getTrustedPath($output[0]);
if ($trusted === false) {
throw new \Exception("Not a trusted BIN path!");
}
return $trusted;
}
unset($output);
exec($use_find_exec . ' sudo', $output, $exit_code);
if ($exit_code === 0) {
$trusted = self::getTrustedPath($output[0]);
if ($trusted === false) {
throw new \Exception("Not a trusted BIN path!");
}
return $trusted;
}
return false;
}
public static function becomeNormal(string $username): string|bool
{
if (posix_getuid() > 0) {
return true;
}
$use_find_exec = self::getExecutableDetails();
exec($use_find_exec . ' doas', $output, $exit_code);
if ($exit_code === 0) {
$trusted = self::getTrustedPath($output[0]);
if ($trusted === false) {
throw new \Exception("Not a trusted BIN path!");
}
return $trusted . " -u " .$username;
}
unset($output);
exec($use_find_exec . ' sudo', $output, $exit_code);
if ($exit_code === 0) {
$trusted = self::getTrustedPath($output[0]);
if ($trusted === false) {
throw new \Exception("Not a trusted BIN path!");
}
return $trusted . " -u " .$username;
}
return false;
}
}

@ -1,17 +1,65 @@
<?php
// php -f view_phar_file_contents.php -- -nosize
$pharFile = 'neatoDeploy.phar';
function hasNoSizeFlag(): bool {
global $argv;
return in_array('-nosize', $argv) || in_array('--nosize', $argv);
}
function formatBytes(int $bytes, int $precision = 2): string {
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow)); // Calculation: 1024^$pow
return round($bytes, $precision) . $units[$pow];
}
try {
$phar = new Phar($pharFile);
if (!is_readable($pharFile)) {
echo "Need to be root!";
exit(1);
}
// Try different archive types
$ext = pathinfo($pharFile, PATHINFO_EXTENSION);
switch (strtolower($ext)) {
case 'phar':
$archive = new Phar($pharFile, 0);
break;
case 'tar':
case 'zip':
$archive = new PharData($pharFile);
break;
case 'gz':
case 'tgz':
$archive = new PharData('compress.zlib://' . $pharFile);
break;
default:
throw new Exception("Unsupported archive type: $ext");
}
// Get the iterator for the Phar archive
$iterator = new RecursiveIteratorIterator($phar);
$iterator = new RecursiveIteratorIterator($archive);
// Iterate through the contents
foreach ($iterator as $file) {
echo $file->getPathname() . PHP_EOL;
$path = $file->getPathname();
$parent = dirname($path);
$bp = basename($parent);
if ($bp == $pharFile) {
$first = "";
} else {
$first = $bp . '/';
}
$lastTwoParts = $first . basename($path);
if (hasNoSizeFlag()) {
echo $lastTwoParts . PHP_EOL;
} else {
$size = formatBytes($file->getSize()) . "\t ";
echo $size . $lastTwoParts . PHP_EOL;
}
}
} catch (PharException $e) {
} catch (PharException | Exception $e) {
echo "Error reading Phar archive: " . $e->getMessage();
}

@ -6,8 +6,8 @@ Configure::set('passwords', ['length' => rand(16, 26)]);
Configure::set('pre_actions', [
/** @phpstan-ignore-next-line Variable $cwd might not be defined */
'make_dir' => [$cwd . '/my_vaults'=>'', '/etc/neato_secrets'=>''],
'chmod_file_or_dir' =>
'makeDir' => [$cwd . '/my_vaults'=>'', '/etc/neato_secrets'=>''],
'chmodFileOrDir' =>
/** @phpstan-ignore-next-line Variable $cwd might not be defined */
[ $cwd . '/my_vaults' => 'keydir', '/etc/neato_secrets' => 'keydir' ],
]);

@ -4,8 +4,8 @@ Configure::set('logfile', false); // Save to log folder
Configure::set('syslog', false);
Configure::set('pre_actions', [
'make_dir' => ['/etc/containers'=>''],
'chmod_file_or_dir' =>
'makeDir' => ['/etc/containers'=>''],
'chmodFileOrDir' =>
['/etc/containers' => 'dir'],
]);

@ -58,4 +58,4 @@ else
esac
fi
./vendor/bin/phpstan analyse $@ $command_params
vendor/bin/phpstan analyse $@ $command_params

@ -9,7 +9,7 @@ $ ./static_tests.sh
## Quick and Dirty testing
```
from your app folder, run an deployment file, EXAMPLE:
$ ./just_testing.sh [deploy_tets1.php]
$ ./just_testing.sh [deploy_test1.php]
```
## Where are the deployment files?

Loading…
Cancel
Save