Source

vasm / src / vasm / backend / bootloaders.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
#!/usr/bin/env python

#    This file is part of VASM.
#
#    VASM is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License v3 as published by
#    the Free Software Foundation.
#
#    VASM is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with VASM.  If not, see <http://www.gnu.org/licenses/>.

#   Thanks to Jason Pierce (rxMokka) for the research that went into this.

__author__ = "Moises Henriquez"
__author_email__ = "moc.liamg@xnl.E0M"[::-1]
__contributors__ = ["Jason Pierce (rxMokka)"]

import parted
import subprocess as sp
import os
import utils
import shutil
import psutil
import logging

DEFAULT_BOOTLOADER='GRUB2'
logger = logging.getLogger('vasm')
LOADER_CONFIGS={
    "GRUB2": "/boot/grub/grub.cfg",
    "LILO": "/etc/lilo.conf",
    "GRUB": "/boot/grub/menu.lst"
}

# Boot loader action constants
Install = -1
Refresh = -2

def get_current_bootsector():
    """ Returns the current partition that is currently mounted in / """
    fslist = psutil.disk_partitions()
    for fs in fslist:
        if fs.mountpoint == "/":
            return fs.device
    return None

def get_linux_boot_info(root_partition):
    """ Use linux-boot-prober to find out how to boot this OS 
    linux-boot-prober produces multiple possible ways to boot the os, so we
    must choose which one to implement.
    
    /dev/sdb1:/dev/sdb1::/boot/vmlinuz26:/boot/kernel26.img:root=/dev/sdb1
    """
    ret = {}
    proc = sp.Popen(['linux-boot-prober', root_partition], stdout=sp.PIPE, stderr=sp.PIPE)
    hits = proc.stdout.readlines()
    if len(hits) == 0: return None
    line = hits[0]
    line = line.strip()
    if ":" not in line:
        return None
    root,boot,trash,kernel,initrd,append = line.split(":")
    ret["root"] = root.strip()
    ret["kernel"] = kernel.strip()
    ret["initrd"] = initrd.strip()
    ret["append"] = append.strip()
    return ret

def find_operating_systems(include_own_root=False):
    """ This function will use os-prober and linux-boot-prober to locate
    existing operating systems.  This should only be used to generate a 
    lilo.conf file 
    
    This produces a list of strings formatted like this:
    root : Long description : Short description: os type
    /dev/sda1:VectorLinux (7.0 STD RC 1):VectorLinux:linux
    """
    proc = sp.Popen(['os-prober'], stdout=sp.PIPE, stderr=sp.PIPE)
    hits = proc.stdout.readlines()
    ret = []
    if include_own_root and os.path.exists('/boot/vmlinuz'):
        # create an entry for the running linux.
        own = Entry()
        tuientry = Entry()
        own.kernel = '/boot/vmlinuz'
        tuientry.kernel = '/boot/vmlinuz'
        own.label = "VectorLinux"
        tuientry.label = 'VectorLinux-tui'
        if os.path.exists('/boot/initrd'):
            own.initrd = '/boot/initrd'
            tuientry.initrd = '/boot/initrd'
        own.root = get_current_bootsector()
        tuientry.root = get_current_bootsector()
        own.appendline = 'splash=silent'
        tuientry.appendline = '2 splash=silent'
        ret.append(own)
        ret.append(tuientry)
    # since we only need this for lilo, we only need to read the short description
    for hit in hits:
        rootpart, long_desc, short_desc, os_type = hit.strip().split(":")
        OS = Entry()
        if short_desc.strip().startswith("Vector"):
            short_desc = "Vector-%s"% rootpart.split("/")[-1]
        OS.label = short_desc.strip()
        if os_type.strip().lower() in ("linux",):
            os._ostype = "linux"
            bootinfo = get_linux_boot_info(rootpart.strip())
            if bootinfo is None: continue
            OS.root = bootinfo["root"] or rootpart.strip()
            OS.kernel = bootinfo["kernel"].strip()
            OS.initrd = bootinfo["initrd"].strip()
            OS.appendline = bootinfo["append"].strip()
        elif "windows" or "microsoft" in os_type_strip().lower():
            OS.root = rootpart.strip()
            OS.label = "Windows-%s"% roorpart.strip().splir("/")[-1]
            OS._ostype = "windows"
            # FIXME: ^^ This needs testing.

        ret.append(OS)

    return ret
    
def get_vga_mode(resolution="800x600", quality="med", grub2=False):
    """ Return a numeric vga mode that can be used in lilo.conf based on 
    the values provided for resolution and quality"""
    val = "nornal"
    values = {
        "640x480" : {
            "low" : "769",
            "med" : "784",
            "high" : "785"},
        "800x600" : {
            "low" : "771",
            "med" : "787",
            "high" : "788"},
        "1024x768" : {
            "low" : "773",
            "med" : "790", 
            "high" : "791"},
        "1280x1024": {
            "high":"794",
            "med":"793",
            "low":"775"}
        }
    grub2values = {
        "640x480":"640x480x16",
        "800x600": "800x600x16",
        "1024x768":"1024x768x16",
        "1280x1024":"1280x1024x16",
        }
    if grub2 is False:
        return values[resolution][quality] or val
    else:
        return grub2values[resolution] or grub2values["800x600"]
    
    

class LiloDotConf(object):
    """ represents a complete lilo.conf file. """
    def __init__(self, target="", default="", 
                timeout_value=0, vga_value="nornal", include_running_os=False):
        self.timeout_value = timeout_value
        self.vga_value = vga_value
        self.target = target
        self.boot_default = default
        self._include_running_os = include_running_os
    
    def set_target(self, value):
        """ Set the target value on the configuration file """
        self.target = value
        return
    
    def set_default_os(self, value):
        """ set the default OS on the configuration file """
        self.boot_default = value
        return
    
    def getOsListing(self, oslist=None):
        """ Returns the os listing for lilo.conf as a list of strings """
        if oslist is None:
            oslist = find_operating_systems(self._include_running_os)
        lilo_root = get_current_bootsector() # this returns whatever partition is mounted @ /
        ret = []
        spacer = " "*4
        
        for entry in oslist:
            ret.append("# -- %s on %s -- "% (entry.label, entry.root))
            if entry._ostype == 'linux':
                ret.append("image = %s"% entry.kernel)
                ret.append("%s root = %s"% (spacer, entry.root))
                if entry.root != lilo_root:
                    ret.append("%s label = %s"% (spacer, entry.label))
                else:
                    if entry.label.endswith('-tui'):
                        ret.append("%s label = %s"% (spacer, entry.label))
                    else:
                        ret.append("%s label = VectorLinux"% spacer)
                if entry.initrd not in ("",None):
                    ret.append("%s initrd = %s"% (spacer, entry.initrd))
                if entry.appendline not in ("", None):
                    if "splash" not in entry.appendline:
                        ret.append("%s append = \"%s splash=silent\""% (spacer, entry.appendline))
                    else:
                        ret.append("%s append = \"%s\""% (spacer, entry.appendline))
                ret.append("%s read-only"% spacer)
                ret.append("#")
                ret.append("#")
                ret.append("# -- End of listing for %s on %s -- "% (entry.label, entry.root))
                ret.append("#")
            elif entry._ostype == 'windows':
                ret.append("%s other = %s"% (spacer, entry.root))
                ret.append("%s label = %s"% (spacer, entry.label))
                ret.append("%s table = %s"% (spacer, entry.root))

            
        # Add some trailing text
        ret.append("#")
        ret.append("# ------------------------------------ #")
        ret.append("# ------- END OF OS LISTING ---------- #")
        ret.append("# ------------------------------------ #\n\n")
        
        return ret
    
    def getHeader(self):
        """ Returns the header of the file as a list of strings """
        ret = [
        "# LILO configuration file.",
        "# ",
        "# Generated by VASM.",
        "# ",
        "boot = %s"% self.target,
        "compact",
        "prompt",
        "timeout = %s"% str(self.timeout_value),
        "# Override dangerous defaults that re-order the partition tables:",
        "change-rules",
        " reset",
        "bitmap = /boot/bitmap/boot.bmp",
        "# default vga mode",
        "vga = %s"% str(self.vga_value),
        "# ",
        "# VGA mode definitions ",
        "# -------------------------- #",
        "# VESA framebuffer console @ 1024x768x64k",
        "# vga=791",
        "# VESA framebuffer console @ 1024x768x32k",
        "# vga=790",
        "# VESA framebuffer console @ 1024x768x256",
        "# vga=773",
        "# VESA framebuffer console @ 800x600x64k",
        "# vga=788",
        "# VESA framebuffer console @ 800x600x32k",
        "# vga=787",
        "# VESA framebuffer console @ 800x600x256",
        "# vga=771",
        "# VESA framebuffer console @ 640x480x64k",
        "# vga=785",
        "# VESA framebuffer console @ 640x480x32k",
        "# vga=784",
        "# VESA framebuffer console @ 640x480x256",
        "# vga=769",
        "# --------------------------------------- #",
        "# --------- START OS LISTING ------------ #",
        "# --------------------------------------- #",
        ]
        return ret

    def set_timeout(self, value):
        """ Set timeout value on the configuration file """
        # lilo wants it in thenths of a second
        self.timeout_value = int(value) * 10
        return
    
    def set_vga_value(self, value):
        self.vga_value = value
        return
    


class MBR(object):
    """ MBR object to be scanned for boot loaders """
    def __init__(self, drive):
        """ Arguments:
            drive = some drive path like '/dev/sda' """
        self.drive = drive

    def read_bootloader(self):
        """ Read the first 2 bytes to see what bootloader is there """
        f = open(self.drive, 'r')
        data = f.read(2)
        f.close()
        if not data:
            return None
        elif data == "\xEB\x63":
            return "GRUB2"
        elif data == "\xEB\x48":
            return "GRUB"
        elif data == "\xFA\xEB":
            return "LILO"
        
        return None

# we still dont know which bootloader is active.  we only know how to read what's in the MBR.
def get_active_bootloader():
    """ Reads each MBR to see what's in there, and if it finds a bootloader
    it will test to see if a config file for that loader exists.  If both of these
    are true, then we know which menu we are using. """
    devs = [dev for dev in parted.getAllDevices() if dev.getSize() > 0]
    for dev in devs:
        mbr = MBR(dev.path)
        loader = mbr.read_bootloader()
        if loader is not None:
            if LOADER_CONFIGS.has_key(loader):
                if os.path.exists(LOADER_CONFIGS[loader]):
                    return loader
    # Return the default bootloader if nothing else.
    return DEFAULT_BOOTLOADER

class Entry(object):
    def __init__(self):
        self.label = ""
        self._ostype = 'linux'

class BootLoader(object):
    def __init__(self,
        target="", timeout=5, vga_size="800x600", vga_quality="med"):
        self.timeout = timeout
        self.target=target
        self.vga_size = vga_size
        self.vga_quality = vga_quality
        self.vga_mode = ""
        self.type = "undefined"
    
    def set_timeout(self, value):
        self.timout = timeout
    
    def set_target(self, value):
        self.target = value
    
    def set_vga_mode(self, value):
        """ Method to set the vga mode """
        pass
    
    def save_config(self):
        """ Common method to save the configuration """
        pass
    
    def refresh_menu(self):
        """common method to refresh the bootloader boot menu """
        pass
    
    def install(self):
        """ common method to install the bootloader to the target """
        pass

class LILO(BootLoader):
    def __init__(self, target, timeout, vga_size, vga_quality, include_running_os=False):
        BootLoader.__init__(self,target, timeout, vga_size, vga_quality)
        self.type = "LiLO"
        self.config = LiloDotConf(include_running_os)
        self._include_running_os=include_running_os

    def set_vga_mode(self):
        self.vga_mode = get_vga_mode(self.vga_size, self.vga_quality, False)
    
    def save_config(self):
        """ save the lilo configuration.
        lilo just saves the generated config file to /etc/lilo.conf"""
        logger.info("Generating lilo.conf")
        configpath = LOADER_CONFIGS["LILO"]
        config = self.config
        # we want to setup the variables in the config.
        config.set_target(self.target)
        config.set_timeout(self.timeout)
        # set the correct vga mode
        self.set_vga_mode()
        config.set_vga_value(self.vga_mode)
        
        # generate the contents of the config file.
        data = config.getHeader()
        # Generate a list of Entry objects where we can check if the initrd
        # and kernels exist.
        OsList = find_operating_systems(self._include_running_os)
        # we need to make sure the paths to the kernels and initrds are relative
        # to lilo's /boot.  This may require some file copying.
        data.extend(self.prepare_os_list(OsList))
        #badOsList = config.getOsListing()
        # fix the os listing
        
        # make a backup of the file
        if os.path.exists(configpath):
            bkfile = "%s.bak"%configpath
            try:
                shutil.copy2(configpath,bkfile)
            except:
                # exit if we can't make a backup copy of lilo.conf
                return 1
        f = open(configpath, "w")
        f.writelines("\n".join(data))
        f.close()
        return 0

    def _copy_kernel(self, root, mntpoint, kname):
        """ copy kname from root/boot to /boot/tamu """
        # root must be a mountpoint
        oldpath = os.path.join(mntpoint, "boot", kname)
        host = os.path.split(root)[-1]
        fname = "%s_%s"% (kname, host)
        newpath = os.path.join("/boot", "tamu", fname)
        if os.path.exists(newpath):
            return newpath            
        try:
            shutil.copy2(oldpath, newpath)
            logger.debug("copied %s to %s "% (oldpath, newpath))
            return newpath
        except:
            logger.warning("Unable to find initrd for %s on %s"% (kname, root))
            return None

    def _check_if_premounted(self, partition, premountlist):
        """ Check if partition was part of the partitions that were
        originally mounted (specified in premountlist)"""
        for p in premountlist:
            if p.device == partition:
                return True
        return False

    def get_partition_mountpoint(self, device, mountlist):
        for item in mountlist:
            if item.device == device:
                return item.mountpoint
        return None
    
    def prepare_os_list(self, object_list):
        """ Copy kernels and initrd's from other Os's /boot to lilos /boot/tamu """
        # before we do anything, take a snapshot of the system to see
        # which partitions are now mounted
        mountlist = psutil.disk_partitions()
        try:
            os.makedirs("/boot/tamu")
        except:
            pass
        lilo_root = utils.get_mounted("/").strip()
        for entry in object_list:
            has_initrd = False
            entry.root = entry.root.strip()
            kname = os.path.split(entry.kernel.strip())[-1]
            if entry.initrd is not None and entry.initrd is not "":
                has_initrd = True
                rdname = os.path.split(entry.initrd.strip())[-1]
            if entry.root != lilo_root:
                # kernel should be in /boot/tamu.
                mpoint = entry.root.replace("/dev/", "/mnt/")
                kpath = os.path.join("/boot", "tamu", kname)
                if not os.path.exists(kpath):
                    if not self._check_if_premounted(entry.root, mountlist):
                        # mount the partition
                        mount = utils.mount(entry.root, mpoint)
                    else:
                        mpoint = self.get_partition_mountpoint(entry.root, mountlist)
                        assert mpoint is not None, \
                            "Unable to get mountpoint for mounted partition %s"% entry.root
                    # copy the kernel now
                    entry.kernel = self._copy_kernel(entry.root, mpoint, kname)
                    
                    # if the kernel was not there, the initrd is most likely not either.
                    if has_initrd:
                        entry.initrd = self._copy_kernel(entry.root, mpoint, rdname)
                    # umount if necesssary
                    if not self._check_if_premounted(entry.root, mountlist):
                        utils.umount(mpoint)
        return self.config.getOsListing(object_list)

    def install(self):
        """ lilo requires you to setup the config file before installation """
        self.save_config()
        return self._do_install()
    
    def _do_install(self):
        """ install the boot loader.  Return the value ($?) of running `lilo` """
        logger.info("Writing lilo to %s"% self.target)
        proc = sp.Popen(["lilo"], stdout=sp.PIPE, stderr=sp.PIPE)
        output = proc.communicate()[1]
        code = proc.returncode
        assert code == 0, output
        logger.info("Lilo was installed to %s"% self.target)
    
    def refresh_menu(self):
        """ Procedure to refresh the menu """
        return self.install()
    

