r032: fix share capacity and add native scoped administration

This commit is contained in:
Mikei386 committed 2026-10-24 22:59:58 +02:00
1 parent b9a2f2e309
commit 11786968cb
20 files changed
+754 -23

No files matched your search

+270
View File
@@ -0,0 +1,270 @@
<?php
/** Typed native Unraid administration. No arbitrary XML, shell or passwords. */
declare(strict_types=1);
function mua_path(string $path): string { return ($GLOBALS['mua_test_root'] ?? '') . $path; }
function mua_name(mixed $name): string {
if (!is_string($name) || !preg_match('/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/D', $name)) throw new RuntimeException('Invalid exact target name');
if (in_array(strtolower($name), ['openvpn-kit', 'gluetunvpn', 'vpn.auth'], true)) throw new RuntimeException('Protected target');
return $name;
}
function mua_run(array $argv, array $allowedCodes = [0]): string {
if (isset($GLOBALS['mua_test_run'])) return ($GLOBALS['mua_test_run'])($argv);
$p = proc_open($argv, [0=>['pipe','r'],1=>['pipe','w'],2=>['pipe','w']], $pipes, '/');
if (!is_resource($p)) throw new RuntimeException('Process start failed');
fclose($pipes[0]);
// Drain both streams concurrently, bounded in memory. Parent enforces timeout.
stream_set_blocking($pipes[1], false); stream_set_blocking($pipes[2], false);
$out=''; $err='';
while (!feof($pipes[1]) || !feof($pipes[2])) {
$r=[]; foreach ([1,2] as $i) if (!feof($pipes[$i])) $r[]=$pipes[$i];
if (!$r) break;
$w=null;$e=null;stream_select($r,$w,$e,1);
foreach ($r as $f) { $v=fread($f,8192); if ($f===$pipes[1]) $out=substr($out.$v,0,131072); else $err=substr($err.$v,0,4096); }
}
fclose($pipes[1]);fclose($pipes[2]);$rc=proc_close($p);
if (!in_array($rc,$allowedCodes,true)) throw new RuntimeException(basename($argv[0]).' failed (exit '.$rc.'): '.substr($err,0,1000));
return trim($out);
}
function mua_json(array $argv): array {
$v=json_decode(mua_run($argv),true,512,JSON_THROW_ON_ERROR);
if (!is_array($v)) throw new RuntimeException('Unexpected command JSON'); return $v;
}
function mua_users(bool $includeRoot=false): array {
$rows=parse_ini_file(mua_path('/var/local/emhttp/users.ini'),true,INI_SCANNER_RAW);
if (!is_array($rows)) throw new RuntimeException('User metadata unavailable');
$out=[]; foreach ($rows as $name=>$row) { $name=trim((string)$name,'"'); if (($includeRoot || $name!=='root') && isset($row['idx']) && ctype_digit((string)$row['idx'])) $out[]=['name'=>$name,'index'=>(int)$row['idx']]; }
return $out;
}
function mua_cfg(string $name): string { return mua_path('/boot/config/shares/'.mua_name($name).'.cfg'); }
function mua_private_spec(array $x): array {
$name=mua_name($x['name']??null);$action=$x['action']??'';
if (!in_array($action,['create','permissions','remove'],true)) throw new RuntimeException('Invalid share action');
$out=['action'=>$action,'name'=>$name];
if ($action==='remove') return $out;
$access=$x['access']??null;
if (!is_array($access) || !$access || count($access)>64) throw new RuntimeException('Explicit access map required');
$users=array_column(mua_users(),'index','name');
foreach ($access as $user=>$mode) {
if (!isset($users[$user]) || !in_array($mode,['read-write','read-only'],true)) throw new RuntimeException('Unknown user or access mode');
}
ksort($access);$out['access']=$access;
$out['security']='private';
$out['export']='e';
if ($action==='permissions') {
$cfg=mua_cfg($name);if(!is_file($cfg)||is_link($cfg))throw new RuntimeException('Share configuration missing or symlink');
$current=parse_ini_file($cfg,false,INI_SCANNER_RAW);$out['export']=$current['shareExport']??'-';
if(!in_array($out['export'],['e','eh','-'],true))throw new RuntimeException('Unsupported existing export mode');
}
if ($action==='create') {
$out['pool']=mua_name($x['pool']??null);
if (!is_dir(mua_path('/mnt/'.$out['pool'])) || in_array($out['pool'],['user','user0','disks','remotes'],true) || preg_match('/^disk\d+$/',$out['pool'])) throw new RuntimeException('Existing named pool required');
$comment=$x['description']??'';
if (!is_string($comment) || strlen($comment)>500 || preg_match('/[\x00-\x1f]/',$comment)) throw new RuntimeException('Invalid description');
$out['description']=$comment;
}
return $out;
}
function mua_share_empty(string $path): bool {
if (!is_dir($path) || is_link($path)) return false;
$it=new FilesystemIterator($path,FilesystemIterator::SKIP_DOTS);return !$it->valid();
}
function mua_share_state(array $x): array {
$cfg=mua_cfg($x['name']);$exists=is_file($cfg);
if (is_link($cfg)) throw new RuntimeException('Symlink configuration refused');
$state=['config_exists'=>$exists,'config_sha256'=>$exists?hash_file('sha256',$cfg):null];
$path=mua_path('/mnt/user/'.$x['name']);
$state['path_exists']=file_exists($path);$state['empty']=$state['path_exists']?mua_share_empty($path):null;
if ($x['action']==='create' && ($exists||$state['path_exists'])) throw new RuntimeException('Share already exists');
if ($x['action']!=='create' && !$exists) throw new RuntimeException('Share configuration missing');
if ($x['action']==='remove' && $state['empty']!==true) throw new RuntimeException('Only existing empty shares can be removed');
if ($x['action']!=='remove') $state['users']=mua_users(true);
return $state;
}
function mua_share_rights(string $name): array {
$p=mua_cfg($name);if (!is_file($p)) throw new RuntimeException('Share configuration missing');
$c=parse_ini_file($p,false,INI_SCANNER_RAW);
$out=[];foreach (['shareComment','shareExport','shareSecurity','shareReadList','shareWriteList','shareCachePool','shareUseCache'] as $key) $out[$key]=$c[$key]??null;
$out['effective_smb_section']=$out['shareExport']==='-'?'':mua_run(['/usr/bin/testparm','-s','--section-name='.$name]);
$out['verification']='configuration_only_not_authenticated_smb';return $out;
}
function mua_emcmd(array $params): void {
$q=http_build_query($params);if ($q==='') throw new RuntimeException('Empty native action');
mua_run(['/usr/local/sbin/emcmd',$q]);
}
function mua_share_apply(array $x): array {
$name=$x['name'];$stages=[];
try {
if ($x['action']==='remove') {
if (!mua_share_empty(mua_path('/mnt/user/'.$name))) throw new RuntimeException('Share became nonempty');
mua_emcmd(['cmdEditShare'=>'Delete','shareName'=>$name,'shareNameOrig'=>$name,'confirmDelete'=>'on']);$stages[]='native_delete';
if (file_exists(mua_cfg($name)) || file_exists(mua_path('/mnt/user/'.$name))) throw new RuntimeException('Share removal incomplete');
return ['ok'=>true,'name'=>$name,'removed'=>true,'stages'=>$stages];
}
if ($x['action']==='create') {
mua_emcmd(['cmdEditShare'=>'Add Share','shareName'=>$name,'shareNameOrig'=>'','shareComment'=>$x['description'],'shareUseCache'=>'only','shareCachePool'=>$x['pool'],'shareCachePool2'=>'','shareAllocator'=>'highwater','shareSplitLevel'=>'','shareInclude'=>'','shareExclude'=>'','shareCOW'=>'auto','shareFloor'=>'0']);$stages[]='native_create';
if (!is_file(mua_cfg($name))) throw new RuntimeException('Native create did not produce configuration');
}
$security=['changeShareSecurity'=>'Apply','shareName'=>$name,'shareExport'=>'-','shareSecurity'=>'private','shareCaseSensitive'=>'auto','shareVolsizelimit'=>''];
mua_emcmd($security);$stages[]='private_export_disabled';
$access=['changeShareAccess'=>'Apply','shareName'=>$name];
foreach (mua_users(true) as $user) $access['userAccess.'.$user['index']]=$x['access'][$user['name']]??'no-access';
mua_emcmd($access);$stages[]='access_set';
$security['shareExport']=$x['export'];mua_emcmd($security);$stages[]='export_restored_or_enabled';
$v=mua_share_rights($name);
$wantRead=array_keys(array_filter($x['access'],fn($v)=>$v==='read-only'));
$wantWrite=array_keys(array_filter($x['access'],fn($v)=>$v==='read-write'));
$list=fn($v)=>array_values(array_filter(preg_split('/[\s,]+/',trim((string)$v))?:[]));
$read=$list($v['shareReadList']);$write=$list($v['shareWriteList']);sort($read);sort($write);sort($wantRead);sort($wantWrite);
if ($v['shareSecurity']!=='private'||$v['shareExport']!==$x['export']||$read!==$wantRead||$write!==$wantWrite) throw new RuntimeException('Rights readback mismatch');
$effective=[];
foreach(explode("\n",$v['effective_smb_section']) as $line)if(preg_match('/^\s*(valid users|read list|write list)\s*=\s*(.*)$/',$line,$m)){$effective[$m[1]]=$list($m[2]);sort($effective[$m[1]]);}
$wantUsers=array_keys($x['access']);sort($wantUsers);
if($x['export']!=='-' && (($effective['valid users']??[])!==$wantUsers||($effective['write list']??[])!==$wantWrite||($effective['read list']??[])!==$wantRead))throw new RuntimeException('Effective Samba rights do not match request');
return ['ok'=>true,'name'=>$name,'stages'=>$stages,'verification'=>$v];
} catch (Throwable $e) {
// Do not erase data or attempt speculative rollback; fail closed on SMB export.
if ($x['action']!=='remove' && is_file(mua_cfg($name))) {
try {mua_emcmd(['changeShareSecurity'=>'Apply','shareName'=>$name,'shareExport'=>'-','shareSecurity'=>'private','shareCaseSensitive'=>'auto','shareVolsizelimit'=>'']);$stages[]='failure_export_disabled';} catch (Throwable) {$stages[]='failure_export_disable_failed';}
}
throw new RuntimeException(json_encode(['ok'=>false,'stages'=>$stages,'error'=>$e->getMessage(),'partial_state'=>'inspect exact target before retry'],JSON_UNESCAPED_SLASHES));
}
}
function mua_template_path(string $name): string {return mua_path('/boot/config/plugins/dockerMan/templates-user/my-'.mua_name($name).'.xml');}
function mua_docker_spec(array $x): array {
$action=$x['action']??'';$name=mua_name($x['name']??null);
if (!in_array($action,['create','remove'],true)) throw new RuntimeException('Invalid Docker action');
if ($action==='remove') return ['action'=>$action,'name'=>$name,'remove_template'=>($x['remove_template']??false)===true];
$image=$x['image']??'';
if (!is_string($image)||strlen($image)>300||!preg_match('/^[a-z0-9][a-z0-9._:\/\-]*(?:@sha256:[a-f0-9]{64})?$/D',$image)||str_contains($image,'..')) throw new RuntimeException('Invalid image reference');
$ports=$x['ports']??[];if (!is_array($ports)||count($ports)>8) throw new RuntimeException('At most 8 ports');
$seen=[];
foreach ($ports as &$p) {
if (!is_array($p)) throw new RuntimeException('Invalid port');
foreach (['host_port','container_port'] as $k) { $value=$p[$k]??null; if (!is_int($value)||$value<($k==='host_port'?1024:1)||$value>65535) throw new RuntimeException('Invalid port range'); }
$p=['host_port'=>$p['host_port'],'container_port'=>$p['container_port'],'protocol'=>$p['protocol']??'tcp'];
if (!in_array($p['protocol'],['tcp','udp'],true)) throw new RuntimeException('Invalid protocol');
$key=$p['host_port'].'/'.$p['protocol'];if(isset($seen[$key]))throw new RuntimeException('Duplicate port');$seen[$key]=true;
} unset($p);
$mem=$x['memory_mb']??128;$cpu=$x['cpus']??0.5;
if (!is_int($mem)||$mem<32||$mem>2048||!is_numeric($cpu)||$cpu<0.1||$cpu>4) throw new RuntimeException('Invalid resource limits');
$description=$x['description']??'';if(!is_string($description)||strlen($description)>1000||str_contains($description,"\0"))throw new RuntimeException('Invalid description');
return ['action'=>$action,'name'=>$name,'image'=>$image,'ports'=>$ports,'memory_mb'=>$mem,'cpus'=>(float)$cpu,'description'=>$description];
}
function mua_template_xml(array $x): string {
$d=new DOMDocument('1.0','utf-8');$r=$d->appendChild($d->createElement('Container'));$r->setAttribute('version','2');
foreach (['Name'=>$x['name'],'Repository'=>$x['image'],'Network'=>'bridge','Privileged'=>'false','TailscaleEnabled'=>'false','Overview'=>$x['description'],'TemplateURL'=>'','WebUI'=>'','ExtraParams'=>'--restart=no --memory='.$x['memory_mb'].'m --cpus='.$x['cpus']] as $k=>$v) {$e=$r->appendChild($d->createElement($k));$e->appendChild($d->createTextNode($v));}
foreach (['Registry','Icon','Support','Project','ReadMe','Category','MyIP','MyMAC','PostArgs','CPUset','DonateText','DonateLink','Requires'] as $k) $r->appendChild($d->createElement($k));
$r->appendChild($d->createElement('Shell','sh'));
foreach ($x['ports'] as $p) {
$e=$r->appendChild($d->createElement('Config','127.0.0.1:'.$p['host_port']));
foreach (['Name'=>'Port '.$p['container_port'],'Target'=>(string)$p['container_port'],'Type'=>'Port','Mode'=>$p['protocol'],'Default'=>'127.0.0.1:'.$p['host_port']] as $k=>$v) $e->setAttribute($k,$v);
}
return $d->saveXML();
}
function mua_native_render(string $xml): array {
global $docroot,$var,$driver,$subnet;
$docroot='/usr/local/emhttp';$var=['timeZone'=>'Europe/Berlin','NAME'=>gethostname()];$driver=['bridge'=>'bridge'];$subnet=['bridge'=>''];
require_once "$docroot/plugins/dynamix.docker.manager/include/Helpers.php";
return xmlToCommand($xml,false);
}
function mua_docker_state(array $x): array {
$p=mua_template_path($x['name']);if(is_link($p))throw new RuntimeException('Symlink template refused');
// Exact-name filtering avoids inspecting unrelated containers.
$rows=mua_run(['/usr/bin/docker','ps','-a','--filter','name=^/'.$x['name'].'$','--format','{{.ID}}']);
$state=['container_id'=>$rows?:null,'template_sha256'=>is_file($p)?hash_file('sha256',$p):null];
if ($x['action']==='create') {
if ($rows!==''||is_file($p)) throw new RuntimeException('Target already exists');
$xml=mua_template_xml($x);[$cmd,$name,$repo]=mua_native_render($xml);
if ($name!==$x['name']||$repo!==$x['image']||!str_contains($cmd,'net.unraid.docker.managed=dockerman')) throw new RuntimeException('Native rendering mismatch');
foreach($x['ports'] as $port) {
$flags=$port['protocol']==='tcp'?'-Hlnt':'-Hlnu';
if(mua_run(['/usr/sbin/ss',$flags,'sport = :'.$port['host_port']])!=='')throw new RuntimeException('Requested loopback host port is occupied');
}
$state['xml_sha256']=hash('sha256',$xml);
$state['rendered_command']=$cmd;
} else {
if ($rows==='') throw new RuntimeException('Exact container not found');
if($x['remove_template'] && is_file($p)) {
$template=simplexml_load_file($p);
if($template===false || (string)$template->Name!==$x['name'])throw new RuntimeException('Template does not belong to target');
}
$state['image_id']=mua_run(['/usr/bin/docker','inspect','--format','{{.Image}}',$x['name']]);
$state['status']=mua_run(['/usr/bin/docker','inspect','--format','{{.State.Status}}',$x['name']]);
if (!in_array($state['status'],['created','exited'],true)) throw new RuntimeException('Stop container explicitly before removal');
}
return $state;
}
function mua_docker_apply(array $x): array {
$name=$x['name'];$p=mua_template_path($name);$stages=[];
try {
if($x['action']==='remove') {
mua_run(['/usr/bin/docker','rm',$name]);$stages[]='container_removed';
if($x['remove_template']&&is_file($p)){if(!unlink($p))throw new RuntimeException('Template deletion failed');$stages[]='template_removed';}
return ['ok'=>true,'stages'=>$stages,'image_retained'=>true,'volumes_retained'=>true];
}
$xml=mua_template_xml($x);[$cmd,$n,$repo]=mua_native_render($xml);
if($n!==$name||$repo!==$x['image'])throw new RuntimeException('Render mismatch');
// Pull before writing or creating anything. Never delete/rebuild an existing target.
mua_run(['/usr/bin/docker','pull',$repo]);$stages[]='image_pulled';
$f=fopen($p,'x');if(!$f)throw new RuntimeException('Exclusive template creation failed');
if(fwrite($f,$xml)!==strlen($xml)){fclose($f);throw new RuntimeException('Template write incomplete');}fclose($f);chmod($p,0600);$stages[]='template_written';
// The command comes exclusively from our structured XML and Unraid's renderer.
mua_run(['/bin/sh','-c',$cmd]);$stages[]='container_created';
$label=mua_run(['/usr/bin/docker','inspect','--format','{{index .Config.Labels "net.unraid.docker.managed"}}',$name]);
if($label!=='dockerman')throw new RuntimeException('Native manager label not confirmed');
return ['ok'=>true,'name'=>$name,'stages'=>$stages,'started'=>false,'gui_managed'=>true,'template'=>$p,'image_id'=>mua_run(['/usr/bin/docker','inspect','--format','{{.Image}}',$name]),'verification'=>'native_backend_not_visual_gui'];
} catch(Throwable $e){throw new RuntimeException(json_encode(['ok'=>false,'stages'=>$stages,'error'=>$e->getMessage(),'partial_state'=>'own image/template/container may remain; inspect target, do not blindly retry']));}
}
function mua_plan(string $kind,array $input): array {
$x=$kind==='share'?mua_private_spec($input):mua_docker_spec($input);
$state=$kind==='share'?mua_share_state($x):mua_docker_state($x);
return ['kind'=>$kind,'spec'=>$x,'before'=>$state];
}
function mua_apply_plan(array $plan): array {
$name=mua_name($plan['spec']['name']);$lock=fopen(mua_path('/var/lock/mua-admin-'.hash('sha256',$plan['kind'].':'.$name).'.lock'),'c');
if(!$lock||!flock($lock,LOCK_EX|LOCK_NB))throw new RuntimeException('Target busy');
try {
$now=mua_plan($plan['kind'],$plan['spec']);
if($now!==$plan)throw new RuntimeException('Target state changed; request a fresh preview');
return $plan['kind']==='share'?mua_share_apply($plan['spec']):mua_docker_apply($plan['spec']);
}finally{flock($lock,LOCK_UN);fclose($lock);}
}
function mua_diagnostics(array $x): array {
$action=$x['action']??'';
if($action==='parity_history'){
$p=mua_path('/boot/config/parity-checks.log');$rows=[];
if(is_readable($p)){ $f=new SplFileObject($p);foreach($f as $line){if(trim((string)$line)!=='')$rows[]=substr(trim($line),0,1000);if(count($rows)>20)array_shift($rows);} }
return ['source'=>'unraid_parity_history','available'=>is_readable($p),'records'=>$rows,'note'=>'Native records; missing history does not establish a successful check.'];
}
if($action==='zfs_pool'){$name=mua_name($x['target']??null);return ['source'=>'zpool','target'=>$name,'status'=>mua_run(['/usr/sbin/zpool','status','-p',$name])];}
if($action==='zfs_dataset'){
$name=$x['target']??'';if(!is_string($name)||!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.\/-]{0,200}$/D',$name)||str_contains($name,'..')||str_contains(strtolower($name),'openvpn'))throw new RuntimeException('Invalid dataset');
return ['source'=>'zfs','target'=>$name,'properties'=>mua_run(['/usr/sbin/zfs','list','-Hp','-o','name,used,refer,available,usedbysnapshots,mountpoint',$name])];
}
if($action==='zfs_snapshots'){
$name=$x['target']??'';if(!is_string($name)||!preg_match('/^[A-Za-z0-9][A-Za-z0-9_.\/-]{0,200}$/D',$name)||str_contains($name,'..')||str_contains(strtolower($name),'openvpn'))throw new RuntimeException('Invalid dataset');
$raw=mua_run(['/usr/sbin/zfs','list','-Hp','-r','-d','1','-t','snapshot','-S','creation','-o','name,used,creation',$name]);
$rows=$raw===''?[]:explode("\n",$raw);
return ['source'=>'zfs_snapshots','target'=>$name,'records'=>array_slice($rows,0,20),'limited'=>count($rows)>20,'order'=>'newest_first'];
}
if($action==='smart'){
$name=mua_name($x['target']??null);$rows=parse_ini_file(mua_path('/var/local/emhttp/disks.ini'),true,INI_SCANNER_RAW);$device=null;
foreach($rows?:[] as $key=>$row)if(trim((string)($row['name']??$key),'"')===$name)$device=$row['device']??null;
if(!is_string($device)||!preg_match('/^(?:sd[a-z]+|nvme[0-9]+n[0-9]+)$/D',$device))throw new RuntimeException('Known physical disk required');
// smartctl uses exit bits 3-7 for health findings, not execution failures.
$raw=mua_run(['/usr/sbin/smartctl','-a','-j','-n','standby','/dev/'.$device],range(0,255));
$v=json_decode($raw,true,512,JSON_THROW_ON_ERROR);
$out=['source'=>'smartctl_json','disk'=>$name,'device'=>$device];
foreach(['smartctl','smart_status','temperature','power_on_time','ata_smart_attributes','nvme_smart_health_information_log','ata_smart_self_test_log'] as $k)if(isset($v[$k]))$out[$k]=$v[$k];
return $out;
}
throw new RuntimeException('Unknown diagnostic action');
}
if(realpath($_SERVER['SCRIPT_FILENAME']??'')===__FILE__){
try{
$mode=$argv[1]??'';$x=json_decode($argv[2]??'{}',true,512,JSON_THROW_ON_ERROR);
$out=match($mode){'share-users'=>mua_users(),'share-rights'=>mua_share_rights(mua_name($x['name']??null)),'share-plan'=>mua_plan('share',$x),'docker-plan'=>mua_plan('docker',$x),'apply'=>mua_apply_plan($x),'diagnostics'=>mua_diagnostics($x),default=>throw new RuntimeException('Unknown admin action')};
echo json_encode($out,JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR),"\n";
}catch(Throwable $e){fwrite(STDERR,json_encode(['ok'=>false,'error'=>$e->getMessage()],JSON_INVALID_UTF8_SUBSTITUTE)."\n");exit(1);}
}