Ensure that grub-install doesn't receive emtpy command line argument
[grml2usb.git] / grml2usb
index 072f1b3..c4d178a 100755 (executable)
--- a/grml2usb
+++ b/grml2usb
@@ -103,6 +103,8 @@ parser.add_option("--quiet", dest="quiet", action="store_true",
                   help="do not output anything but just errors on console")
 parser.add_option("--remove-bootoption", dest="removeoption", action="append",
                   help="regex for removing existing bootoptions")
+parser.add_option("--rw-blockdev", dest="rwblockdev", action="store_true",
+                  help="enforce read-write mode on involved block devices")
 parser.add_option("--skip-addons", dest="skipaddons", action="store_true",
                   help="do not install /boot/addons/ files")
 parser.add_option("--skip-bootflag", dest="skipbootflag", action="store_true",
@@ -134,6 +136,12 @@ if not os.path.isdir(GRML2USB_BASE):
     GRML2USB_BASE = os.path.dirname(os.path.realpath(__file__))
 
 
+class HodorException(Exception):
+    """Throw exception if the exact error is not known and not fatal.
+
+    @Exception: message"""
+
+
 class CriticalException(Exception):
     """Throw critical exception if the exact error is not known but fatal.
 
@@ -246,6 +254,17 @@ def get_function_name(obj):
     return obj.__module__ + '.' + obj.__name__
 
 
+def set_rw(device):
+    if not options.rwblockdev:
+        return
+
+    logging.debug("executing: blockdev --setrw %s", device)
+    proc = subprocess.Popen(["blockdev", "--setrw", device])
+    proc.wait()
+    if proc.returncode != 0:
+        raise Exception("error executing blockdev on %s" % device)
+
+
 def execute(f, *exec_arguments):
     """Wrapper for executing a command. Either really executes
     the command (default) or when using --dry-run commandline option
@@ -289,8 +308,7 @@ def get_defaults_file(iso_mount, flavour, name):
     """
     bootloader_dirs = ['/boot/isolinux/', '/boot/syslinux/']
     for directory in bootloader_dirs:
-        for name in name, \
-        "%s_%s" % (get_flavour_filename(flavour), name):
+        for name in name, "%s_%s" % (get_flavour_filename(flavour), name):
             if os.path.isfile(iso_mount + directory + name):
                 return (directory, name)
     return ('', '')
@@ -356,9 +374,13 @@ def check_boot_flag(device):
     try:
         import parted
         part = get_partition_for_path(device)
+        if part is None:
+            raise HodorException("parted could not find partition")
         if part.getFlag(parted.PARTITION_BOOT):
             logging.debug("bootflag is enabled on %s" % device)
             return
+    except HodorException, e:
+        logging.info("%s, falling back to old bootflag detection", e)
     except ImportError, e:
         logging.debug("could not import parted, falling back to old bootflag detection")
 
@@ -480,8 +502,6 @@ def install_grub(device):
         device_mountpoint = tempfile.mkdtemp(prefix="grml2usb")
         register_tmpfile(device_mountpoint)
         try:
-            mount(device, device_mountpoint, "")
-
             # If using --grub-mbr then make sure we install grub in MBR instead of PBR
             if options.grubmbr:
                 logging.debug("Using option --grub-mbr ...")
@@ -489,13 +509,19 @@ def install_grub(device):
             else:
                 grub_device = device
 
+            set_rw(device)
+            mount(device, device_mountpoint, "")
+
             logging.info("Installing grub as bootloader")
-            for opt in ["", "--force"]:
-                logging.debug("grub-install --recheck %s --no-floppy --root-directory=%s %s",
-                              opt, device_mountpoint, grub_device)
-                proc = subprocess.Popen([GRUB_INSTALL, "--recheck", opt,
+            for opt in ["--", "--force"]:
+                set_rw(device)
+                set_rw(grub_device)
+                logging.debug("%s --recheck --no-floppy --target=i386-pc --root-directory=%s %s %s",
+                              GRUB_INSTALL, device_mountpoint, opt, grub_device)
+                proc = subprocess.Popen([GRUB_INSTALL, "--recheck",
                                          "--no-floppy", "--target=i386-pc",
-                                         "--root-directory=%s" % device_mountpoint, grub_device],
+                                         "--root-directory=%s" % device_mountpoint,
+                                         opt, grub_device],
                                         stdout=file(os.devnull, "r+"))
                 proc.wait()
                 if proc.returncode == 0:
@@ -503,10 +529,10 @@ def install_grub(device):
 
             if proc.returncode != 0:
                 # raise Exception("error executing grub-install")
-                logging.critical("Fatal: error executing grub-install "
-                                 "(please check the grml2usb FAQ or drop the --grub option)")
-                logging.critical("Note:  if using grub2 consider using "
-                                 "the --grub-mbr option as grub considers PBR problematic.")
+                logging.critical("Fatal: error executing grub-install " +
+                                 "(please check the grml2usb FAQ or drop the --grub option)")
+                logging.critical("Note:  if using grub2 consider using " +
+                                 "the --grub-mbr option as grub considers PBR problematic.")
                 cleanup()
                 sys.exit(1)
         except CriticalException as error:
@@ -528,6 +554,8 @@ def install_syslinux(device):
         logging.info("Would install syslinux as bootloader on %s", device)
         return 0
 
+    set_rw(device)
+
     # syslinux -d boot/isolinux /dev/sdb1
     logging.info("Installing syslinux as bootloader")
     logging.debug("syslinux -d boot/syslinux %s", device)
@@ -638,6 +666,8 @@ def install_mbr(mbrtemplate, device, partition, ismirbsdmbr=True):
     tmpf.file.write(mbrcode)
     tmpf.file.close()
 
+    set_rw(device)
+
     logging.debug("executing: dd if='%s' of='%s' bs=512 count=1 conv=notrunc", tmpf.name, device)
     proc = subprocess.Popen(["dd", "if=%s" % tmpf.name, "of=%s" % device, "bs=512", "count=1",
                              "conv=notrunc"], stderr=file(os.devnull, "r+"))
@@ -650,6 +680,8 @@ def install_mbr(mbrtemplate, device, partition, ismirbsdmbr=True):
     proc = subprocess.Popen(["sync"])
     proc.wait()
 
+    set_rw(device)
+
 
 def is_writeable(device):
     """Check if the device is writeable for the current user
@@ -658,7 +690,6 @@ def is_writeable(device):
 
     if not device:
         return False
-        #raise Exception("no device for checking write permissions")
 
     if not os.path.exists(device):
         return False
@@ -678,8 +709,8 @@ def mount(source, target, mount_options):
 
     for x in file('/proc/mounts').readlines():
         if x.startswith(source):
-            raise CriticalException("Error executing mount: %s already mounted - " % source
-                                    "please unmount before invoking grml2usb")
+            raise CriticalException("Error executing mount: %s already mounted - " % source +
+                                    "please unmount before invoking grml2usb")
 
     if os.path.isdir(source):
         logging.debug("Source %s is not a device, therefore not mounting.", source)
@@ -998,6 +1029,9 @@ def copy_addons(iso_mount, target):
     # ipxe.lkrn
     handle_addon_copy('ipxe.lkrn', addons, iso_mount)
 
+    # netboot.xyz
+    handle_addon_copy('netboot.xyz.lkrn', addons, iso_mount)
+
 
 def build_loopbackcfg(target):
     """Generate GRUB's loopback.cfg based on existing config files.
@@ -1107,9 +1141,9 @@ def copy_bootloader_files(iso_mount, target, grml_flavour):
         logging.warning("Warning: Grml releases older than 2011.12 support only one flavour in grub.")
 
     for expr in name, 'distri.cfg', \
-        defaults_file, 'grml.png', 'hd.cfg', 'isolinux.cfg', 'isolinux.bin', \
-        'isoprompt.cfg', 'options.cfg', \
-        'prompt.cfg', 'vesamenu.cfg', 'grml.png', '*.c32':
+      defaults_file, 'grml.png', 'hd.cfg', 'isolinux.cfg', 'isolinux.bin', \
+      'isoprompt.cfg', 'options.cfg', \
+      'prompt.cfg', 'vesamenu.cfg', 'grml.png', '*.c32':
         glob_and_copy(iso_mount + source_dir + expr, syslinux_target)
 
     for filename in glob.glob1(syslinux_target, "*.c32"):
@@ -1292,7 +1326,7 @@ def initial_syslinux_config(target):
 def add_entry_if_not_present(filename, entry):
     """Write entry into filename if entry is not already in the file
 
-    @filanme: name of the file
+    @filename: name of the file
     @entry: data to write to the file
     """
     data = open(filename, "a+")
@@ -1561,6 +1595,8 @@ def install_grml(mountpoint, device):
             check_for_fat(device)
             if not options.skipbootflag:
                 check_boot_flag(device)
+
+            set_rw(device)
             mount(device, device_mountpoint, ['-o', 'utf8,iocharset=iso8859-1'])
         except CriticalException as error:
             mount(device, device_mountpoint, "")
@@ -1747,14 +1783,14 @@ def check_programs():
         global GRUB_INSTALL
         GRUB_INSTALL = which("grub-install") or which("grub2-install")
         if not GRUB_INSTALL:
-            logging.critical("Fatal: grub-install not available (please install the "
-                             "grub package or drop the --grub option)")
+            logging.critical("Fatal: grub-install not available (please install the " +
+                             "grub package or drop the --grub option)")
             sys.exit(1)
 
     if options.syslinux:
         if not which("syslinux"):
-            logging.critical("Fatal: syslinux not available (please install the "
-                             "syslinux package or use the --grub option)")
+            logging.critical("Fatal: syslinux not available (please install the " +
+                             "syslinux package or use the --grub option)")
             sys.exit(1)
 
     if not which("rsync"):
@@ -1808,8 +1844,7 @@ def main():
         if not os.path.isdir(device):
             if device[-1:].isdigit():
                 if int(device[-1:]) > 4 or device[-2:].isdigit():
-                    logging.critical("Fatal: installation on partition number >4 not supported. (BIOS won't support it.)")
-                    sys.exit(1)
+                    logging.warn("Warning: installing on partition number >4, booting *might* fail depending on your system.")
 
         # provide upgrade path
         handle_compat_warning(device)
@@ -1851,5 +1886,5 @@ if __name__ == "__main__":
         logging.info("Received KeyboardInterrupt")
         cleanup()
 
-## END OF FILE #################################################################
+# END OF FILE ##################################################################
 # vim:foldmethod=indent expandtab ai ft=python tw=120 fileencoding=utf-8