class GRUB2(BootLoader):
    def __init__(self, target, timeout, vga_size, vga_quality):
        BootLoader.__init__(self, target, timeout, vga_size, vga_quality)
        self.configpath = "/etc/default/grub"
        self.type = "GRUB2"
        self.timeout = str(int(timeout))
        self.set_vga_mode()
    
    def set_vga_mode(self):
        self.vga_mode = get_vga_mode(self.vga_size, self.vga_quality, True)

    def _do_install(self):
        """ Install grub to the target and give it a menu """
        logger.info("Installing grub2 to %s"% self.target)
        proc = utils.get_popen(["grub-install", "--no-floppy", self.target])
        err = proc.communicate()[1]
        code = proc.returncode
        assert code == 0, err
        logger.info("Grub2 was installed to %s"% self.target)

    def install(self):
        """ install the bootloader and give it its configuration """
        ret = self._do_install()
        return ret

    def refresh_menu(self):
        """ Refresh the grub2 boot menu """
        return self.save_config()
    
    def save_config(self):
        """ The grub2 config file is automatically generated, so we use
        this method to save the values to /etc/default/grub which is 
        parsed while the config file is generated """
        f = open(self.configpath, "r")
        data = f.readlines()
        f.close()
        ndata = []
        # set the correct vga_mode value
        self.set_vga_mode()
        
        vgaline = False
        timeoutline = False
        # check to make sure the file has the variables we need to set
        for line in data:
            if "GRUB_GFXMODE=" in line:
                vgaline = True
            elif "GRUB_TIMEOUT=" in line:
                timeoutline = True
        
        # Add the lines if we dont have them
        if vgaline is False:
            data.append("GRUB_GFXMODE=\n")
        if timeoutline is False:
            data.append("GRUB_TIMEOUT=\n")
        # save the variables.
        for line in data:
            if "GRUB_GFXMODE=" in line:
                line = "GRUB_GFXMODE=%s\n"% str(self.vga_mode)
            elif "GRUB_TIMEOUT=" in line:
                line = "GRUB_TIMEOUT=%s\n"% str(int(self.timeout))
            ndata.append(line)
        # make a backup copy of the file
        bk = "%s.bak"% (self.configpath)
        logger.debug("Saving backup copy of %s to %s"% (self.configpath, bk))
        try:
            shutil.copy2(self.configpath, bk)
        except:
            # exit with a 1 value if we can't save this file
            logger.fatal("Unable to save backup copy of %s"% self.configpath)
            return 1
        # save the new file
        logger.debug("Saving new changes to %s"% self.configpath)
        f = open(self.configpath, "w")
        f.writelines("".join(ndata))
        f.close()
        
        # after these are set, we just need to run grub-mkconfig
        logger.info("Updating grub2 boot menu.")
        proc = utils.get_popen(["grub-mkconfig", "-o", LOADER_CONFIGS["GRUB2"]])
        err = proc.communicate()[1]
        code = proc.returncode
        assert code == 0, err
        logger.info("Grub2 menu was updated.")


class GrubCFG(object):
    """ Parse a grub.cfg file to expose the menu entries as objects """
    def __init__(self):
        fpath = LOADER_CONFIGS["GRUB2"]
        f = open(fpath, 'r')
        self.data = f.readlines()
        f.close()
    
    def get_menu_entries(self):
        res = []
        i = 0
        for line in self.data:
            i = i + 1
            if line.startswith("menuentry"):
                # set the start marker
                sm = i
                entry = Entry()
                start, label, garbage = line.split("\"")
                entry.label = label
                # Loop through the next 10 lines to find the rest of the data
                for x in range(sm, (sm + 10)):
                    _line = self.data[x].strip()
                    if _line.startswith("linux"):
                        start, kernel, rootdev, append = _line.replace("\t", " ").split(" ", 3)
                        entry.kernel = kernel
                        entry.root = rootdev.split('=')[1]
                        entry.append = append
                    elif _line.startswith("initrd"):
                        start, initrdpath = _line.replace("\t", " ").split(" ", 1)
                        entry.initrd = initrdpath
                    elif _line.startswith("}"):
                        break
                res.append(entry)
        return res