Skip to content
Snippets Groups Projects
Commit 7dd5b9bc authored by Martin Suefke's avatar Martin Suefke
Browse files

Reorganized Ubuntu Customization Kit stuff into UbuntuCustomizationKit

Also: split 32/64 bit Ubuntu customization kit in order to have iso_description separate.
Warning: Symlinking files in th customization-scripts-folder will stop UCK from working
parent 55cc4f59
No related branches found
No related tags found
No related merge requests found
Showing
with 827 additions and 1560 deletions
de
en
en
de
en
#!/bin/sh
PREREQ=""
DESCRIPTION="Enforcing MoPS disconnect"
prereqs()
{
echo "$PREREQ"
}
case $1 in
# get pre-requisites
prereqs)
prereqs
exit 0
;;
esac
. /scripts/casper-functions
load_confmodule
log_begin_msg "$DESCRIPTION"
# Starting nmtelekinese with the MoPS network
cp /nm/nmtelekinese.py /root/usr/bin/
chroot /root mkdir -m 755 -p /home/${USERNAME}/.config/autostart
cp /nm/nmtelekinese.desktop /root/home/${USERNAME}/.config/autostart
chroot /root chmod 755 /home/${USERNAME}/.config/autostart/nmtelekinese.desktop
chroot /root chown -R ${USERNAME}:${USERNAME} /home/${USERNAME}/.config
# Denying all connections to redirector.wlan.rwth-aachen.de
mount -t proc none /root/proc
chroot /root modprobe ip_tables
chroot /root modprobe iptable_filter
chroot /root modprobe ipt_REJECT
chroot /root iptables -I OUTPUT 1 -d 137.226.8.34 -j REJECT --reject-with icmp-host-prohibited
chroot /root iptables -I OUTPUT 1 -d 137.226.8.34 -p tcp -j REJECT --reject-with tcp-rst
umount /root/proc
log_end_msg
/scripts/casper-bottom/01integrity_check
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/05mountpoints
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/05mountpoints_lupin
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/07remove_oem_config
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/10custom_installation
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/10ntfs_3g
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/12fstab
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/13swap
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/14locales
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/15autologin
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/18hostname
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/19keyboard
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/20xconfig
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/22gnome_panel_data
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/22screensaver
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/22serialtty
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/22sslcert
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/23etc_modules
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/23networking
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/24preseed
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/25adduser
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/25configure_init
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/26disable_user_menu
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/26mopsmops
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/30accessibility
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/31disable_update_notifier
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/32disable_hibernation
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/33enable_apport_crashes
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/34disable_kde_services
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/35fix_language_selector
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/36disable_trackerd
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/40install_driver_updates
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/41apt_cdrom
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/43disable_updateinitramfs
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/44pk_allow_ubuntu
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/45jackd2
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/48kubuntu_disable_restart_notifications
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/49kubuntu_mobile_session
[ -e /conf/param.conf ] && . /conf/param.conf
/scripts/casper-bottom/50ubiquity-bluetooth-agent
[ -e /conf/param.conf ] && . /conf/param.conf
[Desktop Entry]
Type=Application
Exec=/usr/bin/python /usr/bin/nmtelekinese.py 134.61.32.0/21
Hidden=false
NoDisplay=false
X-GNOME-Autostart-enabled=true
Name[de_DE]=NM Telekinese
Name=NM Telekinese
Comment[de_DE]=Verdindert das Verbinden zu gefärlichen Netzwerken
Comment=Verdindert das Verbinden zu gefärlichen Netzwerken
#! /usr/bin/python
# -*- coding: UTF-8 -*-
"""
Network Manager Telekinesis - Interdicts connections to unwanted networks
This program controls NetworkManager via DBUS
in order to prevent it from connecting to certain networks.
(Copyleft) 2012 Mmoebius/ALUG
License: GPLv3 http://www.gnu.org/licenses/gpl.html
Version 1.0a - Fragt nicht nach dem Abschalten des Mops-Netz-Killers
"""
###
### Configuration
###
#now: Cmdline Parameter
#IPv4unwanted = [
# '134.61.32.0/21' # MoPS range
#]
IPv4unwantedRng=[]
DoDisableUnwanted=True # set to false to stop turning off the network
###
### /Configuration
###
SessionBusListener=None # gets set if waiting for the user to dismiss the action
from pprint import pformat,pprint
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
import dbus, sys
from time import sleep
# Need a Mainloop for signals
from dbus.mainloop.glib import DBusGMainLoop
import gobject
DBusGMainLoop(set_as_default=True)
# Need struct for network byte order handling
from struct import pack,unpack
#Parse comdline options
import argparse
parser = argparse.ArgumentParser(description='Control NetworkManager to stay off some networks')
parser.add_argument('ipranges', metavar='IPv4range', type=str, nargs='+',
help='IPv4 range/mask to disconnect automatically. e.g. "10.11.12.0/24"')
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
help='Set debug level to DEBUG (default INFO)')
parser.description="""Network Manager Telekinesis - Interdicts connections to unwanted networks"""
parser.epilog="""(Copyleft) 2012 Mmoebius/ALUG
License: GPLv3 http://www.gnu.org/licenses/gpl.html"""
args = parser.parse_args()
if args.verbose:
logger.level=logging.DEBUG
logger.debug('Verbose debug messages')
IPv4unwanted=args.ipranges
NMdevtype = { 1: "Ethernet",
2: "Wi-Fi",
5: "Bluetooth",
6: "OLPC",
7: "WiMAX",
8: "Modem",
9: "InfiniBand",
10: "Bond",
11: "VLAN",
12: "ADSL" }
NMstate = { 0: "Unknown",
10: "Unmanaged",
20: "Unavailable",
30: "Disconnected",
40: "Prepare",
50: "Config",
60: "Need Auth",
70: "IP Config",
80: "IP Check",
90: "Secondaries",
100: "Activated",
110: "Deactivating",
120: "Failed" }
bus = dbus.SystemBus()
# Get a proxy for the base NetworkManager object
proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
manager = dbus.Interface(proxy, "org.freedesktop.NetworkManager")
def handle_Carrier(sender=None,**kwargs):
logger.debug("handle_Carrier from %s with %s",sender,pformat(kwargs))
def handle_PropertiesChanged(sender=None,**kwargs):
logger.debug("handle_PropertiesChanged from %s with %s",sender,pformat(kwargs))
def getProp(oPath,propIface,propName):
"""Gets a 'org.freedesktop.DBus.Properties' from any interface on any object path 'org.freedesktop.NetworkManager' serves """
proxy = bus.get_object("org.freedesktop.NetworkManager", oPath)
proxy_if = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
props = proxy_if.Get(propIface, propName)
return props
def getAllProps(oPath,propIface):
"""Gets all 'org.freedesktop.DBus.Properties' from any interface on any object path 'org.freedesktop.NetworkManager' serves """
proxy = bus.get_object("org.freedesktop.NetworkManager", oPath)
proxy_if = dbus.Interface(proxy, "org.freedesktop.DBus.Properties")
props = proxy_if.GetAll(propIface)
return props
#IP Address format conversions:
def IpDbus2Tuple(IpDbus):
return unpack('>BBBB',pack('>L',IpDbus)) #dbus order to tuple
def IpDbus2Int(IpDbus):
return unpack('=L',pack('>L',IpDbus))[0] #dbus order to and'able int
def IpInt2Tuple(IpInt):
return unpack('>BBBB',pack('=L',IpInt))
def IpStr2Tuple(IpStr):
return map(int,IpStr.split('.',3))
def IpTuple2String(IpTuple):
return ".".join(map(str,IpTuple[::-1]))
def IpTuple2Int(IpTuple):
ipa=0
for i in [0,1,2,3]:
ipa+=int(IpTuple[i])<<(24-8*i)
return ipa
def IpMaskStr2StrA(IpMaskStr):
return IpMaskStr.rsplit('/',1)
def IpStr2Tuple(IpStr):
tupl=map(int,IpStr.split('.',3))
for i in tupl:
if (0>i) or (255<i):
raise ValueError("Ip address quad not in range 0..255: %d"%i)
return tupl
def IpGetMasked(adr,mask):
# mask two IP addresses in 'int' - style. All host-specific bits cleared
return adr&(2**32-2**(32-mask)) #cutting at the right end
def IpGetAntiMasked(adr,mask):
# return all nonmasked bits set '1'. All host-specific bits set
return adr|(2**(32-mask)-1) #cutting at the right end
def handle_NotifyUserAction(replaces_id,ActionStrA):
global SessionBusListener
global DoDisableUnwanted
logger.debug('handle_NotifyUserAction: got %s %s',str(replaces_id),str(ActionStrA))
if 'Mops-off-wantMops' in ActionStrA:
DoDisableUnwanted=False
logger.warn('User stops disabling networks.')
def NotifyUser():
global SessionBusListener
global DoDisableUnwanted
sbus = dbus.SessionBus()
oNotifier = sbus.get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
iNotifier=dbus.Interface(oNotifier, "org.freedesktop.Notifications")
if SessionBusListener is None:
SessionBusListener = sbus.add_signal_receiver(handle_NotifyUserAction, signal_name="ActionInvoked",
dbus_interface="org.freedesktop.Notifications" )
logger.debug('Added Dbus listener for session bus: %s',str(SessionBusListener))
NotifyOptionsArray=[]
# Uncomment these 4 Lines if you want to be able to turn off disconnecting MoPS Networks
# if DoDisableUnwanted:
# NotifyOptionsArray=[
# 'Mops-off-Ok', 'Ok',
# 'Mops-off-wantMops','MoPS nicht mehr trennen'
# ]
sleep(3) # Wait until nm-dispatcher sends it smessage, do not overflood the NotifyOS, try not to get buried.
iNotifier.Notify(
"nmtelekinesis", # Applicateion Identifier
0, # replaces_id (hardcoded)
# Note: if replaces_id is 0, the return value is a UINT32 that represent the notification.
"network-error", # "notification-network-disconnected",
"Forced MoPS disconnect",
u"""Das MoPS Netzwerk ist während der Installation
unerwuenscht. Es wurde automatisch getrennt.
Bitte aktiviere das Eduroam-Netzwerk gemäß
Anleitung mit 802.1X Authentifikation.
Frage ein Installhelferhörnchen,
falls Du dabei Hilfe brauchst.""",
NotifyOptionsArray,
{}, #Application specific hint parameter
30000 # OSD Notifier will not take long times
)
def WarnUser():
sbus = dbus.SessionBus()
oNotifier = sbus.get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications")
iNotifier=dbus.Interface(oNotifier, "org.freedesktop.Notifications")
sleep(3)
iNotifier.Notify(
"nmtelekinesis", # Applicateion Identifier
0, # replaces_id (hardcoded)
# Note: if replaces_id is 0, the return value is a UINT32 that represent the notification.
"network", # "notification-network-disconnected",
"MoPS discovered",
u"""Das MoPS Netzwerk ist während der Installation
unerwuenscht. Du bist gewarnt.
Bitte aktiviere das Eduroam-Netzwerk gemäß
Anleitung mit 802.1X Authentifikation.
Frage ein Installhelferhörnchen,
falls Du dabei Hilfe brauchst.""",
[],
{}, #Application specific hint parameter
30000 # OSD Notifier will not take long times
)
def DisableAutoConnect(oConn):
"""Disable AutoConnect for the currently active setting object in oConn"""
try:
Psetting=getProp(oConn,"org.freedesktop.NetworkManager.Connection.Active",'Connection')
proxy = bus.get_object("org.freedesktop.NetworkManager", Psetting)
proxy_if = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Settings.Connection")
props = proxy_if.GetSettings() # read
logger.debug('DisableAutoConnect: Got settings %s',pformat(props))
props['connection']['autoconnect']=0 # modify
proxy_if.Update(props) # write. Simple.
except Exception as err:
logger.warn('Error setting Autocconnect false for %s: (%s)',oConn,str(err))
def DisconnectDevice(oPath, oConn):
global DoDisableUnwanted
if DoDisableUnwanted:
logger.debug('Disconnecting %s',str(oPath))
proxy = bus.get_object("org.freedesktop.NetworkManager", oPath)
proxy_if = dbus.Interface(proxy, "org.freedesktop.NetworkManager.Device")
# about to disconnect something.
# See if there is a setting that can be set to "autoconnect=false" along with this
DisableAutoConnect(oConn)
#result = "Demo-NoDisconnect"
result = "failed"
result = proxy_if.Disconnect()
logger.info('Disconnected %s result %s',str(oPath),result)
NotifyUser()
else:
WarnUser()
logger.info('Not disconnecting %s (DoDisableUnwanted is false)',str(oPath))
def ScanIp4Config2(oIp4Config, oDevice, oConn):
try:
Pip4 = getProp(oIp4Config,"org.freedesktop.NetworkManager.IP4Config",'Addresses')
except dbus.exceptions.DBusException:
logger.debug("ScanIp4Config2(oDevice %s, oIp4Config %s, oConn %s): no IP4Config",oIp4Config, oDevice, oConn)
return
CanDisconnect=False
for addr in Pip4:
logger.debug(
'IP Address: %s/%d gw:%s',
IpTuple2String(IpDbus2Tuple(addr[0])),
addr[1],
IpTuple2String(IpDbus2Tuple(addr[2]))
)
# check ip range against known unwanted range
ipa=IpDbus2Int(addr[0])
if (0>ipa) or (2**32<ipa):
logger.warn('IPv4 address exceeds range: %d',ipa)
return
for (iplo,iphi) in IPv4unwantedRng:
if (ipa>=iplo) and (ipa<=iphi):
logger.info('Detected ip in unwanted range: %s <= %s <= %s on %s',
IpTuple2String(IpInt2Tuple(iplo)),
IpTuple2String(IpInt2Tuple(ipa)),
IpTuple2String(IpInt2Tuple(iphi)),
str(oDevice)
)
CanDisconnect=True
if CanDisconnect:
DisconnectDevice(oDevice, oConn)
return CanDisconnect
def ScanActiveDevice2(adev,aconn):
logger.debug("Examining device: %s", str(adev))
# IPv4Config may not be available instantly
pDev = getAllProps(adev,"org.freedesktop.NetworkManager.Device")
logger.debug('dev props %s',pDev)
if pDev.has_key('Ip4Config'):
oIPv4=pDev['Ip4Config']
logger.debug('dev props ipv4config %s',oIPv4)
ScanIp4Config2(oIPv4,adev,aconn)
def ScanActiveConnections2(ActiveConnections):
"""Scans an array of connection objects for unwanted IP addresses"""
for aconn in ActiveConnections:
try:
logger.debug("Examining connection: %s", str(aconn))
# read props from the Active Connection
Pconn = getProp(aconn,"org.freedesktop.NetworkManager.Connection.Active",'Devices')
Pmaster = getProp(aconn,"org.freedesktop.NetworkManager.Connection.Active",'Master')
if str(Pmaster) in map(str,ActiveConnections):
logger.debug("connection: %s has a master device %s that is examined elsewhere. Stop.",
str(aconn),
str(Pmaster)
)
logger.debug("other location is %s in %s",sAconn,str(map(str,aconn)))
Pconn=[]
break
for adev in Pconn:
ScanActiveDevice2(adev,aconn)
except Exception as err:
logger.warn('Exception while examining connection %s: >>>%s<<<',
str(aconn),
str(err),
)
def handle_NmPropertiesChanged(sender=None,*args,**kwargs):
logger.debug("handle_NmPropertiesChanged with %s and %s and %s",str(sender),str(args),str(kwargs))
logger.debug("handle_NmPropertiesChanged keys %s",str(sender.keys()))
# check if new connection active
if sender.has_key('ActiveConnections'):
conn=sender['ActiveConnections']
logger.info("Scanning ActiveConnections: %s",str(conn))
ScanActiveConnections2(conn)
if sender.has_key('Ip4Config'):
ipv4cfg=sender['Ip4Config']
logger.info("Scanning Ip4Config: %s",str(ipv4cfg))
ScanIp4Config2(ipv4cfg)
if sender.has_key('State'):
try:
StateHint=NMstate[sender['State']]
except KeyError:
StateHint='<unknown>'
logger.debug('State Change to >>>%s<<< (%s)',str(sender['State']),StateHint)
def NmStateStr(iState):
try:
return NMstate[iState]
except KeyError:
return '<unknown>'
def handle_NmDeviceStateChanged(sNew,sOld,sReason,**kwargs):
logger.debug("handle_NmDeviceStateChanged with %s",str(kwargs))
logger.debug("handle_NmDeviceStateChanged %s (%d) -> %s (%d) Reason: %d",
NmStateStr(sOld), sOld, NmStateStr(sNew), sNew, sReason )
if kwargs.has_key('oPath'):
oPath=kwargs['oPath']
if 100 == sNew:
logger.info("Scanning Activated Device: %s",str(oPath))
# need aconn so scan.
oAConn=getProp(oPath,'org.freedesktop.NetworkManager.Device','ActiveConnection')
ScanActiveDevice2(oPath,oAConn)
#Device-Add is not yet required to be watch for
#def handle_addDevice(oDev,*args):
# logger.debug("handle_addDevice from %s with %s",str(oDev),str(args))
def ParseIPv4unwantedRng(IpStrList):
"""filling IPv4unwantedRng from IPv4unwanted"""
global IPv4unwantedRng
for s in IpStrList:
try:
logger.debug('Unwanted IP: parsing >>>%s<<<',s)
[ips,masks]=IpMaskStr2StrA(s)
mask=int(masks)
ip=IpTuple2Int(IpStr2Tuple(ips))
#logger.debug('Unwanted IP %s / %d',str(ip),mask)
if (0>mask) or (32<mask):
raise ValueError('Mask range 0..32 error')
if (0>ip) or (2**32<ip):
raise ValueError('ip range 0..2^32 error')
iplow=IpGetMasked(ip,mask)
iphigh=IpGetAntiMasked(ip,mask)
logger.info('Unwanted IP range %s - %s',IpTuple2String(IpInt2Tuple(iplow)),IpTuple2String(IpInt2Tuple(iphigh)))
IPv4unwantedRng.append((iplow,iphigh))
except ValueError as err:
logger.warn('That is not a valid ip/mask: >>>%s<<< (%s)',str(s),err.message)
logger.debug("Startup - preparing unwanted address ranges")
ParseIPv4unwantedRng(IPv4unwanted)
if len(IPv4unwantedRng)<1:
logger.warn('No unwanted IP range given. Quit.')
quit(1)
# Adding bus signal receivers
# See interface spec at http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#org.freedesktop.NetworkManager
# Chapter "Signal" -> defines "DeviceAdded" on the interface "org.freedesktop.NetworkManager"
#Device-Add is not yet required to be watch for
#bus.add_signal_receiver(handle_addDevice, signal_name="DeviceAdded",
# dbus_interface="org.freedesktop.NetworkManager" )
bus.add_signal_receiver(handle_NmPropertiesChanged, signal_name="PropertiesChanged",
dbus_interface="org.freedesktop.NetworkManager" )
# see path_keyword etc. in http://dbus.freedesktop.org/doc/dbus-python/api/dbus.service-module.html
bus.add_signal_receiver(handle_NmDeviceStateChanged, signal_name="StateChanged",
dbus_interface="org.freedesktop.NetworkManager.Device",
path_keyword='oPath')
#Device-Add is not yet required to be watch for
## Adding all devices via the DeviceAdded callback
#Devices=manager.GetDevices()
#logger.debug("Startup - getting Devices: %s",str(Devices))
#for oDev in Devices:
# handle_addDevice(oDev)
ConnAct=getProp('/org/freedesktop/NetworkManager','org.freedesktop.NetworkManager','ActiveConnections')
logger.debug("Startup - getting active Connections: %s",str(ConnAct))
# plug that into the active connection changed handler
ScanActiveConnections2(ConnAct)
loop = gobject.MainLoop()
logger.debug("Entering MainLoop")
loop.run() # To stop, call loop.quit().
#end;
#!/bin/sh
PREREQ=""
DESCRIPTION="Adding live session user..."
prereqs()
{
echo "$PREREQ"
}
case $1 in
# get pre-requisites
prereqs)
prereqs
exit 0
;;
esac
. /scripts/casper-functions
load_confmodule
log_begin_msg "$DESCRIPTION"
debconf_backup () {
local question backup
for question; do
backup="$question-casper-backup"
db_register debian-installer/dummy "$backup"
db_get "$question"
db_set "$backup" "$RET"
db_fget "$question" seen
db_fset "$backup" seen "$RET"
done
}
debconf_restore () {
local question backup
for question; do
backup="$question-casper-backup"
db_get "$backup"
db_set "$question" "$RET"
db_fget "$backup" seen
db_fset "$question" seen "$RET"
db_unregister "$backup"
done
}
debconf_backup \
passwd/root-password-crypted \
passwd/root-password passwd/root-password-again \
passwd/user-password-crypted \
passwd/user-password passwd/user-password-again \
passwd/user-fullname passwd/username passwd/user-uid
# U6aMy0wojraho is just a blank password
db_set passwd/root-password-crypted '*'
db_set passwd/user-password-crypted U6aMy0wojraho
db_set passwd/user-fullname "$USERFULLNAME"
db_set passwd/username "$USERNAME"
db_set passwd/user-uid 999
chroot /root /usr/lib/user-setup/user-setup-apply > /dev/null
# Clear out debconf database again to avoid confusing ubiquity later.
debconf_restore \
passwd/root-password-crypted \
passwd/root-password passwd/root-password-again \
passwd/user-password-crypted \
passwd/user-password passwd/user-password-again \
passwd/user-fullname passwd/username passwd/user-uid
if [ -f /root/etc/sudoers ]; then
echo "${USERNAME} ALL=(ALL) NOPASSWD: ALL" >> /root/etc/sudoers
fi
# XXX - awful hack to stop xscreensaver locking the screen (#7150)
echo 'RUNNING_UNDER_GDM="yes"' >> /root/etc/environment
LTS="$(cut -d' ' -f3 /root/cdrom/.disk/info 2>/dev/null)" || LTS=
RELEASE="$(cut -d' ' -f1-2 /root/cdrom/.disk/info 2>/dev/null)" || RELEASE=
if [ "$LTS" = "LTS" ] && [ -n "$RELEASE" ]; then
RELEASE="$RELEASE LTS"
fi
for file in /usr/share/applications/ubiquity-gtkui.desktop /usr/share/applications/ubiquity-gtkui-no-bootloader.desktop; do
if [ -f "/root/$file" ]; then
sed -i "s/RELEASE/$RELEASE/" "/root$file"
chroot /root install -d -o $USERNAME -g $USERNAME /home/$USERNAME/Desktop
chroot /root install -D -o $USERNAME -g $USERNAME $file /home/$USERNAME/Desktop/$(basename "$file")
fi
done
if [ -L /root/home/$USERNAME/Examples ]; then
chroot /root install -o $USERNAME -g $USERNAME -d /home/$USERNAME/Desktop/
mv /root/home/$USERNAME/Examples /root/home/$USERNAME/Desktop/
fi
if [ -f /root/home/$USERNAME/examples.desktop ]; then
chroot /root install -o $USERNAME -g $USERNAME -d /home/$USERNAME/Desktop/
mv /root/home/$USERNAME/examples.desktop /root/home/$USERNAME/Desktop/
fi
#Kubuntu
if [ -f "/root/usr/bin/plasma" ]; then
if [ -f "/root/usr/share/kde4/apps/khelpcenter/plugins/kubuntu/about-kubuntu.desktop" ]; then
chroot /root install -d -o $USERNAME -g $USERNAME /home/$USERNAME/Desktop
chroot /root install -D -o $USERNAME -g $USERNAME /usr/share/kde4/apps/khelpcenter/plugins/kubuntu/about-kubuntu.desktop /home/$USERNAME/Desktop/about-kubuntu.desktop
fi
fi
#Ubuntu MID wants to be installed with --automatic
if [ -f "/root/usr/share/ubuntu-mid-default-settings/mid-gui-start" ]; then
if [ -f "/root/usr/share/applications/ubiquity-gtkui.desktop" ]; then
sed -i 's/--desktop/--automatic --desktop/' "/root/usr/share/applications/ubiquity-gtkui.desktop"
fi
fi
#Ubuntu MID uses kourou, and the ubiquity icon should be easy to find
if [ -f "/root/usr/lib/hildon-desktop/kourou.py" ]; then
if [ -f "/root/etc/xdg/menus/home.menu" ]; then
sed -i '/<\/Include>/i\ <Filename>ubiquity-gtkui.desktop</Filename>' "/root/etc/xdg/menus/home.menu"
fi
fi
log_end_msg
[Desktop Entry]
Type=Application
Version=1.0
# Do not translate the word "RELEASE". It is used as a marker by casper.
Name=Install RELEASE (No bootloader)
Name[am]=የተለቀቀውን መግጠሚያ
Name[ar]=ثبّت RELEASE
Name[ast]=Instalar RELEASE
Name[be]=Усталяваць RELEASE
Name[bg]=Инсталиране на RELEASE
Name[bn]=RELEASE ইনস্টল করুন
Name[bs]=Instaliraj izdanje
Name[ca]=Instal·la la versió RELEASE
Name[cs]=Nainstalovat RELEASE
Name[da]=Installér RELEASE
Name[de]=RELEASE installieren (kein Bootloader)
Name[el]=Εγκατάσταση RELEASE
Name[eo]=Instali RELEASE
Name[es]=Instalar RELEASE
Name[et]=Paigalda RELEASE
Name[eu]=Instalatu RELEASE
Name[fi]=Asenna RELEASE
Name[fr]=Installer RELEASE
Name[ga]=Suiteáil RELEASE
Name[gl]=Instalar RELEASE
Name[gu]=રિલીઝ નું સ્થાપન કરો.
Name[he]=התקנת RELEASE
Name[hi]=प्रकाशन को संस्थापित करें
Name[hr]=Instaliraj RELEASE
Name[hu]=RELEASE telepítése
Name[id]=Pasang RELEASE
Name[it]=Installa RELEASE
Name[ja]=RELEASE のインストール
Name[ka]=RELEASE-ის დაყენება
Name[kk]=RELEASE орнату
Name[km]=ដំឡើង​ឯកសារ​ចេញ​ផ្សាយ
Name[ko]=RELEASE 설치
Name[ku]=RELEASE saz bike
Name[lt]=Įdiegti RELEASE į kompiuterį
Name[lv]=Instalēt RELEASE
Name[mk]=Инсталирај RELEASE
Name[ml]=RELEASE സജ്ജമാക്കുക
Name[mr]=स्थापित RELEASE
Name[nl]=RELEASE installeren
Name[pa]=RELEASE ਰੀਲਿਜ਼
Name[pl]=Zainstaluj RELEASE
Name[pt]=Instalar RELEASE
Name[pt_BR]=Instalar o RELEASE
Name[ro]=Instalare RELEASE
Name[ru]=Установить RELEASE
Name[sk]=Inštalovať RELEASE
Name[sl]=Namesti RELEASE
Name[sq]=Instalo RELEASE
Name[sr]=Инсталирајте RELEASE
Name[sv]=Installera RELEASE
Name[ta]=RELEASEஐ நிறுவு
Name[th]=ติดตั้ง RELEASE
Name[tl]=Iluklok ang RELEASE
Name[tr]=RELEASE Kur
Name[uk]=Встановити RELEASE
Name[vi]=Cài đặt RELEASE
Name[zh_CN]=安装 RELEASE
Name[zh_TW]=安裝 RELEASE
Comment=Install this system permanently to your hard disk
Comment[am]=ይኼን ሲስተም ሀርድ ዲስክዎ ላይ በቋሚነት ይጫኑት
Comment[ar]=ثبّت هذا النظام على القرص الصلب
Comment[ast]=Instalar permanentemente esti sistema nel to discu duru
Comment[be]=Усталяваць сістэму на жорсткі дыск
Comment[bg]=Инсталиране на тази система за постоянно на твърдия диск
Comment[bn]=এই সিস্টেমটি আপনার হার্ডডিস্কে স্থায়ীভাবে ইনস্টল করুন।
Comment[bs]=Instaliraj ovaj sistem trajno na hard disk
Comment[ca]=Instal·leu aquest sistema permanentment al vostre disc dur
Comment[cs]=Nainstalovat tento systém natrvalo na váš disk
Comment[da]=Installér dette system permanent på din harddisk
Comment[de]=Dieses System dauerhaft auf der Festplatte installieren
Comment[el]=Εγκαταστήστε αυτό το σύστημα μόνιμα στο σκληρό σας δίσκο
Comment[eo]=Instali ĉi tiun sistemon daŭre en via disko
Comment[es]=Instalar este sistema permanentemente en su disco duro
Comment[et]=Paigalda see süsteem jäädavalt oma kõvakettale
Comment[eu]=Sistema hau betiko instalatu disko gogorrean
Comment[fi]=Asenna tämä järjestelmä pysyvästi kiintolevyllesi
Comment[fr]=Installer ce système de façon permanente sur votre disque dur
Comment[ga]=Suiteáil an córas seo go buan ar do chruadhiosca
Comment[gl]=Instalar o sistema de xeito permanente no disco ríxido
Comment[gu]=આ સિસ્ટમ તમારી હાર્ડ ડિસ્ક પર હંમેશ માટે સ્થાપિત કરો
Comment[he]=התקנת המערכת באופן קבוע על הכונן הקשיח
Comment[hi]=इस तंत्र को आपके हार्ड डिस्क में स्थायी रूप से संस्थापित करें
Comment[hr]=Trajno instaliraj sustav na čvrsti disk
Comment[hu]=A rendszer telepítése merevlemezre
Comment[id]=Memasang sistem ini secara permanen pada diska Anda
Comment[it]=Installa questo sistema in modo permanente sul disco rigido
Comment[ja]=このシステムをハードディスクにインストールします
Comment[ka]=მოცემული სისტემის მყარ დისკზე ჩაყენება
Comment[kk]=Осы жүйені қатқыл дискіңізге тұрақты орнату
Comment[km]=ដំឡើង​ប្រព័ន្ធ​នេះ​ជា​អចិន្ត្រៃយ៍​ទៅ​កាន់​ថាស​រឹង​របស់​អ្នក
Comment[ko]=이 시스템을 당신의 하드 디스크에 설치합니다.
Comment[ku]=Sîstemê di hard dîskê xwe de saz bike
Comment[lt]=Įdiegti Linux operacinę sistemą į kompiuterio (standųjį) diską
Comment[lv]=Instalēt šo sistēmu cietajā diskā
Comment[mk]=Инсталирајте го системот трајно на Вашиот тврд диск
Comment[ml]=സ്ഥിരമായി ഹാര്‍ഡ് ഡിസ്കിലേക്ക് ഇന്‍സ്റ്റാള്‍ ചെയ്യുക
Comment[mr]=ही प्रणाली कायमची तुमच्या हार्ड डिस्कवर स्थापित करा
Comment[ne]=यो प्रणाली तपाईको हार्ड डिस्कमा स्थाई रुपमा प्रतिस्थापन गर्नुहोस्
Comment[nl]=Dit systeem definitief op uw harde schijf installeren
Comment[pa]=ਇਹ ਸਿਸਟਮ ਪੱਕੇ ਤੌਰ ਉੱਤੇ ਆਪਣੀ ਹਾਰਡ ਡਿਸਕ ਉੱਤੇ ਇੰਸਟਾਲ
Comment[pl]=Instaluje system na dysku twardym
Comment[pt]=Instalar este sistema permanentemente no seu disco rígido
Comment[pt_BR]=Instalar este sistema de maneira permanente no seu disco rígido
Comment[ro]=Instalați acest sistem pe discul calculatorului
Comment[ru]=Установить эту систему на жёсткий диск
Comment[sk]=Nainštalovať systém natrvalo na pevný disk
Comment[sl]=Trajno namesti sistem na trdi disk
Comment[sq]=Instalo këtë sistem përgjithmonë në Hard Disk
Comment[sr]=Инсталирајте овај систем трајно на ваш чврсти диск
Comment[sv]=Installera detta system permanent på din hårddisk
Comment[ta]=இந்த நிலையை நிரந்தரமாக தங்களது கணினியில் நிறுவுக
Comment[th]=ติดตั้งระบบนี้อย่างถาวรลงบนฮาร์ดดิสก์ของคุณ
Comment[tl]=Iluklok ng permanente ang systema sa iyong hard disk
Comment[tr]=Bu sistemi sabit diskinize kalıcı olarak kurun
Comment[uk]=Встановити цю систему на жорсткий диск
Comment[vi]=Cài hệ thống vào đĩa cứng
Comment[zh_CN]=将这个系统永久安装在您的硬盘上
Comment[zh_TW]=將此系統安裝到您的硬碟中
Exec=ubiquity --no-bootloader --desktop %k gtk_ui
Icon=ubiquity
Terminal=false
Categories=GTK;System;Settings;
OnlyShowIn=GNOME;XFCE;Unity;
#X-Ubuntu-Gettext-Domain=ubiquity-desktop
X-Ayatana-Appmenu-Show-Stubs=False
yes
#!/bin/sh
# set -e
export PATH=/usr/bin:/usr/sbin:/bin:/sbin
mountpoint=/cdrom
LIVE_MEDIA_PATH=casper
[ -f /conf/uuid.conf ] && UUID="$(cat /conf/uuid.conf)"
root_persistence="casper-rw"
home_persistence="home-rw"
root_snapshot_label="casper-sn"
home_snapshot_label="home-sn"
USERNAME=casper
USERFULLNAME="Live session user"
HOST=live
BUILD_SYSTEM=Custom
mkdir -p $mountpoint
tried=/tmp/tried
[ -f /etc/casper.conf ] && . /etc/casper.conf
export USERNAME USERFULLNAME HOST BUILD_SYSTEM
. /scripts/casper-helpers
if [ ! -f /casper.vars ]; then
touch /casper.vars
fi
parse_cmdline() {
for x in $(cat /proc/cmdline); do
case $x in
showmounts|show-cow)
export SHOWMOUNTS='Yes' ;;
persistent)
export PERSISTENT="Yes" ;;
nopersistent)
export PERSISTENT="" ;;
persistent-path=*)
export PERSISTENT_PATH="${x#persistent-path=}" ;;
union=*)
export UNIONFS="${x#union=}";;
unionstack=*)
export UNIONSTACK="${x#unionstack=}";;
ip=*)
STATICIP=${x#ip=}
if [ "${STATICIP}" = "" ]; then
STATICIP="frommedia"
fi
export STATICIP ;;
uuid=*)
UUID=${x#uuid=} ;;
ignore_uuid)
UUID="" ;;
live-media-path=*)
LIVE_MEDIA_PATH="${x#live-media-path=}"
export LIVE_MEDIA_PATH
echo "export LIVE_MEDIA_PATH=\"$LIVE_MEDIA_PATH\"" >> /etc/casper.conf ;;
toram)
export TORAM="Yes" ;;
todisk=*)
export TODISK="${x#todisk=}" ;;
esac
done
if [ "${UNIONFS}" = "" ]; then
export UNIONFS="DEFAULT"
fi
}
is_casper_path() {
path=$1
if [ -d "$path/$LIVE_MEDIA_PATH" ]; then
if [ "$(echo $path/$LIVE_MEDIA_PATH/*.squashfs)" != "$path/$LIVE_MEDIA_PATH/*.squashfs" ] ||
[ "$(echo $path/$LIVE_MEDIA_PATH/*.ext2)" != "$path/$LIVE_MEDIA_PATH/*.ext2" ] ||
[ "$(echo $path/$LIVE_MEDIA_PATH/*.dir)" != "$path/$LIVE_MEDIA_PATH/*.dir" ]; then
return 0
fi
fi
return 1
}
matches_uuid() {
if [ -z "$UUID" ]; then
return 0
fi
path="$1"
for try_uuid_file in "$path/.disk/casper-uuid"*; do
[ -e "$try_uuid_file" ] || continue
try_uuid="$(cat "$try_uuid_file")"
if [ "$UUID" = "$try_uuid" ]; then
return 0
fi
done
return 1
}
get_backing_device() {
case "$1" in
*.squashfs|*.ext2)
echo $(setup_loop "$1" "loop" "/sys/block/loop*")
;;
*.dir)
echo "directory"
;;
*)
panic "Unrecognized casper filesystem: $1"
;;
esac
}
match_files_in_dir() {
# Does any files match pattern $1 ?
local pattern="$1"
if [ "$(echo $pattern)" != "$pattern" ]; then
return 0
fi
return 1
}
mount_images_in_directory() {
directory="$1"
rootmnt="$2"
if match_files_in_dir "$directory/$LIVE_MEDIA_PATH/*.squashfs" ||
match_files_in_dir "$directory/$LIVE_MEDIA_PATH/*.ext2" ||
match_files_in_dir "$directory/$LIVE_MEDIA_PATH/*.dir"; then
setup_unionfs "$directory/$LIVE_MEDIA_PATH" "$rootmnt"
else
:
fi
}
is_nice_device() {
sysfs_path="${1#/sys}"
if /sbin/udevadm test-builtin path_id "${sysfs_path}" | egrep -q "ID_PATH=(usb|pci-[^-]*-(ide|sas|scsi|usb|virtio)|platform-sata_mv|platform-orion-ehci|platform-mmc|platform-mxsdhci|platform-omap_hsmmc|platform-sdhci-tegra)"; then
return 0
fi
if echo ${sysfs_path} | grep -q "^/block/dm-"; then
return 0
fi
return 1
}
copy_live_to() {
copyfrom="${1}"
copytodev="${2}"
copyto="${copyfrom}_swap"
size=$(fs_size "" ${copyfrom} "used")
if [ "${copytodev}" = "ram" ]; then
# copying to ram:
freespace=$(awk '/^MemFree:/{f=$2} /^Cached:/{c=$2} END{print f+c}' /proc/meminfo)
mount_options="-o size=${size}k"
free_string="memory"
fstype="tmpfs"
dev="/dev/shm"
else
# it should be a writable block device
if [ -b "${copytodev}" ]; then
dev="${copytodev}"
free_string="space"
fstype=$(get_fstype "${dev}")
freespace=$(fs_size "${dev}")
else
[ "$quiet" != "y" ] && log_warning_msg "${copytodev} is not a block device."
return 1
fi
fi
if [ "${freespace}" -lt "${size}" ] ; then
[ "$quiet" != "y" ] && log_warning_msg "Not enough free ${free_string} (${freespace}k > ${size}k) to copy live media in ${copytodev}."
return 1
fi
# begin copying..
mkdir "${copyto}"
echo "mount -t ${fstype} ${mount_options} ${dev} ${copyto}"
mount -t "${fstype}" ${mount_options} "${dev}" "${copyto}"
cp -a ${copyfrom}/* ${copyto}
if [ -e ${copyfrom}/.disk ]; then
cp -a ${copyfrom}/.disk ${copyto}
fi
umount ${copyfrom}
mount -r -o move ${copyto} ${copyfrom}
rmdir ${copyto}
return 0
}
do_netmount() {
rc=1
modprobe "${MP_QUIET}" af_packet # For DHCP
/sbin/udevadm trigger
/sbin/udevadm settle
configure_networking
export DEVICE
if [ "${NFSROOT}" = "auto" ]; then
NFSROOT=${ROOTSERVER}:${ROOTPATH}
fi
[ "$quiet" != "y" ] && log_begin_msg "Trying netboot from ${NFSROOT}"
if [ "${NETBOOT}" != "nfs" ] && do_cifsmount ; then
rc=0
elif do_nfsmount ; then
NETBOOT="nfs"
export NETBOOT
rc=0
fi
[ "$quiet" != "y" ] && log_end_msg
return ${rc}
}
do_nfsmount() {
rc=1
modprobe "${MP_QUIET}" nfs
if [ -z "${NFSOPTS}" ]; then
NFSOPTS=""
fi
[ "$quiet" != "y" ] && log_begin_msg "Trying nfsmount -o nolock -o ro ${NFSOPTS} ${NFSROOT} ${mountpoint}"
# FIXME: This while loop is an ugly HACK round an nfs bug
i=0
while [ "$i" -lt 60 ]; do
nfsmount -o nolock -o ro ${NFSOPTS} "${NFSROOT}" "${mountpoint}" && rc=0 && break
sleep 1
i="$(($i + 1))"
done
return ${rc}
}
do_cifsmount() {
rc=1
if [ -x "/sbin/mount.cifs" ]; then
if [ -z "${NFSOPTS}" ]; then
CIFSOPTS="-ouser=root,password="
else
CIFSOPTS="${NFSOPTS}"
fi
[ "$quiet" != "y" ] && log_begin_msg "Trying mount.cifs ${NFSROOT} ${mountpoint} ${CIFSOPTS}"
modprobe "${MP_QUIET}" cifs
if mount.cifs "${NFSROOT}" "${mountpoint}" "${CIFSOPTS}" ; then
rc=0
fi
fi
return ${rc}
}
do_snap_copy ()
{
fromdev="${1}"
todir="${2}"
snap_type="${3}"
size=$(fs_size "${fromdev}" "" "used")
if [ -b "${fromdev}" ]; then
# look for free mem
if [ -n "${HOMEMOUNTED}" -a "${snap_type}" = "HOME" ]; then
todev=$(cat /proc/mounts | grep -s " $(base_path ${todir}) " | awk '{print $1}' )
freespace=$(df -k | grep -s ${todev} | awk '{print $4}')
else
freespace=$(awk '/^MemFree:/{f=$2} /^Cached:/{c=$2} END{print f+c}' /proc/meminfo)
fi
tomount="/mnt/tmpsnap"
if [ ! -d "${tomount}" ] ; then
mkdir -p "${tomount}"
fi
fstype=$(get_fstype "${fromdev}")
if [ -n "${fstype}" ]; then
# Copying stuff...
mount -t "${fstype}" -o ro,noatime "${fromdev}" "${tomount}"
cp -a "${tomount}"/* ${todir}
umount "${tomount}"
else
log_warning_msg "Unrecognized fstype: ${fstype} on ${fromdev}:${snap_type}"
fi
rmdir "${tomount}"
if echo ${fromdev} | grep -qs loop; then
losetup -d "${fromdev}"
fi
return 0
else
return 1
[ "$quiet" != "y" ] && log_warning_msg "Unable to find the snapshot ${snap_type} medium"
fi
}
try_snap ()
{
# Look for $snap_label.* in block devices and copy the contents to $snap_mount
# and remember the device and filename for resync on exit in casper.init
snap_label="${1}"
snap_mount="${2}"
snap_type="${3}"
snapdata=$(find_files "${snap_label}.squashfs ${snap_label}.cpio.gz ${snap_label}.ext2")
if [ ! -z "${snapdata}" ]; then
snapdev="$(echo ${snapdata} | cut -f1 -d ' ')"
snapback="$(echo ${snapdata} | cut -f2 -d ' ')"
snapfile="$(echo ${snapdata} | cut -f3 -d ' ')"
if echo "${snapfile}" | grep -qs '\(squashfs\|ext2\)'; then
# squashfs or ext2 snapshot
dev=$(get_backing_device "${snapback}/${snapfile}")
if ! do_snap_copy "${dev}" "${snap_mount}" "${snap_type}"; then
log_warning_msg "Impossible to include the ${snapfile} Snapshot"
return 1
fi
else
# cpio.gz snapshot
# Unfortunately klibc's cpio is incompatible with the rest of
# the world; everything else requires -u -d, while klibc doesn't
# implement them. Try to detect whether it's in use.
cpiopath="$(which cpio)" || true
if [ "$cpiopath" ] && grep -aq /lib/klibc "$cpiopath"; then
cpioargs=
else
cpioargs='-u -d'
fi
if ! (cd "${snap_mount}" && zcat "${snapback}/${snapfile}" | cpio -i $cpioargs 2>/dev/null) ; then
log_warning_msg "Impossible to include the ${snapfile} Snapshot"
return 1
fi
fi
umount "${snapback}"
else
dev=$(find_cow_device "${snap_label}")
if [ -b "${dev}" ]; then
if echo "${dev}" | grep -qs loop; then
# strange things happens, user confused?
snaploop=$( losetup ${dev} | awk '{print $3}' | tr -d '()' )
snapfile=$(basename ${snaploop})
snapdev=$(cat /proc/mounts | awk '{print $2,$1}' | grep -es "^$( dirname ${snaploop} )" | cut -f2 -d ' ')
else
snapdev="${dev}"
fi
if ! do_snap_copy "${dev}" "${snap_mount}" "${snap_type}" ; then
log_warning_msg "Impossible to include the ${snap_label} Snapshot"
return 1
else
if [ -n "${snapfile}" ]; then
# it was a loop device, user confused
umount ${snapdev}
fi
fi
else
log_warning_msg "Impossible to include the ${snap_label} Snapshot"
return 1
fi
fi
echo "export ${snap_type}SNAP="/cow${snap_mount#$rootmnt}":${snapdev}:${snapfile}" >> /etc/casper.conf # for resync on reboot/halt
return 0
}
setup_unionfs() {
image_directory="$1"
rootmnt="$2"
if [ "${UNIONFS}" = 'DEFAULT' ]; then
for union in 'overlayfs' 'aufs' 'unionfs'
do
modprobe "${MP_QUIET}" -b ${union} || true
if cut -f2 /proc/filesystems | grep -q "^${union}\$"; then
UNIONFS="${union}"
break
fi
done
fi
if [ "${UNIONFS}" = 'DEFAULT' -a -x /bin/unionfs-fuse ]; then
UNIONFS="unionfs-fuse"
fi
# If all else fails fall back to aufs.
if [ "${UNIONFS}" = 'DEFAULT' ]; then
UNIONFS='aufs'
fi
# run-init can't deal with images in a subdir, but we're going to
# move all of these away before it runs anyway. No, we're not,
# put them in / since move-mounting them into / breaks mono and
# some other apps.
croot="/"
# Let's just mount the read-only file systems first
rofsstring=""
rofslist=""
if [ "${UNIONFS}" = "aufs" ]; then
roopt="rr"
elif [ "${UNIONFS}" = "unionfs-fuse" ]; then
roopt="RO"
else
roopt="ro"
fi
mkdir -p "${croot}"
for image_type in "ext2" "squashfs" "dir" ; do
for image in "${image_directory}"/*."${image_type}"; do
imagename=$(basename "${image}")
if [ -n "$UNIONSTACK" ]; then
if [ "$(echo $UNIONSTACK | sed "s/$imagename//";)" == "$UNIONSTACK" ]; then
log_warning_msg "Filesystem image $imagename not in UNIONSTACK. Ignored."
continue
fi
fi
if [ -d "${image}" ]; then
# it is a plain directory: do nothing
rofsstring="${image}=${roopt}:${rofsstring}"
rofslist="${image} ${rofslist}"
elif [ -f "${image}" ]; then
backdev=$(get_backing_device "$image")
fstype=$(get_fstype "${backdev}")
if [ "${fstype}" = "unknown" ]; then
panic "Unknown file system type on ${backdev} (${image})"
fi
mkdir -p "${croot}/${imagename}"
mount -t "${fstype}" -o ro,noatime "${backdev}" "${croot}/${imagename}" || panic "Can not mount $backdev ($image) on ${croot}/${imagename}" && rofsstring="${croot}/${imagename}=${roopt}:${rofsstring}" && rofslist="${croot}/${imagename} ${rofslist}"
fi
done
done
rofsstring=${rofsstring%:}
mkdir -p /cow
cowdevice="tmpfs"
cow_fstype="tmpfs"
cow_mountopt="rw,noatime,mode=755"
# Looking for "${root_persistence}" device or file
if [ -n "${PERSISTENT}" ]; then
cowprobe=$(find_cow_device "${root_persistence}")
if [ -b "${cowprobe}" ]; then
cowdevice=${cowprobe}
cow_fstype=$(get_fstype "${cowprobe}")
cow_mountopt="rw,noatime"
else
[ "$quiet" != "y" ] && log_warning_msg "Unable to find the persistent medium"
fi
fi
mount -t ${cow_fstype} -o ${cow_mountopt} ${cowdevice} /cow || panic "Can not mount $cowdevice on /cow"
overlay_mount_dir=/overlay
mkdir -p "$overlay_mount_dir"
case ${UNIONFS} in
unionfs-fuse)
(ulimit -n 16384; unionfs-fuse -o cow -o noinitgroups -o default_permissions -o allow_other -o use_ino -o suid /cow=RW:$rofsstring "$rootmnt" || panic "${UNIONFS} mount failed")
mkdir -p /dev/.initramfs/varrun
pidof unionfs-fuse >> /dev/.initramfs/varrun/sendsigs.omit || true
;;
aufs|unionfs)
mount -t ${UNIONFS} -o noatime,dirs=/cow=rw:$rofsstring ${UNIONFS} "$rootmnt" || panic "${UNIONFS} mount failed"
;;
overlayfs)
# Mount the layers pairwise from the bottom onto rootmnt,
# for the second and later layers rootmnt forms the lower layer.
#overlay all readonly file systems first
mounts=""
for mount in $rofslist
do
mounts="$mount $mounts"
done
lower=""
for mount in $mounts
do
if [ "$lower" = "" ]; then
lower="$mount"
continue
fi
mount -t overlayfs -o "upperdir=$mount,lowerdir=$lower" \
"$mount" "$overlay_mount_dir"
lower="$overlay_mount_dir"
done
mount -t overlayfs -o "upperdir=/cow,lowerdir=$overlay_mount_dir" \
"$mount" "$rootmnt"
;;
esac
# Adding other custom mounts
if [ -n "${PERSISTENT}" ]; then
# directly mount /home
# FIXME: add a custom mounts configurable system
homecow=$(find_cow_device "${home_persistence}" )
if [ -b "${homecow}" ]; then
mount -t $(get_fstype "${homecow}") -o rw,noatime "${homecow}" "${rootmnt}/home"
export HOMEMOUNTED=1 # used to proper calculate free space in do_snap_copy()
else
[ "$quiet" != "y" ] && log_warning_msg "Unable to find the persistent home medium"
fi
# Look for other snapshots to copy in
try_snap "${root_snapshot_label}" "${rootmnt}" "ROOT"
try_snap "${home_snapshot_label}" "${rootmnt}/home" "HOME"
fi
if [ -n "${SHOWMOUNTS}" ]; then
for d in ${rofslist}; do
mkdir -p "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
case d in
*.dir) # do nothing # mount -o bind "${d}" "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
;;
*)
if [ "${UNIONFS}" = unionfs-fuse ]; then
mount -o bind "${d}" "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
else
mount -o move "${d}" "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
fi
;;
esac
done
# shows cow fs on /cow for use by casper-snapshot
mkdir -p "${rootmnt}/cow"
mount -o bind /cow "${rootmnt}/cow"
fi
# move the first mount; no head in busybox-initramfs
#for d in $(mount -t squashfs | cut -d\ -f 3); do
# mkdir -p "${rootmnt}/rofs"
# if [ "${UNIONFS}" = unionfs-fuse ]; then
# mount -o bind "${d}" "${rootmnt}/rofs"
# else
# mount -o move "${d}" "${rootmnt}/rofs"
# fi
# break
#done
mkdir -p "${rootmnt}/rofs"
mount -o move "$overlay_mount_dir" "${rootmnt}/rofs"
}
check_dev ()
{
sysdev="${1}"
devname="${2}"
skip_uuid_check="${3}"
if [ -z "${devname}" ]; then
devname=$(sys2dev "${sysdev}")
fi
if [ -d "${devname}" ]; then
mount -o bind "${devname}" $mountpoint || continue
if is_casper_path $mountpoint; then
echo $mountpoint
return 0
else
umount $mountpoint
fi
fi
[ -e "$devname" ] || continue
if [ -n "${LIVEMEDIA_OFFSET}" ]; then
loopdevname=$(setup_loop "${devname}" "loop" "/sys/block/loop*" "${LIVEMEDIA_OFFSET}")
devname="${loopdevname}"
fi
fstype=$(get_fstype "${devname}")
if is_supported_fs ${fstype}; then
devuid=$(blkid -o value -s UUID "$devname")
[ -n "$devuid" ] && grep -qs "\<$devuid\>" $tried && continue
mount -t ${fstype} -o ro,noatime "${devname}" $mountpoint || continue
[ -n "$devuid" ] && echo "$devuid" >> $tried
if is_casper_path $mountpoint && \
([ "$skip_uuid_check" ] || [ "$UUID" = "$devuid" ] || matches_uuid $mountpoint); then
echo $mountpoint
return 0
else
umount $mountpoint
fi
fi
if [ -n "${LIVEMEDIA_OFFSET}" ]; then
losetup -d "${loopdevname}"
fi
return 1
}
find_livefs() {
timeout="${1}"
# first look at the one specified in the command line
if [ ! -z "${LIVEMEDIA}" ]; then
if check_dev "null" "${LIVEMEDIA}" "skip_uuid_check"; then
return 0
fi
fi
# don't start autodetection before timeout has expired
if [ -n "${LIVEMEDIA_TIMEOUT}" ]; then
if [ "${timeout}" -lt "${LIVEMEDIA_TIMEOUT}" ]; then
return 1
fi
fi
# or do the scan of block devices
for sysblock in $(echo /sys/block/* | tr ' ' '\n' | egrep -v "/(loop|ram|fd)"); do
devname=$(sys2dev "${sysblock}")
[ -e "$devname" ] || continue
fstype=$(get_fstype "${devname}")
if /lib/udev/cdrom_id ${devname} > /dev/null; then
if check_dev "null" "${devname}" ; then
return 0
fi
elif is_nice_device "${sysblock}" ; then
for dev in $(subdevices "${sysblock}"); do
if check_dev "${dev}" ; then
return 0
fi
done
elif [ "${fstype}" = "squashfs" -o \
"${fstype}" = "ext4" -o \
"${fstype}" = "ext3" -o \
"${fstype}" = "ext2" -o \
"${fstype}" = "btrfs" ]; then
# This is an ugly hack situation, the block device has
# an image directly on it. It's hopefully
# casper, so take it and run with it.
ln -s "${devname}" "${devname}.${fstype}"
echo "${devname}.${fstype}"
return 0
fi
done
return 1
}
set_usplash_timeout() {
if [ -x /sbin/usplash_write ]; then
/sbin/usplash_write "TIMEOUT 120"
fi
}
start_usplash_pulse() {
if [ -x /sbin/usplash_write ]; then
/sbin/usplash_write "PULSELOGO"
fi
}
mountroot() {
exec 6>&1
exec 7>&2
exec > casper.log
exec 2>&1
tail -f casper.log >&7 &
tailpid="$!"
parse_cmdline
set_usplash_timeout
start_usplash_pulse
[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/casper-premount"
run_scripts /scripts/casper-premount
[ "$quiet" != "y" ] && log_end_msg
# Needed here too because some things (*cough* udev *cough*)
# changes the timeout
set_usplash_timeout
if [ ! -z "${NETBOOT}" ]; then
if do_netmount ; then
livefs_root="${mountpoint}"
else
panic "Unable to find a live file system on the network"
fi
else
# Scan local devices for the image
i=0
while [ "$i" -lt 60 ]; do
livefs_root=$(find_livefs $i)
if [ "${livefs_root}" ]; then
break
fi
sleep 1
i="$(($i + 1))"
done
fi
if [ -z "${livefs_root}" ]; then
panic "Unable to find a medium containing a live file system"
fi
if [ "${TORAM}" ]; then
live_dest="ram"
elif [ "${TODISK}" ]; then
live_dest="${TODISK}"
fi
if [ "${live_dest}" ]; then
log_begin_msg "Copying live_media to ${live_dest}"
copy_live_to "${livefs_root}" "${live_dest}"
log_end_msg
fi
mount_images_in_directory "${livefs_root}" "${rootmnt}"
log_end_msg
# Allow to override USERNAME and HOST based on media information
# make it skipable by setting FLAVOUR= in casper.conf
if [ -f /cdrom/.disk/info ] && [ -z "$FLAVOUR" ]; then
FLAVOUR="$(cut -d' ' -f1 "/cdrom/.disk/info" 2>/dev/null | tr '[A-Z]' '[a-z]')" || FLAVOUR=
if [ -n "$FLAVOUR" ]; then
HOST=$FLAVOUR
USERNAME=$FLAVOUR
export HOST USERNAME
sed -i "s,USERNAME=.*,USERNAME=\"$FLAVOUR\",g; s,HOST=.*,HOST=\"$FLAVOUR\",g" /etc/casper.conf
fi
fi
# unionfs-fuse needs /dev to be bind-mounted for the duration of
# casper-bottom; udev's init script will take care of things after that
if [ "${UNIONFS}" = unionfs-fuse ]; then
mount -n -o bind /dev "${rootmnt}/dev"
fi
# Open up two fifo's fd's for debconf-communicate to use. Speeds up
# the Casper process considerably.
log_begin_msg "Creating debconf-communicate fifo mechanism"
mkfifo /tmp/debconf-in.fifo
mkfifo /tmp/debconf-out.fifo
# Make the template database read-only, so that passthrough debconf
# instances can write to it directly; otherwise templates are only
# passed through when necessary. Use temporary config databases as
# well; we'll copy their contents back at the end.
DEBCONF_TMPDIR="$(chroot /root mktemp -dt debconf.XXXXXX)"
cp -a /root/var/cache/debconf/config.dat "/root$DEBCONF_TMPDIR/"
cp -a /root/var/cache/debconf/passwords.dat "/root$DEBCONF_TMPDIR/"
sed "s,^Filename: /var/cache/debconf/\(config\|passwords\).dat$,Filename: $DEBCONF_TMPDIR/\1.dat,; /^Name: templatedb/a\
Readonly: true" /root/etc/debconf.conf >"/root$DEBCONF_TMPDIR/debconf.conf"
DEBCONF_SYSTEMRC="$DEBCONF_TMPDIR/debconf.conf" chroot /root debconf-communicate -fnoninteractive casper > /tmp/debconf-out.fifo < /tmp/debconf-in.fifo &
debconfpid="$!"
if [ ! -p /tmp/debconf-in.fifo ] || [ ! -p /tmp/debconf-out.fifo ]; then
log_warning_msg "failed to setup debconf-communicate channel"
fi
log_end_msg
# Order matters!
# These file descriptors must stay open until we're finished with
# debconf-communicate.
exec 4</tmp/debconf-out.fifo 3>/tmp/debconf-in.fifo
maybe_break casper-bottom
[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/casper-bottom"
run_scripts /scripts/casper-bottom
[ "$quiet" != "y" ] && log_end_msg
if [ "${UNIONFS}" = unionfs-fuse ]; then
umount "${rootmnt}/dev"
fi
# Close the fd's associated with debconf-communicate.
exec 3>&- 4<&-
rm -f /tmp/debconf-in.fifo
rm -f /tmp/debconf-out.fifo
wait $debconfpid
# Copy config database changes back to the master files.
chroot /root debconf-copydb tmpdb config \
--config=Name:tmpdb --config=Driver:File \
--config="Filename:$DEBCONF_TMPDIR/config.dat"
chroot /root debconf-copydb tmpdb passwords \
--config=Name:tmpdb --config=Driver:File \
--config="Filename:$DEBCONF_TMPDIR/passwords.dat"
rm -rf "$DEBCONF_TMPDIR"
exec 1>&6 6>&-
exec 2>&7 7>&-
kill "$tailpid"
cp casper.log "${rootmnt}/var/log/"
if [ -f /etc/casper.conf ]; then
cp /etc/casper.conf "${rootmnt}/etc/"
fi
}
LIP SS2013 32BIT
#!/bin/sh
# set -e
export PATH=/usr/bin:/usr/sbin:/bin:/sbin
mountpoint=/cdrom
LIVE_MEDIA_PATH=casper
[ -f /conf/uuid.conf ] && UUID="$(cat /conf/uuid.conf)"
root_persistence="casper-rw"
home_persistence="home-rw"
root_snapshot_label="casper-sn"
home_snapshot_label="home-sn"
USERNAME=casper
USERFULLNAME="Live session user"
HOST=live
BUILD_SYSTEM=Custom
mkdir -p $mountpoint
tried=/tmp/tried
[ -f /etc/casper.conf ] && . /etc/casper.conf
export USERNAME USERFULLNAME HOST BUILD_SYSTEM
. /scripts/casper-helpers
if [ ! -f /casper.vars ]; then
touch /casper.vars
fi
parse_cmdline() {
for x in $(cat /proc/cmdline); do
case $x in
showmounts|show-cow)
export SHOWMOUNTS='Yes' ;;
persistent)
export PERSISTENT="Yes" ;;
nopersistent)
export PERSISTENT="" ;;
persistent-path=*)
export PERSISTENT_PATH="${x#persistent-path=}" ;;
union=*)
export UNIONFS="${x#union=}";;
unionstack=*)
export UNIONSTACK="${x#unionstack=}";;
ip=*)
STATICIP=${x#ip=}
if [ "${STATICIP}" = "" ]; then
STATICIP="frommedia"
fi
export STATICIP ;;
uuid=*)
UUID=${x#uuid=} ;;
ignore_uuid)
UUID="" ;;
live-media-path=*)
LIVE_MEDIA_PATH="${x#live-media-path=}"
export LIVE_MEDIA_PATH
echo "export LIVE_MEDIA_PATH=\"$LIVE_MEDIA_PATH\"" >> /etc/casper.conf ;;
toram)
export TORAM="Yes" ;;
todisk=*)
export TODISK="${x#todisk=}" ;;
esac
done
if [ "${UNIONFS}" = "" ]; then
export UNIONFS="DEFAULT"
fi
}
is_casper_path() {
path=$1
if [ -d "$path/$LIVE_MEDIA_PATH" ]; then
if [ "$(echo $path/$LIVE_MEDIA_PATH/*.squashfs)" != "$path/$LIVE_MEDIA_PATH/*.squashfs" ] ||
[ "$(echo $path/$LIVE_MEDIA_PATH/*.ext2)" != "$path/$LIVE_MEDIA_PATH/*.ext2" ] ||
[ "$(echo $path/$LIVE_MEDIA_PATH/*.dir)" != "$path/$LIVE_MEDIA_PATH/*.dir" ]; then
return 0
fi
fi
return 1
}
matches_uuid() {
if [ -z "$UUID" ]; then
return 0
fi
path="$1"
for try_uuid_file in "$path/.disk/casper-uuid"*; do
[ -e "$try_uuid_file" ] || continue
try_uuid="$(cat "$try_uuid_file")"
if [ "$UUID" = "$try_uuid" ]; then
return 0
fi
done
return 1
}
get_backing_device() {
case "$1" in
*.squashfs|*.ext2)
echo $(setup_loop "$1" "loop" "/sys/block/loop*")
;;
*.dir)
echo "directory"
;;
*)
panic "Unrecognized casper filesystem: $1"
;;
esac
}
match_files_in_dir() {
# Does any files match pattern $1 ?
local pattern="$1"
if [ "$(echo $pattern)" != "$pattern" ]; then
return 0
fi
return 1
}
mount_images_in_directory() {
directory="$1"
rootmnt="$2"
if match_files_in_dir "$directory/$LIVE_MEDIA_PATH/*.squashfs" ||
match_files_in_dir "$directory/$LIVE_MEDIA_PATH/*.ext2" ||
match_files_in_dir "$directory/$LIVE_MEDIA_PATH/*.dir"; then
setup_unionfs "$directory/$LIVE_MEDIA_PATH" "$rootmnt"
else
:
fi
}
is_nice_device() {
sysfs_path="${1#/sys}"
if /sbin/udevadm test-builtin path_id "${sysfs_path}" | egrep -q "ID_PATH=(usb|pci-[^-]*-(ide|sas|scsi|usb|virtio)|platform-sata_mv|platform-orion-ehci|platform-mmc|platform-mxsdhci|platform-omap_hsmmc|platform-sdhci-tegra)"; then
return 0
fi
if echo ${sysfs_path} | grep -q "^/block/dm-"; then
return 0
fi
return 1
}
copy_live_to() {
copyfrom="${1}"
copytodev="${2}"
copyto="${copyfrom}_swap"
size=$(fs_size "" ${copyfrom} "used")
if [ "${copytodev}" = "ram" ]; then
# copying to ram:
freespace=$(awk '/^MemFree:/{f=$2} /^Cached:/{c=$2} END{print f+c}' /proc/meminfo)
mount_options="-o size=${size}k"
free_string="memory"
fstype="tmpfs"
dev="/dev/shm"
else
# it should be a writable block device
if [ -b "${copytodev}" ]; then
dev="${copytodev}"
free_string="space"
fstype=$(get_fstype "${dev}")
freespace=$(fs_size "${dev}")
else
[ "$quiet" != "y" ] && log_warning_msg "${copytodev} is not a block device."
return 1
fi
fi
if [ "${freespace}" -lt "${size}" ] ; then
[ "$quiet" != "y" ] && log_warning_msg "Not enough free ${free_string} (${freespace}k > ${size}k) to copy live media in ${copytodev}."
return 1
fi
# begin copying..
mkdir "${copyto}"
echo "mount -t ${fstype} ${mount_options} ${dev} ${copyto}"
mount -t "${fstype}" ${mount_options} "${dev}" "${copyto}"
cp -a ${copyfrom}/* ${copyto}
if [ -e ${copyfrom}/.disk ]; then
cp -a ${copyfrom}/.disk ${copyto}
fi
umount ${copyfrom}
mount -r -o move ${copyto} ${copyfrom}
rmdir ${copyto}
return 0
}
do_netmount() {
rc=1
modprobe "${MP_QUIET}" af_packet # For DHCP
/sbin/udevadm trigger
/sbin/udevadm settle
configure_networking
export DEVICE
if [ "${NFSROOT}" = "auto" ]; then
NFSROOT=${ROOTSERVER}:${ROOTPATH}
fi
[ "$quiet" != "y" ] && log_begin_msg "Trying netboot from ${NFSROOT}"
if [ "${NETBOOT}" != "nfs" ] && do_cifsmount ; then
rc=0
elif do_nfsmount ; then
NETBOOT="nfs"
export NETBOOT
rc=0
fi
[ "$quiet" != "y" ] && log_end_msg
return ${rc}
}
do_nfsmount() {
rc=1
modprobe "${MP_QUIET}" nfs
if [ -z "${NFSOPTS}" ]; then
NFSOPTS=""
fi
[ "$quiet" != "y" ] && log_begin_msg "Trying nfsmount -o nolock -o ro ${NFSOPTS} ${NFSROOT} ${mountpoint}"
# FIXME: This while loop is an ugly HACK round an nfs bug
i=0
while [ "$i" -lt 60 ]; do
nfsmount -o nolock -o ro ${NFSOPTS} "${NFSROOT}" "${mountpoint}" && rc=0 && break
sleep 1
i="$(($i + 1))"
done
return ${rc}
}
do_cifsmount() {
rc=1
if [ -x "/sbin/mount.cifs" ]; then
if [ -z "${NFSOPTS}" ]; then
CIFSOPTS="-ouser=root,password="
else
CIFSOPTS="${NFSOPTS}"
fi
[ "$quiet" != "y" ] && log_begin_msg "Trying mount.cifs ${NFSROOT} ${mountpoint} ${CIFSOPTS}"
modprobe "${MP_QUIET}" cifs
if mount.cifs "${NFSROOT}" "${mountpoint}" "${CIFSOPTS}" ; then
rc=0
fi
fi
return ${rc}
}
do_snap_copy ()
{
fromdev="${1}"
todir="${2}"
snap_type="${3}"
size=$(fs_size "${fromdev}" "" "used")
if [ -b "${fromdev}" ]; then
# look for free mem
if [ -n "${HOMEMOUNTED}" -a "${snap_type}" = "HOME" ]; then
todev=$(cat /proc/mounts | grep -s " $(base_path ${todir}) " | awk '{print $1}' )
freespace=$(df -k | grep -s ${todev} | awk '{print $4}')
else
freespace=$(awk '/^MemFree:/{f=$2} /^Cached:/{c=$2} END{print f+c}' /proc/meminfo)
fi
tomount="/mnt/tmpsnap"
if [ ! -d "${tomount}" ] ; then
mkdir -p "${tomount}"
fi
fstype=$(get_fstype "${fromdev}")
if [ -n "${fstype}" ]; then
# Copying stuff...
mount -t "${fstype}" -o ro,noatime "${fromdev}" "${tomount}"
cp -a "${tomount}"/* ${todir}
umount "${tomount}"
else
log_warning_msg "Unrecognized fstype: ${fstype} on ${fromdev}:${snap_type}"
fi
rmdir "${tomount}"
if echo ${fromdev} | grep -qs loop; then
losetup -d "${fromdev}"
fi
return 0
else
return 1
[ "$quiet" != "y" ] && log_warning_msg "Unable to find the snapshot ${snap_type} medium"
fi
}
try_snap ()
{
# Look for $snap_label.* in block devices and copy the contents to $snap_mount
# and remember the device and filename for resync on exit in casper.init
snap_label="${1}"
snap_mount="${2}"
snap_type="${3}"
snapdata=$(find_files "${snap_label}.squashfs ${snap_label}.cpio.gz ${snap_label}.ext2")
if [ ! -z "${snapdata}" ]; then
snapdev="$(echo ${snapdata} | cut -f1 -d ' ')"
snapback="$(echo ${snapdata} | cut -f2 -d ' ')"
snapfile="$(echo ${snapdata} | cut -f3 -d ' ')"
if echo "${snapfile}" | grep -qs '\(squashfs\|ext2\)'; then
# squashfs or ext2 snapshot
dev=$(get_backing_device "${snapback}/${snapfile}")
if ! do_snap_copy "${dev}" "${snap_mount}" "${snap_type}"; then
log_warning_msg "Impossible to include the ${snapfile} Snapshot"
return 1
fi
else
# cpio.gz snapshot
# Unfortunately klibc's cpio is incompatible with the rest of
# the world; everything else requires -u -d, while klibc doesn't
# implement them. Try to detect whether it's in use.
cpiopath="$(which cpio)" || true
if [ "$cpiopath" ] && grep -aq /lib/klibc "$cpiopath"; then
cpioargs=
else
cpioargs='-u -d'
fi
if ! (cd "${snap_mount}" && zcat "${snapback}/${snapfile}" | cpio -i $cpioargs 2>/dev/null) ; then
log_warning_msg "Impossible to include the ${snapfile} Snapshot"
return 1
fi
fi
umount "${snapback}"
else
dev=$(find_cow_device "${snap_label}")
if [ -b "${dev}" ]; then
if echo "${dev}" | grep -qs loop; then
# strange things happens, user confused?
snaploop=$( losetup ${dev} | awk '{print $3}' | tr -d '()' )
snapfile=$(basename ${snaploop})
snapdev=$(cat /proc/mounts | awk '{print $2,$1}' | grep -es "^$( dirname ${snaploop} )" | cut -f2 -d ' ')
else
snapdev="${dev}"
fi
if ! do_snap_copy "${dev}" "${snap_mount}" "${snap_type}" ; then
log_warning_msg "Impossible to include the ${snap_label} Snapshot"
return 1
else
if [ -n "${snapfile}" ]; then
# it was a loop device, user confused
umount ${snapdev}
fi
fi
else
log_warning_msg "Impossible to include the ${snap_label} Snapshot"
return 1
fi
fi
echo "export ${snap_type}SNAP="/cow${snap_mount#$rootmnt}":${snapdev}:${snapfile}" >> /etc/casper.conf # for resync on reboot/halt
return 0
}
setup_unionfs() {
image_directory="$1"
rootmnt="$2"
if [ "${UNIONFS}" = 'DEFAULT' ]; then
for union in 'overlayfs' 'aufs' 'unionfs'
do
modprobe "${MP_QUIET}" -b ${union} || true
if cut -f2 /proc/filesystems | grep -q "^${union}\$"; then
UNIONFS="${union}"
break
fi
done
fi
if [ "${UNIONFS}" = 'DEFAULT' -a -x /bin/unionfs-fuse ]; then
UNIONFS="unionfs-fuse"
fi
# If all else fails fall back to aufs.
if [ "${UNIONFS}" = 'DEFAULT' ]; then
UNIONFS='aufs'
fi
# run-init can't deal with images in a subdir, but we're going to
# move all of these away before it runs anyway. No, we're not,
# put them in / since move-mounting them into / breaks mono and
# some other apps.
croot="/"
# Let's just mount the read-only file systems first
rofsstring=""
rofslist=""
if [ "${UNIONFS}" = "aufs" ]; then
roopt="rr"
elif [ "${UNIONFS}" = "unionfs-fuse" ]; then
roopt="RO"
else
roopt="ro"
fi
mkdir -p "${croot}"
for image_type in "ext2" "squashfs" "dir" ; do
for image in "${image_directory}"/*."${image_type}"; do
imagename=$(basename "${image}")
if [ -n "$UNIONSTACK" ]; then
if [ "$(echo $UNIONSTACK | sed "s/$imagename//";)" == "$UNIONSTACK" ]; then
log_warning_msg "Filesystem image $imagename not in UNIONSTACK. Ignored."
continue
fi
fi
if [ -d "${image}" ]; then
# it is a plain directory: do nothing
rofsstring="${image}=${roopt}:${rofsstring}"
rofslist="${image} ${rofslist}"
elif [ -f "${image}" ]; then
backdev=$(get_backing_device "$image")
fstype=$(get_fstype "${backdev}")
if [ "${fstype}" = "unknown" ]; then
panic "Unknown file system type on ${backdev} (${image})"
fi
mkdir -p "${croot}/${imagename}"
mount -t "${fstype}" -o ro,noatime "${backdev}" "${croot}/${imagename}" || panic "Can not mount $backdev ($image) on ${croot}/${imagename}" && rofsstring="${croot}/${imagename}=${roopt}:${rofsstring}" && rofslist="${croot}/${imagename} ${rofslist}"
fi
done
done
rofsstring=${rofsstring%:}
mkdir -p /cow
cowdevice="tmpfs"
cow_fstype="tmpfs"
cow_mountopt="rw,noatime,mode=755"
# Looking for "${root_persistence}" device or file
if [ -n "${PERSISTENT}" ]; then
cowprobe=$(find_cow_device "${root_persistence}")
if [ -b "${cowprobe}" ]; then
cowdevice=${cowprobe}
cow_fstype=$(get_fstype "${cowprobe}")
cow_mountopt="rw,noatime"
else
[ "$quiet" != "y" ] && log_warning_msg "Unable to find the persistent medium"
fi
fi
mount -t ${cow_fstype} -o ${cow_mountopt} ${cowdevice} /cow || panic "Can not mount $cowdevice on /cow"
case ${UNIONFS} in
unionfs-fuse)
(ulimit -n 16384; unionfs-fuse -o cow -o noinitgroups -o default_permissions -o allow_other -o use_ino -o suid /cow=RW:$rofsstring "$rootmnt" || panic "${UNIONFS} mount failed")
mkdir -p /dev/.initramfs/varrun
pidof unionfs-fuse >> /dev/.initramfs/varrun/sendsigs.omit || true
;;
aufs|unionfs)
mount -t ${UNIONFS} -o noatime,dirs=/cow=rw:$rofsstring ${UNIONFS} "$rootmnt" || panic "${UNIONFS} mount failed"
;;
overlayfs)
# Mount the layers pairwise from the bottom onto rootmnt,
# for the second and later layers rootmnt forms the lower layer.
mounts=""
for mount in /cow $rofslist
do
mounts="$mount $mounts"
done
lower=""
for mount in $mounts
do
if [ "$lower" = "" ]; then
lower="$mount"
continue
fi
mount -t overlayfs -o "upperdir=$mount,lowerdir=$lower" \
"$mount" "$rootmnt"
lower="$rootmnt"
done
;;
esac
# Adding other custom mounts
if [ -n "${PERSISTENT}" ]; then
# directly mount /home
# FIXME: add a custom mounts configurable system
homecow=$(find_cow_device "${home_persistence}" )
if [ -b "${homecow}" ]; then
mount -t $(get_fstype "${homecow}") -o rw,noatime "${homecow}" "${rootmnt}/home"
export HOMEMOUNTED=1 # used to proper calculate free space in do_snap_copy()
else
[ "$quiet" != "y" ] && log_warning_msg "Unable to find the persistent home medium"
fi
# Look for other snapshots to copy in
try_snap "${root_snapshot_label}" "${rootmnt}" "ROOT"
try_snap "${home_snapshot_label}" "${rootmnt}/home" "HOME"
fi
if [ -n "${SHOWMOUNTS}" ]; then
for d in ${rofslist}; do
mkdir -p "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
case d in
*.dir) # do nothing # mount -o bind "${d}" "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
;;
*)
if [ "${UNIONFS}" = unionfs-fuse ]; then
mount -o bind "${d}" "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
else
mount -o move "${d}" "${rootmnt}/${LIVE_MEDIA_PATH}/${d##*/}"
fi
;;
esac
done
# shows cow fs on /cow for use by casper-snapshot
mkdir -p "${rootmnt}/cow"
mount -o bind /cow "${rootmnt}/cow"
fi
# move the first mount; no head in busybox-initramfs
for d in $(mount -t squashfs | cut -d\ -f 3); do
mkdir -p "${rootmnt}/rofs"
if [ "${UNIONFS}" = unionfs-fuse ]; then
mount -o bind "${d}" "${rootmnt}/rofs"
else
mount -o move "${d}" "${rootmnt}/rofs"
fi
break
done
}
check_dev ()
{
sysdev="${1}"
devname="${2}"
skip_uuid_check="${3}"
if [ -z "${devname}" ]; then
devname=$(sys2dev "${sysdev}")
fi
if [ -d "${devname}" ]; then
mount -o bind "${devname}" $mountpoint || continue
if is_casper_path $mountpoint; then
echo $mountpoint
return 0
else
umount $mountpoint
fi
fi
[ -e "$devname" ] || continue
if [ -n "${LIVEMEDIA_OFFSET}" ]; then
loopdevname=$(setup_loop "${devname}" "loop" "/sys/block/loop*" "${LIVEMEDIA_OFFSET}")
devname="${loopdevname}"
fi
fstype=$(get_fstype "${devname}")
if is_supported_fs ${fstype}; then
devuid=$(blkid -o value -s UUID "$devname")
[ -n "$devuid" ] && grep -qs "\<$devuid\>" $tried && continue
mount -t ${fstype} -o ro,noatime "${devname}" $mountpoint || continue
[ -n "$devuid" ] && echo "$devuid" >> $tried
if is_casper_path $mountpoint && \
([ "$skip_uuid_check" ] || [ "$UUID" = "$devuid" ] || matches_uuid $mountpoint); then
echo $mountpoint
return 0
else
umount $mountpoint
fi
fi
if [ -n "${LIVEMEDIA_OFFSET}" ]; then
losetup -d "${loopdevname}"
fi
return 1
}
find_livefs() {
timeout="${1}"
# first look at the one specified in the command line
if [ ! -z "${LIVEMEDIA}" ]; then
if check_dev "null" "${LIVEMEDIA}" "skip_uuid_check"; then
return 0
fi
fi
# don't start autodetection before timeout has expired
if [ -n "${LIVEMEDIA_TIMEOUT}" ]; then
if [ "${timeout}" -lt "${LIVEMEDIA_TIMEOUT}" ]; then
return 1
fi
fi
# or do the scan of block devices
for sysblock in $(echo /sys/block/* | tr ' ' '\n' | egrep -v "/(loop|ram|fd)"); do
devname=$(sys2dev "${sysblock}")
[ -e "$devname" ] || continue
fstype=$(get_fstype "${devname}")
if /lib/udev/cdrom_id ${devname} > /dev/null; then
if check_dev "null" "${devname}" ; then
return 0
fi
elif is_nice_device "${sysblock}" ; then
for dev in $(subdevices "${sysblock}"); do
if check_dev "${dev}" ; then
return 0
fi
done
elif [ "${fstype}" = "squashfs" -o \
"${fstype}" = "ext4" -o \
"${fstype}" = "ext3" -o \
"${fstype}" = "ext2" -o \
"${fstype}" = "btrfs" ]; then
# This is an ugly hack situation, the block device has
# an image directly on it. It's hopefully
# casper, so take it and run with it.
ln -s "${devname}" "${devname}.${fstype}"
echo "${devname}.${fstype}"
return 0
fi
done
return 1
}
set_usplash_timeout() {
if [ -x /sbin/usplash_write ]; then
/sbin/usplash_write "TIMEOUT 120"
fi
}
start_usplash_pulse() {
if [ -x /sbin/usplash_write ]; then
/sbin/usplash_write "PULSELOGO"
fi
}
mountroot() {
exec 6>&1
exec 7>&2
exec > casper.log
exec 2>&1
tail -f casper.log >&7 &
tailpid="$!"
parse_cmdline
set_usplash_timeout
start_usplash_pulse
[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/casper-premount"
run_scripts /scripts/casper-premount
[ "$quiet" != "y" ] && log_end_msg
# Needed here too because some things (*cough* udev *cough*)
# changes the timeout
set_usplash_timeout
if [ ! -z "${NETBOOT}" ]; then
if do_netmount ; then
livefs_root="${mountpoint}"
else
panic "Unable to find a live file system on the network"
fi
else
# Scan local devices for the image
i=0
while [ "$i" -lt 60 ]; do
livefs_root=$(find_livefs $i)
if [ "${livefs_root}" ]; then
break
fi
sleep 1
i="$(($i + 1))"
done
fi
if [ -z "${livefs_root}" ]; then
panic "Unable to find a medium containing a live file system"
fi
if [ "${TORAM}" ]; then
live_dest="ram"
elif [ "${TODISK}" ]; then
live_dest="${TODISK}"
fi
if [ "${live_dest}" ]; then
log_begin_msg "Copying live_media to ${live_dest}"
copy_live_to "${livefs_root}" "${live_dest}"
log_end_msg
fi
mount_images_in_directory "${livefs_root}" "${rootmnt}"
log_end_msg
# Allow to override USERNAME and HOST based on media information
# make it skipable by setting FLAVOUR= in casper.conf
if [ -f /cdrom/.disk/info ] && [ -z "$FLAVOUR" ]; then
FLAVOUR="$(cut -d' ' -f1 "/cdrom/.disk/info" 2>/dev/null | tr '[A-Z]' '[a-z]')" || FLAVOUR=
if [ -n "$FLAVOUR" ]; then
HOST=$FLAVOUR
USERNAME=$FLAVOUR
export HOST USERNAME
sed -i "s,USERNAME=.*,USERNAME=\"$FLAVOUR\",g; s,HOST=.*,HOST=\"$FLAVOUR\",g" /etc/casper.conf
fi
fi
# unionfs-fuse needs /dev to be bind-mounted for the duration of
# casper-bottom; udev's init script will take care of things after that
if [ "${UNIONFS}" = unionfs-fuse ]; then
mount -n -o bind /dev "${rootmnt}/dev"
fi
# Open up two fifo's fd's for debconf-communicate to use. Speeds up
# the Casper process considerably.
log_begin_msg "Creating debconf-communicate fifo mechanism"
mkfifo /tmp/debconf-in.fifo
mkfifo /tmp/debconf-out.fifo
# Make the template database read-only, so that passthrough debconf
# instances can write to it directly; otherwise templates are only
# passed through when necessary. Use temporary config databases as
# well; we'll copy their contents back at the end.
DEBCONF_TMPDIR="$(chroot /root mktemp -dt debconf.XXXXXX)"
cp -a /root/var/cache/debconf/config.dat "/root$DEBCONF_TMPDIR/"
cp -a /root/var/cache/debconf/passwords.dat "/root$DEBCONF_TMPDIR/"
sed "s,^Filename: /var/cache/debconf/\(config\|passwords\).dat$,Filename: $DEBCONF_TMPDIR/\1.dat,; /^Name: templatedb/a\
Readonly: true" /root/etc/debconf.conf >"/root$DEBCONF_TMPDIR/debconf.conf"
DEBCONF_SYSTEMRC="$DEBCONF_TMPDIR/debconf.conf" chroot /root debconf-communicate -fnoninteractive casper > /tmp/debconf-out.fifo < /tmp/debconf-in.fifo &
debconfpid="$!"
if [ ! -p /tmp/debconf-in.fifo ] || [ ! -p /tmp/debconf-out.fifo ]; then
log_warning_msg "failed to setup debconf-communicate channel"
fi
log_end_msg
# Order matters!
# These file descriptors must stay open until we're finished with
# debconf-communicate.
exec 4</tmp/debconf-out.fifo 3>/tmp/debconf-in.fifo
maybe_break casper-bottom
[ "$quiet" != "y" ] && log_begin_msg "Running /scripts/casper-bottom"
run_scripts /scripts/casper-bottom
[ "$quiet" != "y" ] && log_end_msg
if [ "${UNIONFS}" = unionfs-fuse ]; then
umount "${rootmnt}/dev"
fi
# Close the fd's associated with debconf-communicate.
exec 3>&- 4<&-
rm -f /tmp/debconf-in.fifo
rm -f /tmp/debconf-out.fifo
wait $debconfpid
# Copy config database changes back to the master files.
chroot /root debconf-copydb tmpdb config \
--config=Name:tmpdb --config=Driver:File \
--config="Filename:$DEBCONF_TMPDIR/config.dat"
chroot /root debconf-copydb tmpdb passwords \
--config=Name:tmpdb --config=Driver:File \
--config="Filename:$DEBCONF_TMPDIR/passwords.dat"
rm -rf "$DEBCONF_TMPDIR"
exec 1>&6 6>&-
exec 2>&7 7>&-
kill "$tailpid"
cp casper.log "${rootmnt}/var/log/"
if [ -f /etc/casper.conf ]; then
cp /etc/casper.conf "${rootmnt}/etc/"
fi
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment