<?php
/*
disks.inc
part of FreeNAS (http://www.freenas.org)
Copyright (C) 2005-2008 Olivier Cochard-Labbe <olivier@freenas.org>.
All rights reserved.
Based on m0n0wall (http://m0n0.ch/wall)
Copyright (C) 2003-2006 Manuel Kasper <mk@neon1.net>.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
require_once("functions.inc");
// Mount all configured disks.
// Return 0 if successful, 1 if error
function disks_mount_all()
{
global $config, $g;
// For each device configured:
if (is_array($config['mounts']['mount'])) {
// Mount real disks first
foreach ($config['mounts']['mount'] as $mount) {
if ("disk" !== $mount['type'])
continue;
// Advanced unmount filesystem if not in booting mode (mount edition).
// Background: 'disks_umount' can't be used in the case the mount point
// has been renamed by the user because it uses the 'sharename' (which is
// now the new name of the share, but we need the old name) for unmounting.
if (!is_booting())
disks_umount_ex($mount);
disks_mount($mount);
}
// Then mount ISOs
foreach ($config['mounts']['mount'] as $mount) {
if ("iso" !== $mount['type'])
continue;
// Advanced unmount filesystem if not in booting mode (mount edition)
if (!is_booting())
disks_umount($mount);
disks_mount($mount);
}
}
return 0;
}
// This function unmounts all configured mountpoints
// Return 0 if successful, otherwise 1
function disks_umount_all()
{
global $config;
// Sync disks first
mwexec("/bin/sync");
if (is_array($config['mounts']['mount'])) {
foreach ($config['mounts']['mount'] as $mountent) {
disks_umount($mountent);
}
}
return 0;
}
// Mount using the configured mount given in parameter
// Return 0 if successful, 1 if error
function disks_mount($mount)
{
global $config, $g;
// Set PATH (otherwise ntfs won't be mounted via WebGUI)
putenv("PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin");
// Set mount name
$mountname = "/mnt/{$mount['sharename']}";
// Changing the PHP file creation mask to 0777
$oldumask = umask(0);
// Create one directory for each device under /mnt
if (! @mkdir($mountname, 0777)) {
write_log("Error: Can't create directory {$mountname} in disks_mount().");
}
// Restoring PHP file creation mask to old value
umask($oldumask);
// Check
if ($oldumask != umask()) {
write_log("Error: Failed to change back umask in disks_mount().");
}
/* Mount the filesystem */
/* In booting mode, skip encrypted disk (need to enter the passphrase on the webgui) */
if (is_booting()) {
// If mdisk is in the form "/dev/ad1.eli", then it's an encrypted disk :
if(stristr($mount['mdisk'], '.eli') === TRUE) {
write_log("Skip mounting '{$mount['sharename']}': Passphrase needed for '{$mountname}'.");
return 0;
}
}
switch($mount['type']) {
case "disk":
$devicespecialfile = $mount['devicespecialfile'];
break;
case "iso":
// Create memory disk. 'mdconfig' returns the ID of this disk
exec("/sbin/mdconfig -a -t vnode -f '{$mount['filename']}'", $mdid, $result);
if (0 !== $result) {
write_log("Error: Failed to create memory disk for '{$mount['filename']}'");
return 1;
}
$devicespecialfile = "/dev/{$mdid[0]}";
break;
}
/* Check if filesystem should be mounted read-only */
$readonly = (isset($mount['readonly'])) ? "-r" : "";
/* Check the fileystem only if there is a problem. */
/* This part is too stupid: I must read the FreeBSD start script for use the same intelligent method for checking hard drive */
switch ($mount['fstype']) {
case "ufs":
$result = mwexec("/sbin/mount -t ufs -o acls {$readonly} {$devicespecialfile} '{$mountname}'");
if (0 == $result) {
write_log("Device {$devicespecialfile} mounted using UFS on '{$mountname}'");
$result = 0;
} else {
@rmdir($mountname);
write_log("Error: Failed to mount {$devicespecialfile} using UFS");
$result = 1;
}
break;
case "msdosfs":
$result = mwexec("/sbin/mount -t msdosfs -o -u=ftp,-g=ftp,-m=777 {$readonly} {$devicespecialfile} '{$mountname}'");
if (0 == $result) {
write_log("Device {$devicespecialfile} mounted using FAT on '{$mountname}'");
$result = 0;
} else {
@rmdir($mountname);
write_log("Error: Failed to mount {$devicespecialfile} using FAT");
$result = 1;
}
break;
case "cd9660":
$result = mwexec("/sbin/mount -t cd9660 {$devicespecialfile} '{$mountname}'");
if (0 == $result) {
write_log("Device {$devicespecialfile} mounted as CD/DVD on '{$mountname}'");
$result = 0;
} else {
@rmdir($mountname);
write_log("Error: Failed to mount {$devicespecialfile} as CD/DVD");
$result = 1;
}
break;
case "ntfs":
// Load the kernel FUSE module
mwexec("/sbin/kldload /boot/kernel/fuse.ko");
$result = mwexec("/sbin/mount -t ntfs-3g -o force {$readonly} {$devicespecialfile} '{$mountname}'"); // default options: silent,allow_other
if (0 == $result) {
write_log("Disk {$devicespecialfile} mounted using NTFS on '{$mountname}'");
$result = 0;
} else {
@rmdir($mountname);
write_log("Error: Failed to mount {$devicespecialfile} using NTFS");
$result = 1;
}
break;
case "ext2fs":
$result = mwexec("/sbin/mount -t ext2fs {$readonly} {$devicespecialfile} '{$mountname}'");
if (0 == $result) {
write_log("Disk {$devicespecialfile} mounted using EXT2 on '{$mountname}'");
$result = 0;
} else {
@rmdir("{$mountname}");
write_log("Error: Failed to mount {$devicespecialfile} using EXT2");
$result = 1;
}
break;
}
// Modify directory mode to 0777. Check if target directory is writable,
// otherwise we will get an error message.
// For ISO's this may be 'chmod: /mnt/xxx: Read-only file system)'
if (file_exists($mountname) && is_writable($mountname)) {
if (!@chmod($mountname, 0777)) {
write_log("Error: Can't reset mode 0777 on directory {$mountname}");
}
}
return $result;
}
// Unmount the specified configured mount point.
// Return 0 is successfull, 1 if error
function disks_umount($mount)
{
// Get memory disk unit for ISOs
if ("iso" === $mount['type']) {
// Get current mount list
$amountlist = get_mounts_list();
foreach ($amountlist as $amountk => $amountv) {
if (0 == strcmp($amountv['sharename'], $mount['sharename'])) {
// Extract memory disk unit id
preg_match("/^\/dev\/md(\d+)$/", $amountv['devicespecialfile'], $matches);
$mdunit = $matches[1];
break;
}
}
}
// Unmount mount point
$mountname = "/mnt/{$mount['sharename']}";
if (mwexec("/sbin/umount -f '{$mountname}'") == 0) {
if(@rmdir("{$mountname}")) {
write_log("Successfully unmounted '{$mountname}'");
$result = 0;
} else {
write_log("Error: Failed to unmount '{$mountname}'");
$result = 1;
}
} else {
write_log("Error: Failed to unmount '{$mountname}'");
$result = 1;
}
// Detach memory disk for ISOs
if (0 == $result && "iso" === $mount['type']) {
$result = mwexec("/sbin/mdconfig -d -u {$mdunit}");
}
return $result;
}
// Advanced unmount the specified mount point without using the sharename,
// e.g. used when the 'sharename' has been modified/changed. Use the device
// special file (e.g. /dev/ad1p1) instead.
// Return 0 if successful, 1 if error
function disks_umount_ex($mount)
{
// Get current mount list
$amountlist = get_mounts_list();
foreach ($amountlist as $amountk => $amountv) {
if (0 == strcmp($amountv['devicespecialfile'], $mount['devicespecialfile'])) {
$mountname = $amountv['mp'];
break;
}
}
if ($mountname) {
if (mwexec("/sbin/umount -f '{$mountname}'") == 0) {
if(@rmdir("{$mountname}")) {
write_log("Successfully unmounted '{$mountname}'");
$result = 0;
} else {
write_log("Error: Failed to unmount '{$mountname}'");
$result = 1;
}
} else {
write_log("Error: Failed to unmount '{$mountname}'");
$result = 1;
}
}
return $result;
}
// Check if mount point is mounted.
// $mount - Mount point config array
// Return 0 if not mounted, otherwise 1
function disks_ismounted($mount)
{
// MUST CHECK IF IT'S NTFS filesystem
if (0 == strcmp($mount['fstype'],"ntfs")) {
return disks_ismounted_ex($mount['sharename'], "sharename");
} else {
return disks_ismounted_ex($mount['devicespecialfile'], "devicespecialfile");
}
}
// Check if mountpoint is mounted.
// $var - The attribute value to search for
// $key - The attribute name to search for
// e.g.: disks_ismounted_ex("/dev/ad0s1","devicespecialfile");
// disks_ismounted_ex("data","sharename");
// disks_ismounted_ex("ad0","mdisk");
// Return 0 if not mounted, otherwise 1
function disks_ismounted_ex($var,$key)
{
$result = 0;
// Get current mount list
$amountlist = get_mounts_list();
foreach ($amountlist as $amountk => $amountv) {
switch ($key) {
case "mdisk":
case "devicespecialfile":
// Must find the $val (e.g. ad0) in 'mdisk' (e.g. ad0s1).
// Must find the $val (e.g. /dev/ad1) in 'devicespecialfile' (e.g. /dev/ad1s1).
if (false !== strstr($amountv[$key], $var)) {
$result = 1;
break;
}
break;
default:
if (0 == strcmp($amountv[$key], $var)) {
$result = 1;
break;
}
break;
}
}
return $result;
}
// Configure, create and start gvinum volume.
// $name - Name of the gvinum disk to be configured.
// Return 0 if successful, 1 if error
function disks_raid_gvinum_configure($name)
{
global $g, $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index) {
write_console("Error: Disk name not found in disks_raid_gvinum_configure().\n");
return 1;
}
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk)) {
write_console("Error: Not an array in disks_raid_gvinum_configure().\n");
return 1;
}
// Generate the raid.conf file
$fd = fopen("{$g['varetc_path']}/raid-{$vdisk['name']}.conf", "w");
if (!$fd) {
write_console("Error: Failed to open raid.conf in disks_raid_gvinum_configure().\n");
return 1;
}
$raidconf="";
foreach ($vdisk['device'] as $devicek => $devicev) {
$raidconf .= <<<EOD
drive disk_{$devicev} device {$devicev}
EOD;
}
$raidconf .= <<<EOD
volume {$vdisk['name']}
EOD;
switch ($vdisk['type']) {
case "0":
$raidconf .= <<<EOD
plex org striped 256k
EOD;
foreach ($vdisk['device'] as $devicek => $devicev) {
/* Get the disksize */
$diskinfo=disks_get_diskinfo($devicev);
/* $raidconf .= <<<EOD
sd length {$diskinfo['mediasize_mbytes']}M drive disk_{$devicev}
EOD; */
$raidconf .= <<<EOD
sd length 0 drive disk_{$devicev}
EOD;
}
break;
case "1":
foreach ($vdisk['device'] as $devicek => $devicev) {
$raidconf .= <<<EOD
plex org concat
EOD;
/* Get the disksize */
$diskinfo=disks_get_diskinfo($devicev);
/* $raidconf .= <<<EOD
sd length {$diskinfo['mediasize_mbytes']}M drive disk_{$devicev}
EOD; */
$raidconf .= <<<EOD
sd length 0 drive disk_{$devicev}
EOD;
}
break;
case "5":
$raidconf .= <<<EOD
plex org raid5 256k
EOD;
foreach ($vdisk['device'] as $devicek => $devicev) {
/* Get the disksize */
$diskinfo=disks_get_diskinfo($devicev);
/* $raidconf .= <<<EOD
sd length {$diskinfo['mediasize_mbytes']}M drive disk_{$devicev}
EOD; */
$raidconf .= <<<EOD
sd length 0 drive disk_{$devicev}
EOD;
}
break;
}
fwrite($fd, $raidconf);
fclose($fd);
// Create volume
mwexec("/sbin/gvinum create {$g['varetc_path']}/raid-{$vdisk['name']}.conf");
// Start volume
mwexec("/sbin/gvinum start {$vdisk['name']}");
return 0;
}
// Configure, create and start gmirror volume.
// $name - Name of the RAID to be configured.
// Return 0 if successful, 1 if error
function disks_raid_gmirror_configure($name)
{
global $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index)
return 1;
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk))
return 1;
// Load kernel module
mwexec("/sbin/gmirror load");
// Create volume
$cmd = "/sbin/gmirror label -b {$vdisk['balance']} {$vdisk['name']} ";
foreach ($vdisk['device'] as $devicek => $devicev) {
$cmd .= "{$devicev} ";
}
return mwexec($cmd);
}
// Configure, create and start gconcat volume.
// $name - Name of the RAID to be configured.
// Return 0 if successful, 1 if error
function disks_raid_gconcat_configure($name)
{
global $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index)
return 1;
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk))
return 1;
// Load kernel module
mwexec("/sbin/gconcat load");
// Create volume
$cmd = "/sbin/gconcat label {$vdisk['name']} ";
foreach ($vdisk['device'] as $devicek => $devicev) {
$cmd .= "{$devicev} ";
}
return mwexec($cmd);
}
// Configure, create and start gstripe volume.
// $name - Name of the RAID to be configured.
// Return 0 if successful, 1 if error
function disks_raid_gstripe_configure($name)
{
global $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index)
return 1;
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk))
return 1;
// Load kernel module
mwexec("/sbin/gstripe load");
// Create volume
$cmd = "/sbin/gstripe label {$vdisk['name']} ";
foreach ($vdisk['device'] as $devicek => $devicev) {
$cmd .= "{$devicev} ";
}
return mwexec($cmd);
}
// Configure, create and start graid5 volume.
// $name - Name of the RAID to be configured.
// Return 0 if successful, 1 if error
function disks_raid_graid5_configure($name)
{
global $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index)
return 1;
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk))
return 1;
// Load kernel module
mwexec("/sbin/graid5 load");
// Tune system
disks_raid_graid5_tune();
// Create volume
$cmd = "/sbin/graid5 label -s 131072 {$vdisk['name']} ";
foreach ($vdisk['device'] as $devicek => $devicev) {
$cmd .= "{$devicev} ";
}
return mwexec($cmd);
}
// Start all geom RAID volumes.
// Return 0 if successful, 1 if error
function disks_raid_start()
{
disks_raid_gvinum_start();
disks_raid_gmirror_start();
disks_raid_gstripe_start();
disks_raid_gconcat_start();
disks_raid_graid5_start();
return 0;
}
// Start geom vinum volumes.
// Return 0 if successful, 1 if error
function disks_raid_gvinum_start()
{
global $config;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "gvinum"); {
/* Start each gvinum volume */
mwexec("/sbin/gvinum start {$vdiskv['name']}");
}
}
}
return 0;
}
// Start geom mirror volumes.
// Return 0 if successful, 1 if error
function disks_raid_gmirror_start()
{
global $config;
$found=0;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "gmirror"); {
$found=1;
break;
}
}
if ($found) {
mwexec("/sbin/gmirror load");
}
}
return 0;
}
// Start geom concat volumes.
// Return 0 if successful, 1 if error
function disks_raid_gconcat_start()
{
global $config;
$found=0;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "gconcat"); {
$found=1;
break;
}
}
if ($found) {
mwexec("/sbin/gconcat load");
}
}
return 0;
}
// Start geom stripe volumes.
// Return 0 if successful, 1 if error
function disks_raid_gstripe_start()
{
global $config;
$found=0;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "gstripe"); {
$found=1;
break;
}
}
if ($found) {
mwexec("/sbin/gstripe load");
}
}
return 0;
}
// Start geom raid5 volumes.
// Return 0 if successful, 1 if error
function disks_raid_graid5_start()
{
global $config;
$found=0;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "graid5"); {
$found=1;
break;
}
}
if ($found) {
mwexec("/sbin/graid5 load");
//Tune graid5
disks_raid_graid5_tune();
}
}
return 0;
}
// Optimize geom raid5 RAM usage
// Return none
function disks_raid_graid5_tune()
{
/* Get RAM information */
$raminfo = system_get_ram_info();
/* Calculate real RAM in MB */
$realram = round($raminfo['real'] / 1024 / 1024);
if ($realram <= 128) {
write_log("Optimizing graid5 for systems with <= 128MB of RAM");
mwexec('sysctl value kern.geom.raid5.maxwql=10');
mwexec('sysctl value kern.geom.raid5.maxmem=1100000');
} else if ($realram <= 256) {
write_log("Optimizing graid5 for systems with <= 256MB of RAM");
mwexec('sysctl value kern.geom.raid5.maxwql=20');
mwexec('sysctl value kern.geom.raid5.maxmem=2000000');
} else {
write_log("Detected >= 512MB of RAM... No need to optimize RAM usage for graid5");
}
// Modify ATA timeout to 15 seconds
mwexec('sysctl hw.ata.to=15');
}
// Stop all geom RAID volumes.
// Return 0 if successful, 1 if error
function disks_raid_stop()
{
disks_raid_gvinum_stop();
disks_raid_graid5_stop();
disks_raid_gstripe_stop();
disks_raid_gconcat_stop();
disks_raid_gmirror_stop();
return 0;
}
// Stop all geom gvinum volumes.
// Return 0 if successful, 1 if error
function disks_raid_gvinum_stop()
{
global $config;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "gvinum"); {
mwexec("/sbin/gvinum stop {$vdiskv['name']}");
}
}
}
return 0;
}
// Stop all geom mirror volumes.
// Return 0 if successful, 1 if error
function disks_raid_gmirror_stop()
{
global $config;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "gmirror"); {
mwexec("/sbin/gmirror stop {$vdiskv['name']}");
}
}
}
return 0;
}
// Stop all geom concat volumes.
// Return 0 if successful, 1 if error
function disks_raid_gconcat_stop()
{
global $config;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "gconcat"); {
mwexec("/sbin/gconcat stop {$vdiskv['name']}");
}
}
}
return 0;
}
// Stop all geom stripe volumes.
// Return 0 if successful, 1 if error
function disks_raid_gstripe_stop()
{
global $config;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "gstripe"); {
mwexec("/sbin/gstripe stop {$vdiskv['name']}");
}
}
}
return 0;
}
// Stop all geom raid5 volumes.
// Return 0 if successful, 1 if error
function disks_raid_graid5_stop()
{
global $config;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "graid5"); {
mwexec("/sbin/graid5 stop {$vdiskv['name']}");
}
}
}
return 0;
}
// Delete geom gvinum volume given in parameter.
// $name - Name of the RAID to be deleted.
// Return 0 if successful, 1 if error
function disks_raid_gvinum_delete($name)
{
global $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index)
return 1;
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk))
return 1;
exec("/sbin/gvinum lv {$name}", $rawdata);
if (strpos($rawdata[0],"State: up") === false) {
return 0;
}
mwexec("/sbin/gvinum rm -r {$name}");
foreach ($vdisk['device'] as $device){
mwexec("/sbin/gvinum rm -r disk_{$device}");
}
return 0;
}
// Delete geom mirror volume given in parameter.
// $name - Name of the RAID to be deleted.
// Return 0 if successful, 1 if error
function disks_raid_gmirror_delete($name)
{
global $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index)
return 1;
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk))
return 1;
// Stop the volume
mwexec("/sbin/gmirror stop {$name}");
// Clear the gmirror information on the hard drive
foreach ($vdisk['device'] as $device) {
mwexec("/sbin/gmirror clear {$device}");
}
return 0;
}
// Delete geom concat volume given in parameter.
// $name - Name of the RAID to be deleted.
// Return 0 if successful, 1 if error
function disks_raid_gconcat_delete($name)
{
global $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index)
return 1;
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk))
return 1;
// Stop the volume
mwexec("/sbin/gconcat stop {$name}");
// Clear the gconcat information on the hard drive
foreach ($vdisk['device'] as $device) {
mwexec("/sbin/gconcat clear {$device}");
}
mwexec("/sbin/gconcat destroy {$name}");
return 0;
}
// Delete geom stripe volume given in parameter.
// $name - Name of the RAID to be deleted.
// Return 0 if successful, 1 if error
function disks_raid_gstripe_delete($name)
{
global $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index)
return 1;
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk))
return 1;
// Stop the volume
mwexec("/sbin/gstripe stop {$name}");
// Clear the gconcat information on the hard drive
foreach ($vdisk['device'] as $device) {
mwexec("/sbin/gstripe clear {$device}");
}
mwexec("/sbin/gstripe destroy {$name}");
return 0;
}
// Delete geom raid5 volume given in parameter.
// $name - Name of the RAID to be deleted.
// Return 0 if successful, 1 if error
function disks_raid_graid5_delete($name)
{
global $config;
if (!is_array($config['disks']['disk']))
return 1;
$index = array_search_ex($name, $config['disks']['disk'], "name");
if (false === $index)
return 1;
$vdisk = $config['disks']['disk'][$index];
if (!is_array($vdisk))
return 1;
// Stop the volume
// Arne Woerner advice: Don't stop the volume before deleting it.
// mwexec("/sbin/graid5 stop {$name}");
// Clear the graid5 information on the hard drive
foreach ($vdisk['device'] as $device){
// Get the name of the provider
$id = array_search_ex($device, $config['disks']['disk'], "devicespecialfile");
$provider = $config['disks']['disk'][$id]['name'];
// Remove provider
mwexec("/sbin/graid5 remove {$name} {$provider}");
}
mwexec("/sbin/graid5 destroy {$name}");
return 0;
}
// Initialize provider which needs to be encrypted.
// Return 0 if successful, 1 if error
function disks_geli_init($provider, $aalgo, $ealgo, $passphrase, $verbose = false)
{
$param = "-t";
$result = 1;
// Add additional parameters
if (true == $verbose) $param .= " -v";
if (0 !== strcmp($aalgo,"none")) $param .= " -a {$aalgo}";
if (!empty($ealgo)) $param .= " -e {$ealgo}";
// Init disk
system("(/bin/echo {$passphrase}; /bin/echo {$passphrase}) | /sbin/geli init {$param} {$provider} 2>&1", $result);
return $result;
}
// Attach the given provider. The master key will be decrypted
// using the given passphrase/keyfile and a new GEOM provider
// will be created using the given provider's name with an ".eli"
// suffix.
// Return 0 if successful, 1 if error
function disks_geli_attach($provider, $passphrase, $verbose = false)
{
$param = "-t";
$result = 1;
// Add additional parameters
if (true == $verbose) $param .= " -v";
// Attach disk
system("(/bin/echo {$passphrase}; /bin/echo {$passphrase}) | /sbin/geli attach {$param} {$provider} 2>&1", $result);
return $result;
}
// Detach the given providers, which means remove the devfs entry
// and clear the keys from memory.
// Return 0 if successful, 1 if error
function disks_geli_detach($provider, $verbose = false)
{
if (true == $verbose)
$result = system("/sbin/geli detach {$provider} 2>&1", $result);
else
$result = mwexec("/sbin/geli detach {$provider}");
return $result;
}
// Kill (destroy) a geli encrypted volume.
// Return 0 if successful, 1 if error
function disks_geli_kill($provider)
{
$result = mwexec("/sbin/geli kill {$provider}");
return $result;
}
// Detach all geli encrypted disks.
// Return 0 if successful, 1 if error
function disks_geli_detach_all()
{
global $config;
$result = 0;
if (is_array($config['disks']['disk'])) {
foreach ($config['disks']['disk'] as $vdiskv) {
if ($vdiskv['class'] == "geli"); {
$result |= disks_geli_detach($vdiskv['devicespecialfile']) ;
}
}
}
return $result;
}
// Change or setup (if not yet initialized) selected key.
// The passphrase can always be changed: for an attached provider and
// a detached provider. When a provider is attached, the user does not
// have to provide an old passphrase.
// provider: Name of the provider, e.g. da0, ad3, ...
// oldpassphrase: Old passphrase
// passphrase: New passphrase
// verbose: Display additional information
// Return 0 if successful, 1 if error
function disks_geli_setkey($provider, $oldpassphrase, $passphrase, $verbose = false)
{
$param = "-t";
$result = 1;
// Add additional parameters
if (true == $verbose) $param .= " -v";
if (0 == disks_exists("/dev/{$provider}.eli")) {
// Provider is already attached
system("(/bin/echo {$passphrase}; /bin/echo {$passphrase}) | /sbin/geli setkey {$param} {$provider} 2>&1", $result);
} else {
// Provider has not already been attached
system("(/bin/echo {$oldpassphrase}; /bin/echo {$passphrase}; /bin/echo {$passphrase}) | /sbin/geli setkey {$param} {$provider} 2>&1", $result);
}
return $result;
}
// Format disk. Error and warning messages are redirected to stdout.
// Return none
function disks_format($disk, $type, $notinitmbr, $minspace, $volumelabel)
{
global $g;
if (!$notinitmbr) {
echo gettext("Erasing MBR and all partitions").".\n";
system("/bin/dd if=/dev/zero of={$disk} bs=32k count=640");
}
switch ($type) {
case "ufsgpt":
// Create GPT partition table
echo gettext("Creating partition").":\n";
system("/sbin/gpt destroy {$disk} 1>/dev/null 2>&1"); // Destroy old GTP partition
system("/sbin/gpt create -f {$disk} 2>&1");
system("/sbin/gpt add -t ufs {$disk} 2>&1");
// Create filesystem
echo gettext("Creating filesystem with 'Soft Updates'").":\n";
$param = "-U";
if (!empty($volumelabel))
$param .= " -L " . escapeshellarg($volumelabel);
if (!empty($minspace))
$param .= " -m {$minspace}";
system("/sbin/newfs {$param} {$disk}p1 2>&1");
break;
case "pool":
// Initialize disk
echo gettext("Formating disk").".\n";
system("/bin/dd if=/dev/zero of={$disk} bs=1m count=16");
break;
case "msdos":
// Get disk information
$diskinfo = disks_get_diskinfo($disk);
// Get valid CHS information. 'diskinfo' gets values from harddisk firmware that
// are maybe unusable by 'fdisk' (e.g. sectors = 255, fdisk requires <= 63).
disk_sanitize_bios_geom($diskinfo);
// Create fdisk config file (fdisk.conf)
if (1 == disks_create_fdisk_configfile(11, $diskinfo, "{$g['tmp_path']}/fdisk.conf")) {
echo("Error: Failed to create '{$g['tmp_path']}/fdisk.conf'.\n");
break;
}
// Initialize disk
echo gettext("Creating partition").":\n";
system("/sbin/fdisk -v -f {$g['tmp_path']}/fdisk.conf {$disk} 2>&1");
// Initialize the partition
echo gettext("Initializing partition").".\n";
system("/bin/dd if=/dev/zero of={$disk}s1 bs=32k count=16");
// Create filesystem
echo gettext("Creating filesystem").":\n";
$param = "-F 32";
if (!empty($volumelabel))
$param .= " -L " . escapeshellarg($volumelabel);
system("/sbin/newfs_msdos {$param} {$disk}s1 2>&1");
// Cleanup
@unlink("{$g['tmp_path']}/fdisk.conf");
break;
case "ext2":
// Get disk information
$diskinfo = disks_get_diskinfo($disk);
// Get valid CHS information. 'diskinfo' gets values from harddisk firmware that
// are maybe unusable by 'fdisk' (e.g. sectors = 255, fdisk requires <= 63).
disk_sanitize_bios_geom($diskinfo);
// Create fdisk config file (fdisk.conf)
if (1 == disks_create_fdisk_configfile(131, $diskinfo, "{$g['tmp_path']}/fdisk.conf")) {
echo("Error: Failed to create '{$g['tmp_path']}/fdisk.conf'.\n");
break;
}
// Initialize disk
echo gettext("Creating partition").":\n";
system("/sbin/fdisk -v -f {$g['tmp_path']}/fdisk.conf {$disk} 2>&1");
// Initialize the partition
echo gettext("Initializing partition").".\n";
system("/bin/dd if=/dev/zero of={$disk}s1 bs=32k count=16");
// Create filesystem
echo gettext("Creating filesystem").":\n";
$param = "-r 0 "; // Use revision 0 when formating EXT2 filesystems, otherwise mount_ext2fs fails (mount point disapears)
if (!empty($volumelabel))
$param .= " -L " . escapeshellarg($volumelabel);
system("/usr/local/sbin/mke2fs {$param} {$disk}s1 2>&1");
// Cleanup
@unlink("{$g['tmp_path']}/fdisk.conf");
break;
}
echo gettext("Done")."!\n";
}
// File system consistency check and interactive repair.
// The filesystem type will be get from the mount configuration information.
// Parameter:
// device - Name of the device (e.g. /dev/ad1s1).
// umount - Unmount disk if necessary.
// Return 0 if successful, 1 if error
function disks_fsck($device,$umount = false)
{
global $config;
// Check if there exits any mounts
if(!is_array($config['mounts']['mount']))
return 1;
// Get the id of the disk
$id = array_search_ex($device, $config['mounts']['mount'], "devicespecialfile");
if (false === $id)
return 1;
// Get the mount configuration
$mount = $config['mounts']['mount'][$id];
// Check if disk is mounted
$ismounted = disks_ismounted($mount);
// Unmount disk temporarily if necessary
if($umount && $ismounted) {
echo("<strong class='red'>" . gettext("Note") . ":</strong> " . gettext("The disk is currently mounted! The mount point will be removed temporary to perform selected command.") . "<br><br>");
disks_umount($mount);
}
switch($mount['fstype']) {
case "cd9660":
case "ntfs":
break;
default:
system("/sbin/fsck -t {$mount['fstype']} -y -f " . escapeshellarg($device));
break;
}
// Remount disk again if necessary
if($umount && $ismounted) {
disks_mount($mount);
}
return 0;
}
// Get list of partition information from disk.
// $disk - Name of the disk (e.g. ad0)
// Result is in the form:
// [1] => Array
// (
// [start] => 31
// [size] => 409169
// [type] => 0xa5
// [flags] => 0x80
// )
//
// Called in disks_manage_tools.php
// Return array of partition info
function disks_get_partition_info($disk) {
exec("/sbin/fdisk -s {$disk}", $rawdata);
array_shift($rawdata);
array_shift($rawdata);
$result = array();
foreach($rawdata as $partinfo) {
$apartinfo = preg_split("/\s+/", $partinfo);
$partid = chop($apartinfo[1],":");
$result[$partid] = array();
$result[$partid]['start'] = chop($apartinfo[2]);
$result[$partid]['size'] = chop($apartinfo[3]);
$result[$partid]['type'] = chop($apartinfo[4]);
$result[$partid]['flags'] = chop($apartinfo[5]);
}
return $result;
}
// Get disk information.
// $disk - Name of the disk (e.g. ad0)
// Result is in the form:
// [1] => Array
// (
// [name] => ad0
// [sectorsize] => 512
// [mediasize_bytes] => 5242503168
// [mediasize_mbytes] => 4999
// [mediasize_sectors] => 10239264
// [cylinders] => 10158
// [heads] => 16
// [sectors] => 63
// )
// Return array containing diskinfo.
function disks_get_diskinfo($disk)
{
exec("/usr/sbin/diskinfo {$disk}", $rawdata);
$diskinfo = preg_split("/\s+/", $rawdata[0]);
$result = array();
$result[name] = chop($diskinfo[0]);
$result[sectorsize] = chop($diskinfo[1]);
$result[mediasize_bytes] = chop($diskinfo[2]);
$result[mediasize_mbytes] = ceil(chop($diskinfo[2]) / 1024 / 1024);
$result[mediasize_sectors] = chop($diskinfo[3]);
$result[cylinders] = chop($diskinfo[4]);
$result[heads] = chop($diskinfo[5]);
$result[sectors] = chop($diskinfo[6]);
return $result;
}
// Get cylinders/heads/sectors from disk.
// $info - Array containing CHS information.
// [1] => Array
// (
// [cylinders] => 10158
// [heads] => 16
// [sectors] => 63
// )
// Return 0 if successful, 1 if error.
function disks_get_chs_info($disk, &$info)
{
if (!is_array($info))
return 1;
exec("/sbin/fdisk -t {$disk}", $rawdata);
// Parse string: cylinders=77826 heads=255 sectors/track=63 (16065 blks/cyl)
if (0 == preg_match("/.+cylinders=(\d+) heads=(\d+) sectors\/track=(\d+) .+/", implode($rawdata), $chs))
return 1;
$info['cylinders'] = $chs[1];
$info['heads'] = $chs[2];
$info['sectors'] = $chs[3];
return 0;
}
// Check if given disk is available.
// $disk - e.g. /dev/ad4, /dev/ad2.eli
// Return 0 if yes, 1 if no.
function disks_exists($disk)
{
if (file_exists($disk)) {
return 0;
}
return 1;
}
// Wrapper to execute geom commands.
// $class - Name of geom class (e.g. stripe, mirror, vinum, raid5, ...)
// $command - Command to execute (e.g. list, status, load, activate, ...).
// The commands depend on the GEOM class.
// $param - The command parameter.
// $verbose - Display command results or hide them.
// $stderr - Redirect stderr to stdout to display error messages too.
// Return 0 if successful, 1 if error.
function disks_geom_cmd($class, $command, $param, $verbose = false, $stderr = true)
{
$result = 1;
if ("vinum" !== $class)
$cmd = "/sbin/geom {$class} {$command} {$param}";
else
$cmd = "/sbin/gvinum {$command} {$param}"; // gvinum can't be executed via geom
if (true === $verbose) {
if (true === $stderr)
$cmd .= " 2>&1"; // Redirect error message to stdout
system($cmd, $result);
} else {
$result = mwexec($cmd);
}
return $result;
}
// Calculate valid cylinders/heads/sectors.
// Code taken from FreeBSD kernel /src/lib/libdisk/change.c.
// $info [in|out] - Array containing CHS information.
// [1] => Array
// (
// [name] => ad0
// [sectorsize] => 512
// [mediasize_bytes] => 5242503168
// [mediasize_mbytes] => 4999
// [mediasize_sectors] => 10239264
// [cylinders] => 10158
// [heads] => 16
// [sectors] => 63
// )
// Return: None
function disk_sanitize_bios_geom(&$info) {
$sane = 1;
if ($info['cylinders'] > 1024)
$sane = 0;
if ($info['heads'] > 16)
$sane = 0;
if ($info['sectors'] > 63)
$sane = 0;
if ($info['cylinders'] * $info['heads'] * $info['sectors'] != $info['mediasize_sectors'])
$sane = 0;
if (0 != $sane)
return;
// First try something that IDE can handle
$info['sectors'] = 63;
$info['heads'] = 16;
$info['cylinders'] = intval($info['mediasize_sectors'] / ($info['sectors'] * $info['heads']));
if ($info['cylinders'] < 1024)
return;
// Hmm, try harder...
// Assume standard SCSI parameter
$info['heads'] = 255;
$info['cylinders'] = intval($info['mediasize_sectors'] / ($info['sectors'] * $info['heads']));
}
// Create fdisk configuration file.
// $type - File system identified (131 for EXT2, 11 for MSDOS)
// $diskinfo - Array
// (
// [name] => ad0
// [sectorsize] => 512
// [mediasize_bytes] => 5242503168
// [mediasize_mbytes] => 4999
// [mediasize_sectors] => 10239264
// [cylinders] => 10158
// [heads] => 16
// [sectors] => 63
// )
// $file - Filename of fdisk configuration file.
// Return 0 if successful, 1 if error.
function disks_create_fdisk_configfile($type, $diskinfo, $file) {
global $g;
if (!is_array($diskinfo))
return 1;
$fdiskconf .= <<<EOD
g c{$diskinfo['cylinders']} h{$diskinfo['heads']} s{$diskinfo['sectors']}
p 1 {$type} {$diskinfo['sectors']} {$diskinfo['mediasize_sectors']}
p 2 0 0 0
p 3 0 0 0
p 4 0 0 0
a 1
EOD;
if (false === file_put_contents($file, $fdiskconf)) {
write_log("Error: Failed to create '{$file}'.");
return 1;
}
return 0;
}
?>