summaryrefslogtreecommitdiffstats
path: root/liveusb/creator.py
blob: b8fe44fffa90953d561b76d0430e102e663fb699 (plain)
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
# -*- coding: utf-8 -*-
#
# Copyright © 2008-2013  Red Hat, Inc. All rights reserved.
# Copyright © 2008-2013  Luke Macken <lmacken@redhat.com>
#
# This copyrighted material is made available to anyone wishing to use, modify,
# copy, or redistribute it subject to the terms and conditions of the GNU
# General Public License v.2.  This program is distributed in the hope that it
# will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the
# implied warranties 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 this program; if
# not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
# Floor, Boston, MA 02110-1301, USA. Any Red Hat trademarks that are
# incorporated in the source code or documentation are not subject to the GNU
# General Public License and may only be used or replicated with the express
# permission of Red Hat, Inc.

"""
Our main LiveUSBCreator module.

This contains the LiveUSBCreator parent class, which is an abstract interface
that provides platform-independent methods.  Platform specific implementations
include the LinuxLiveUSBCreator and the WindowsLiveUSBCreator.
"""

import subprocess
import tempfile
import logging
import hashlib
import shutil
import signal
import time
import os
import platform
import re
import stat
import sys

from StringIO import StringIO
from datetime import datetime
from pprint import pformat

if 'linux' in sys.platform:
    from gi.repository import UDisks, GLib

from liveusb.utils import (_move_if_exists, _unlink_if_exists, unicode_to_utf8,
                           unicode_to_filesystemencoding,
                           _set_liberal_perms_recursive, underlying_physical_device,
                           get_open_write_fd, write_to_block_device)
from liveusb import _
from liveusb.config import config
from liveusb.source import SourceError

#XXX: size should be configurable
SYSTEM_PARTITION_FLAGS = [ 0,    # system partition
                           2,    # legacy BIOS bootable
                           60,   # read-only
                           62,   # hidden
                           63    # do not automount
                         ]
# EFI System Partition
ESP_GUID = 'C12A7328-F81F-11D2-BA4B-00A0C93EC93B'

class LiveUSBError(Exception):
    """ A generic error message that is thrown by the LiveUSBCreator """


class LiveUSBCreator(object):
    """ An OS-independent parent class for Live USB Creators """

    system_partition_size = config['min_system_partition_size'] # MiB
    min_persistence_partition_size = config['min_persistence_partition_size'] # MiB
    source = None       # the object representing our live source image
    label = config['branding']['partition_label'] # if one doesn't already exist
    fstype = None       # the format of our usb stick
    drives = {}         # {device: {'label': label, 'mount': mountpoint}}
    overlay = 0         # size in mb of our persisten overlay
    dest = None         # the mount point of of our selected drive
    uuid = None         # the uuid of our selected drive
    pids = []           # a list of pids of all of our subprocesses
    output = StringIO() # log subprocess output in case of errors
    totalsize = 0       # the total size of our overlay + iso
    _drive = None       # mountpoint of the currently selected drive
    mb_per_sec = 0      # how many megabytes per second we can write
    log = None
    ext_fstypes = set(['ext2', 'ext3', 'ext4'])
    valid_fstypes = set(['vfat', 'msdos']) | ext_fstypes

    drive = property(fget=lambda self: self.drives[self._drive],
	                     fset=lambda self, d: self._set_drive(d))

    def __init__(self, opts):
        self.opts = opts
        import sys
        if sys.platform != "win32" and not opts.unprivileged:
            if os.getuid() != 0:
                print >> sys.stderr, _("You must run this application as root")
                sys.exit(1)
        self._setup_logger()

    def _setup_logger(self):
        self.log = logging.getLogger()
        self.log.setLevel(logging.DEBUG if self.opts.verbose else logging.INFO)
        self.handler = logging.StreamHandler()
        formatter = logging.Formatter("[%(filename)s:%(lineno)s (%(funcName)s)] %(levelname)s: %(message)s")
        self.handler.setFormatter(formatter)
        self.log.addHandler(self.handler)

    def detect_supported_drives(self, callback=None):
        """ This method should populate self.drives with supported devices """
        raise NotImplementedError

    def verify_filesystem(self):
        """
        Verify the filesystem of our device, setting the volume label
        if necessary.  If something is not right, this method throws a
        LiveUSBError.
        """
        raise NotImplementedError

    def get_free_bytes(self, drive=None):
        """ Return the number of free bytes on a given drive.

        If drive is None, then use the currently selected device.
        """
        raise NotImplementedError

    def verify_iso_md5(self):
        """ Verify the ISO md5sum.
        """
        if not self.source.supports_verify_md5:
            self.log.info(_('Source type does not support verification of ISO MD5 checksum, skipping'))
            return True
        self.log.info(_('Verifying ISO MD5 checksum'))
        try:
            self.source.verify_md5()
        except SourceError, e:
            self.log.exception(e)
            self.log.info(_('ISO MD5 checksum verification failed'))
            return False
        self.log.info(_('ISO MD5 checksum passed'))
        return True

    def extract_iso(self):
        """ Extract our ISO with 7-zip directly to the USB key """
        self.log.info(_("Extracting live image to the target device..."))
        start = datetime.now()
        self.source.clone(self.dest)
        delta = datetime.now() - start
        if delta.seconds:
            self.mb_per_sec = (self.source.size / delta.seconds) / 1024**2
            if self.mb_per_sec:
                self.log.info(_("Wrote to device at %(speed)d MB/sec") % {'speed': self.mb_per_sec})

    def syslinux_options(self):
        opts = []
        if self.opts.force:
            opts.append('-f')
        if self.opts.safe:
            opts.append('-s')
        return opts

    def install_bootloader(self):
        """ Install the bootloader to our device.

        Platform-specific classes inheriting from the LiveUSBCreator are
        expected to implement this method to install the bootloader to the
        specified device using syslinux.  This specific implemention is
        platform independent and performs sanity checking along with adding
        OLPC support.
        """
        if self.opts.xo:
            self.setup_olpc()

    def setup_olpc(self):
        """ Install the Open Firmware configuration for the OLPC.

        This method will make the selected device bootable on the OLPC.  It
        does this by installing a /boot/olpc.fth open firmware configuration
        file that enables booting off of USB and SD cards on the XO.
        """
        from liveusb.olpc import ofw_config
        self.log.info(_('Setting up OLPC boot file...'))
        args = self.get_kernel_args()
        if not os.path.exists(self.get_liveos_file_path('boot')):
            os.mkdir(self.get_liveos_file_path('boot'))
        olpc_cfg = file(self.get_liveos_file_path('boot', 'olpc.fth'), 'w')
        olpc_cfg.write(ofw_config % ' '.join(args))
        olpc_cfg.close()
        self.log.debug('Wrote %s' % olpc_cfg.name)

    def get_kernel_args(self):
        """ Grab the kernel arguments from our syslinux configuration """
        args = []
        cfg = file(self.get_liveos_file_path('isolinux', 'syslinux.cfg'))
        for line in cfg.readlines():
            if 'append' in line:
                args.extend([arg for arg in line.split()[1:]
                             if not arg.startswith('initrd')])
                break
        cfg.close()
        return args

    def terminate(self):
        """ Terminate any subprocesses that we have spawned """
        raise NotImplementedError

    def mount_device(self):
        """ Mount self.drive, setting the mount point to self.mount """
        raise NotImplementedError

    def unmount_device(self):
        """ Unmount the device mounted at self.mount """
        raise NotImplementedError

    def _set_partition_flags(self, partition, flags):
        flags_total = 0
        for flag in flags:
            flags_total |= (1<<flag)
        partition.call_set_flags_sync(flags_total,
                                      GLib.Variant('a{sv}', None),
                                      None)

    def partition_device(self):
        """ Partition device listed at self.drive """
        raise NotImplementedError

    def update_system_partition_properties(self):
        cmd = (  [ '/sbin/sgdisk' ]
               + [ '--typecode=1:%s' % ESP_GUID ]
               + [ self.drive['parent'] ])
        self.popen(cmd, shell=False)

    def _gdisk_script(self, gdisk_cmds):
        cmd = [ '/sbin/gdisk', self.drive['device'] ]
        stdin = tempfile.TemporaryFile(mode='w')
        stdin.write('\n'.join(gdisk_cmds) + '\n')
        stdin.seek(0)
        self.popen(cmd, shell=False, stdin=stdin)

    def create_hybrid_mbr(self):
        # only relevant with OS that don't know how to access partitions on GPT
        self._gdisk_script([ 'r',   # recovery and transformation options
                             'h',   # make hybrid MBR
                             '1',   # add first partition
                             'N',   # no EFI GPT (0xEE) partition
                             '0c',  # partition type (Win95 FAT32 LBA)
                             'N',   # don't set the bootable flag
                             'N',   # no protective partition
                             'w',   # write table to disk and exit
                             'Y',   # proceed, possibly destroying data
                           ])
        self.flush_buffers(silent=True)
        time.sleep(3)
        self._get_object().props.block.call_rescan_sync(GLib.Variant('a{sv}', None))

    def remove_hybrid_mbr(self):
        self._gdisk_script([ 'x',   # extra functionality
                             'n',   # create a new protective MBR
                             'w',   # write table to disk and exit
                             'Y',   # proceed, possibly destroying data
                           ])

    def is_device_big_enough(self, deviceSize):
        if (self.system_partition_size + self.min_persistence_partition_size) \
                * 1024**2 <= deviceSize:
            return True
        return False

    def can_read_partition_table(self, device=None):
        if not device:
            device = self.drive['device']

        proc = self.popen(['/sbin/sgdisk', '--print', device], shell=False, passive=True)
        if proc.returncode:
            return False
        return True

    def clear_all_partition_tables(self, device=None):
        if not device:
            device = self.drive['device']

        # We need to ignore errors because sgdisk returns error code
        # 2 when it successfully zaps partition tables it cannot
        # understand... while we want to make it do this reset
        # precisely to fix that unreadable partition table issue.
        # Chicken'n'egg, right.
        self.popen(['/sbin/sgdisk', '--zap-all', device],
                   shell=False, passive=True)

    def switch_drive_to_system_partition(self):
        pass

    def switch_back_to_full_drive(self):
        pass

    def popen(self, cmd, passive=False, ret='proc', **user_kwargs):
        """ A wrapper method for running subprocesses.

        This method handles logging of the command and it's output, and keeps
        track of the pids in case we need to kill them.  If something goes
        wrong, an error log is written out and a LiveUSBError is thrown.

        @param cmd: The commandline to execute.  Either a string or a list.
        @param passive: Enable passive process failure.
        @param kwargs: Extra arguments to pass to subprocess.Popen
        """
        if isinstance(cmd, list):
            cmd_decoded = u' '.join(cmd)
            cmd_bytes = [ unicode_to_filesystemencoding(el) for el in cmd ]
        else:
            cmd_decoded = cmd
            cmd_bytes = unicode_to_filesystemencoding(cmd)
        self.log.debug(cmd_decoded)
        self.output.write(cmd_bytes)
        kwargs = { 'shell': True, 'stdin': subprocess.PIPE }
        kwargs.update(user_kwargs)
        proc = subprocess.Popen(cmd_bytes, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                **kwargs)
        self.pids.append(proc.pid)
        out, err = proc.communicate()
        out = unicode_to_utf8(out)
        err = unicode_to_utf8(err)
        self.output.write(out + '\n' + err + '\n')
        if proc.returncode:
            filename = self.write_log()
            if not passive:
                raise LiveUSBError(_(
                        "There was a problem executing the following command: `%(command)s`.\nA more detailed error log has been written to '%(filename)s'.")
                        % {'command': cmd_decoded, 'filename': filename})
        if ret == 'stdout':
            return out
        return proc

    def verify_iso_sha1(self, progress=None):
        """ Verify the SHA1 checksum of our ISO if it is in our release list """
        if not self.source.supports_verify_sha1:
            return True
        if not progress:
            class DummyProgress:
                def set_max_progress(self, value): pass
                def update_progress(self, value): pass
            progress = DummyProgress()
        release = self.source.get_release()
        if release:
            progress.set_max_progress(self.source.size / 1024)
            if 'sha1' in release:
                self.log.info(_("Verifying SHA1 checksum of LiveCD image..."))
                hash = 'sha1'
                checksum = hashlib.sha1()
            elif 'sha256' in release:
                self.log.info(_("Verifying SHA256 checksum of LiveCD image..."))
                hash = 'sha256'
                checksum = hashlib.sha256()
            isofile = file(self.source.path, 'rb')
            bytes = 1024**2
            total = 0
            while bytes:
                data = isofile.read(bytes)
                checksum.update(data)
                bytes = len(data)
                total += bytes
                progress.update_progress(total / 1024)
            isofile.close()
            if checksum.hexdigest() == release[hash]:
                return True
            else:
                self.log.info(_("Error: The SHA1 of your Live CD is "
                                "invalid.  You can run this program with "
                                "the --noverify argument to bypass this "
                                "verification check."))
                return False
        else:
            self.log.debug(_('Unknown ISO, skipping checksum verification'))

    def check_free_space(self):
        """ Make sure there is enough space for the LiveOS and overlay """
        freebytes = self.get_free_bytes()
        self.log.debug('freebytes = %d' % freebytes)
        self.log.debug('source size = %d' % self.source.size)
        overlaysize = self.overlay * 1024**2
        self.log.debug('overlaysize = %d' % overlaysize)
        self.totalsize = overlaysize + self.source.size
        if self.totalsize > freebytes:
            raise LiveUSBError(_("Not enough free space on device." +
                                 "\n%dMB ISO + %dMB overlay > %dMB free space") %
                                 (self.source.size/1024**2, self.overlay,
                                  freebytes/1024**2))

    def create_persistent_overlay(self):
        if self.overlay:
            self.log.info(_("Creating %sMB persistent overlay") % self.overlay)
            if self.fstype == 'vfat':
                # vfat apparently can't handle sparse files
                self.popen('dd if=/dev/zero of="%s" count=%d bs=1M'
                           % (self.get_overlay(), self.overlay))
            else:
                self.popen('dd if=/dev/zero of="%s" count=1 bs=1M seek=%d'
                           % (self.get_overlay(), self.overlay))

    def _update_configs(self, infile, outfile):
        outfile_new = "%s.new" % outfile
        shutil.copy(infile, outfile_new)
        infile = file(infile, 'r')
        outfile_new = file(outfile_new, 'w')
        usblabel = self.uuid and 'UUID=' + self.uuid or 'LABEL=' + self.label
        for line in infile.readlines():
            line = re.sub('/isolinux/', '/syslinux/', line)
            if "CDLABEL" in line:
                line = re.sub("CDLABEL=[^ ]*", usblabel, line)
                line = re.sub("rootfstype=[^ ]*",
                              "rootfstype=%s" % self.fstype,
                              line)
            if self.overlay and "liveimg" in line:
                line = line.replace("liveimg", "liveimg overlay=" + usblabel)
                line = line.replace(" ro ", " rw ")
            if self.opts.kernel_args:
                line = line.replace("liveimg", "liveimg %s" %
                                    ' '.join(self.opts.kernel_args.split(',')))
            outfile_new.write(line)
        infile.close()
        outfile_new.close()
        shutil.move(outfile_new.name, outfile)

    def update_configs(self):
        """ Generate our syslinux.cfg and grub.conf files """
        grubconf     = self.get_liveos_file_path("EFI", "BOOT", "grub.conf")
        bootconf     = self.get_liveos_file_path("EFI", "BOOT", "boot.conf")
        bootx64conf  = self.get_liveos_file_path("EFI", "BOOT", "bootx64.conf")
        bootia32conf = self.get_liveos_file_path("EFI", "BOOT", "bootia32.conf")
        updates = [(self.get_liveos_file_path("isolinux", "isolinux.cfg"),
                    self.get_liveos_file_path("isolinux", "syslinux.cfg")),
                   (self.get_liveos_file_path("isolinux", "stdmenu.cfg"),
                    self.get_liveos_file_path("isolinux", "stdmenu.cfg")),
                   (self.get_liveos_file_path("isolinux", "exithelp.cfg"),
                    self.get_liveos_file_path("isolinux", "exithelp.cfg")),
                   (self.get_liveos_file_path("EFI", "BOOT", "isolinux.cfg"),
                    self.get_liveos_file_path("EFI", "BOOT", "syslinux.cfg")),
                   (grubconf, bootconf)]
        copies = [(bootconf, grubconf),
                  (bootconf, bootx64conf),
                  (bootconf, bootia32conf)]

        for (infile, outfile) in updates:
            if os.path.exists(infile):
                self._update_configs(infile, outfile)
        # only copy/overwrite files we had originally started with
        for (infile, outfile) in copies:
            if os.path.exists(outfile):
                try:
                    shutil.copyfile(infile, outfile)
                except Exception, e:
                    self.log.warning(_("Unable to copy %(infile)s to %(outfile)s: %(message)s")
                                     % {'infile': infile,
                                        'outfile': outfile,
                                        'message': str(e)})

        syslinux_path = self.get_liveos_file_path("syslinux")
        _move_if_exists(self.get_liveos_file_path("isolinux"), syslinux_path)
        _unlink_if_exists(os.path.join(syslinux_path, "isolinux.cfg"))

    def delete_liveos(self):
        """ Delete the files installed by the existing Live OS, after
        chmod'ing them since Python for Windows is unable to delete
        read-only files.
        """
        self.log.info(_('Removing existing Live OS'))
        for path in self.get_liveos_toplevel_files(absolute=True):
            if not os.path.exists(path):
                continue
            self.log.debug("Considering " + path)
            if os.path.isfile(path):
                try:
                    os.chmod(path, 0644)
                except OSError, e:
                    self.log.debug(_("Unable to chmod %(file)s: %(message)s") % {'file': path, 'message': str(e)})
                try:
                    os.unlink(path)
                except:
                    raise LiveUSBError(_("Unable to remove file from"
                                         " previous LiveOS: %(message)s")
                                         % {'message': str(e)})
            elif os.path.isdir(path):
                try:
                    _set_liberal_perms_recursive(path)
                except OSError, e:
                    self.log.debug(_("Unable to chmod %(file)s: %(message)s")
                                   % {'file': path, 'message': str(e)})
                try:
                    shutil.rmtree(path)
                except OSError, e:
                    raise LiveUSBError(_("Unable to remove directory from"
                                         " previous LiveOS: %(message)s")
                                         % {'message': str(e)})

    def write_log(self):
        """ Write out our subprocess stdout/stderr to a log file """
        tmpdir = os.getenv('TEMP', '/tmp')
        filename = os.path.join(tmpdir, 'liveusb-creator.log')
        out = file(filename, 'a')
        out.write(self.output.getvalue())
        out.close()
        return unicode(filename)


    def get_liveos(self):
        return self.get_liveos_file_path(config['main_liveos_dir'])

    def running_liveos_mountpoint(self):
        return config['running_liveos_mountpoint']

    def get_liveos_file_path(self, *args):
        """ Given a path relative to the root of the Live OS filesystem,
        returns the absolute path to it from the perspective of the system
        liveusb-creator is running on.
        """
        return os.path.join(self.dest + os.path.sep, *args)

    def get_liveos_toplevel_files(self, absolute=False):
        """ Returns the list of files install at top level in the Live
        OS filesystem.
        If absolute=True, return absolute paths from the perspective
        of the system liveusb-creator is running on; else, return paths
        relative to the root of the Live OS filesystem.
        """
        toplevels = config['liveos_toplevel_files']
        if absolute:
            return [ self.get_liveos_file_path(f) for f in toplevels ]
        return toplevels

    def existing_overlay(self):
        return os.path.exists(self.get_overlay())

    def get_overlay(self):
        return os.path.join(self.get_liveos(),
                            'overlay-%s-%s' % (self.label, self.uuid or ''))

    def _set_drive(self, drive):
        # XXX: sometimes fails with:
        # Traceback (most recent call last):
        #  File "liveusb-creator/git/liveusb/gui.py", line 200, in run
        #    self.live.switch_drive_to_system_partition()
        #  File "liveusb-creator/git/liveusb/creator.py", line 967, in switch_drive_to_system_partition
        #    self.drive = '%s%s' % (full_drive_name, append)
        #  File "liveusb-creator/git/liveusb/creator.py", line 88, in <lambda>
        #    fset=lambda self, d: self._set_drive(d))
        #  File "liveusb-creator/git/liveusb/creator.py", line 553, in _set_drive
        #    raise LiveUSBError(_("Cannot find device %s") % drive)
        if not self.drives.has_key(drive):
            raise LiveUSBError(_("Cannot find device %s") % drive)
        self.log.debug("%s selected: %s" % (drive, self.drives[drive]))
        self._drive = drive
        self.uuid = self.drives[drive]['uuid']
        self.fstype = self.drives[drive]['fstype']

    def get_proxies(self):
        """ Return a dictionary of proxy settings """
        return None

    def bootable_partition(self):
        """ Ensure that the selected partition is flagged as bootable """
        # Done on Windows by syslinux.exe -a option
        pass

    def get_mbr(self):
        pass

    def blank_mbr(self):
        pass

    def mbr_matches_syslinux_bin(self):
        """
        Return whether or not the MBR on the drive matches the system's
        syslinux gptmbr.bin
        """
        return True

    def reset_mbr(self):
        # Done on Windows by syslinux.exe -m option
        pass

    def flush_buffers(self):
        """ Flush filesystem buffers """
        pass

    def is_admin(self):
        raise NotImplementedError

    def running_device(self):
        """Returns the physical block device UDI (e.g.
        /org/freedesktop/UDisks2/devices/sdb) from which the system
        is running."""
        liveos_mountpoint = self.running_liveos_mountpoint()
        if os.path.exists(liveos_mountpoint):
            return underlying_physical_device(liveos_mountpoint)
        else:
            return False

    def connect_drive_monitor(self, callback):
        """Connects a callback to be called (at least) when the drive list
        changes."""
        raise NotImplementedError

class LinuxLiveUSBCreator(LiveUSBCreator):

    def __init__(self, *args, **kw):
        super(LinuxLiveUSBCreator, self).__init__(*args, **kw)

        extlinux = self.get_extlinux_version()
        if extlinux is None:
            self.valid_fstypes -= self.ext_fstypes
        elif extlinux < 4:
            self.log.debug(_('You are using an old version of syslinux-extlinux '
                    'that does not support the ext4 filesystem'))
            self.valid_fstypes -= set(['ext4'])

        self.drives = {}
        self._udisksclient = UDisks.Client.new_sync()

    def detect_supported_drives(self, callback=None, force_partitions=False):
        """ Detect all supported (USB and SDIO) storage devices using UDisks.
        Note that the removable bit is not checked.
        """
        mounted_parts = {}
        self.drives = {}
        for obj in self._udisksclient.get_object_manager().get_objects():
            block = obj.props.block
            self.log.debug("looking at %s" % obj.get_object_path())
            if not block:
                self.log.debug("skip %s which is not a block device" % obj.get_object_path())
                continue
            partition = obj.props.partition
            filesystem = obj.props.filesystem
            drive = self._udisksclient.get_drive_for_block(block)
            if not drive:
                self.log.debug("skip %s which has no associated drive" % obj.get_object_path())
                continue
            data = {
                'udi': obj.get_object_path(),
                'is_optical': drive.props.optical,
                'label': drive.props.id.replace(' ', '_'),
                'vendor': drive.props.vendor,
                'model': drive.props.model,
                'fstype': block.props.id_type,
                'fsversion': block.props.id_version,
                'uuid': block.props.id_uuid,
                'device': block.props.device,
                'mount': filesystem.props.mount_points if filesystem else None,
                'bootable': None, #'bootable': 'boot' in map(str, list(dev.Get(device, 'PartitionFlags'))),
                'parent': None,
                'parent_udi': None,
                'parent_size': None,
                'size': drive.props.size,
                'mounted_partitions': set(),
            }
            # Only pay attention to USB and SDIO devices, unless --force'd
            iface = drive.props.connection_bus
            if iface != 'usb' and iface != 'sdio' and self.opts.force != data['device']:
                self.log.warning(
                    "Skipping device '%(device)s' connected to '%(interface)s' interface"
                    % {'device': data['udi'], 'interface': iface}
                )
                continue

            # Skip optical drives
            if data['is_optical'] and self.opts.force != data['device']:
                self.log.debug('Skipping optical device: %s' % data['device'])
                continue

            # Skip things without a size
            if not data['size'] and not self.opts.force:
                self.log.debug('Skipping device without size: %s' % data['device'])
                continue

            if partition:
                partition_table = self._udisksclient.get_partition_table(partition)
                parent_block = partition_table.get_object().props.block
                data['parent'] = parent_block.props.device
                data['parent_size'] = parent_block.props.size
                data['parent_udi'] = parent_block.get_object_path()
            else:
                parent_block = None

            # Skip devices that are too small
            if self.opts.partition and not parent_block \
            	   and not self.is_device_big_enough(data['size']):
                self.log.warning('Skipping too small device: %s' % data['device'])
                continue

            mount = data['mount']
            if mount:
                if len(mount) > 1:
                    self.log.warning('Multiple mount points for %s' %
                            data['device'])
                mount = data['mount'] = data['mount'][0]
            else:
                mount = data['mount'] = None

            if parent_block and mount:
                if not data['parent'] in mounted_parts:
                    mounted_parts[data['parent']] = set()
                mounted_parts[data['parent']].add(data['udi'])

            data['free'] = mount and \
                    self.get_free_bytes(mount) / 1024**2 or None
            data['free'] = None

            self.log.debug(pformat(data))

            if not force_partitions and self.opts.partition:
                # Add whole drive in partitioning mode
                if data['parent'] is None:
                    # Ensure the device is writable
                    if block.props.read_only:
                        self.log.debug(_('Unable to write on %(device)s, skipping.')
                                       % {'device': data['device']})
                        continue
                    self.drives[data['device']] = data
            else:
               self.drives[data['device']] = data

               # Remove parent drives if a valid partition exists
               for parent in [d['parent'] for d in self.drives.values()]:
                   if parent in self.drives:
                        del(self.drives[parent])

        self.log.debug(pformat(mounted_parts))

        for device, data in self.drives.iteritems():
            if self.source and self.source.dev and data['udi'] == self.source.dev:
                continue
            if device in mounted_parts and len(mounted_parts[device]) > 0:
                data['mounted_partitions'] = mounted_parts[device]
                self.log.debug(_('Some partitions of the target device %(device)s are mounted. '
                                 'They will be unmounted before starting the '
                                 'installation process.') % {'device': data['device']})

        if callback:
            callback()

    def _storage_bus(self, dev):
        storage_bus = None
        try:
            storage_bus = dev.GetProperty('storage.bus')
        except Exception, e:
            self.log.exception(e)
        return storage_bus

    def _block_is_volume(self, dev):
        is_volume = False
        try:
            is_volume = dev.GetProperty("block.is_volume")
        except Exception, e:
            self.log.exception(e)
        return is_volume

    def _add_device(self, dev, parent=None):
        mount = str(dev.GetProperty('volume.mount_point'))
        device = str(dev.GetProperty('block.device'))
        if parent:
            parent = parent.GetProperty('block.device')
        self.drives[device] = {
            'label'   : str(dev.GetProperty('volume.label')).replace(' ', '_'),
            'fstype'  : str(dev.GetProperty('volume.fstype')),
            'fsversion': str(dev.GetProperty('volume.fsversion')),
            'uuid'    : str(dev.GetProperty('volume.uuid')),
            'mount'   : mount,
            'udi'     : dev,
            'free'    : mount and self.get_free_bytes(mount) / 1024**2 or None,
            'device'  : device,
            'parent'  : parent
        }

    def mount_device(self):
        """ Mount our device if it is not already mounted """
        if not self.fstype:
            raise LiveUSBError(_("Unknown filesystem.  Your device "
                                 "may need to be reformatted."))
        if self.fstype == "iso9660":
            raise LiveUSBError(_("Unsupported filesystem: %s\nIn case you are trying to upgrade a manually installed Tails system (that is, if it was installed without this installer), this option is not supported: you need to install it anew to start with, e.g. by choosing the \"Clone & Install\" action instead.") % self.fstype)
        elif self.fstype not in self.valid_fstypes:
            raise LiveUSBError(_("Unsupported filesystem: %s") %
                                 self.fstype)
        self.dest = self.drive['mount']
        if not self.dest:
            self.log.debug("Mounting %s" % self.drive['udi'])
            # XXX: this is racy and then it sometimes fails with:
            # 'NoneType' object has no attribute 'call_mount_sync'
            filesystem = self._get_object().props.filesystem
            mount = None
            try:
                mount = filesystem.call_mount_sync(
                        arg_options = GLib.Variant('a{sv}', None),
                        cancellable = None)
            except GLib.Error as e:
                if 'org.freedesktop.UDisks2.Error.AlreadyMounted' in e.message:
                    self.log.debug('Device already mounted')
                else:
                    raise LiveUSBError(_('Unknown GLib exception while trying to '
                                     'mount device: %(message)s')
                                     % {'message': str(e)})
            except Exception, e:
                raise LiveUSBError(_("Unable to mount device: %(message)s")
                                     % {'message': str(e)})

            # Get the new mount point
            if not mount:
                self.log.error(_('No mount points found'))
            else:
                self.dest = self.drive['mount'] = mount
                self.drive['free'] = self.get_free_bytes(self.dest) / 1024**2
                self.log.debug("Mounted %s to %s " % (self.drive['device'],
                                                      self.dest))
        else:
            self.log.debug("Using existing mount: %s" % self.dest)

    def unmount_device(self):
        """ Unmount our device """
        self.log.debug(_("Entering unmount_device for '%(device)s'") % {
            'device': self.drive['device']
        })

        self.log.debug(pformat(self.drive))
        if self.drive['mount'] is None:
            udis = self.drive['mounted_partitions']
        else:
            udis = [self.drive['udi']]
        if udis:
            self.log.info(_("Unmounting mounted filesystems on '%(device)s'") % {
                'device': self.drive['device']
            })
        for udi in udis:
            self.log.debug(_("Unmounting '%(udi)s' on '%(device)s'") % {
                'device': self.drive['device'],
                'udi': udi
            })
            filesystem = self._get_object(udi).props.filesystem
            filesystem.call_unmount_sync(
                    arg_options=GLib.Variant('a{sv}', None),
                    cancellable=None)
        self.drive['mount'] = None
        if not self.opts.partition and self.dest is not None and os.path.exists(self.dest):
            self.log.error(_("Mount %s exists after unmounting") % self.dest)
        self.dest = None
        # Sometimes the device is still considered as busy by the kernel
        # at this point, which prevents, when called by reset_mbr() ->
        # write_to_block_device() -> get_open_write_fd()
        # -> call_open_for_restore_sync() from opening it for writing.
        self.flush_buffers(silent=True)
        time.sleep(3)

    def partition_device(self):
        if not self.opts.partition:
            return

        self.log.info(_('Partitioning device %(device)s') % {
            'device': self.drive['device']
        })

        self.log.debug("Creating partition table")
        # Use udisks instead of plain sgdisk will allow unprivileged users
        # to get a refreshed partition table from the kernel
        obj = self._get_object()
        block = obj.props.block
        try:
            block.call_format_sync(
                    'gpt',
                    arg_options=GLib.Variant('a{sv}', None),
                    cancellable=None)
        except GLib.Error as e:
            # XXX: sometimes retrying fails as well
            # https://bugs.freedesktop.org/show_bug.cgi?id=76178
            if ('GDBus.Error:org.freedesktop.UDisks2.Error.Failed' in e.message and
                    'Error synchronizing after initial wipe' in e.message):
                self.log.debug("Failed to synchronize. Trying again, which usually solves the issue. Error was: %s" % e.message)
                self.flush_buffers(silent=True)
                time.sleep(5)
                block.call_format_sync(
                        'gpt',
                        arg_options=GLib.Variant('a{sv}', None),
                        cancellable=None)
            else:
                raise

        self.log.debug("Creating partition")
        partition_table = obj.props.partition_table
        try:
            partition_table.call_create_partition_sync(
                    arg_offset=0,
                    arg_size=self.system_partition_size * 2**20,
                    arg_type=ESP_GUID,
                    arg_name=self.label,
                    arg_options=GLib.Variant('a{sv}', None),
                    cancellable=None)
        except GLib.Error as e:
            # XXX: as of Debian Jessie, we often get errors while wiping
            # (Debian bug #767457). We ignore them as they are not fatal
            # for us... but we need to fix a few things later...
            if ('GDBus.Error:org.freedesktop.UDisks2.Error.Failed' in e.message and
                    'Error wiping newly created partition' in e.message):
                self.log.debug("Ignoring error %s" % e.message)
            else:
                raise

        self.flush_buffers(silent=True)
        time.sleep(5)

        # Rescan the device as it seems this is not always done automatically.
        # XXX: this should only be needed when call_create_partition_sync fails.
        block.call_rescan_sync(GLib.Variant('a{sv}', None))

        # Gets the new object after the rescan, then its 1st partition
        # which is the one we just created on our new partition table.
        obj = self._get_object(self.drive['udi'])
        partition_table = obj.props.partition_table
        partitions = self._udisksclient.get_partitions(partition_table)
        self.log.debug("partitions: %(partitions)s" % {'partitions': partitions})
        system_partition = partitions[0]

        # Sets the partition type that is not set by call_create_partition_sync...
        # because it is not implemented in UDisks as of version 2.1.5 (see
        # http://cgit.freedesktop.org/udisks/tree/src/udiskslinuxpartitiontable.c?id=a66691c3#n630)
        #
        # XXX: this sometimes fails with:
        # liveusb/creator.py, line 940, in partition_device
        #    system_partition.call_set_type_sync(ESP_GUID,
        #        GLib.Variant('a{sv}', None))
        # Error: udisks-error-quark:
        # GDBus.Error:org.freedesktop.UDisks2.Error.NotSupported:
        # No support for modifying a partition a table of type `PMBR' (11)
        system_partition.call_set_type_sync(ESP_GUID, GLib.Variant('a{sv}', None))
        system_partition.call_set_name_sync(self.label, GLib.Variant('a{sv}', None))

        self._set_partition_flags(system_partition, SYSTEM_PARTITION_FLAGS)

    def update_system_partition_properties(self):
        self.log.info(_('Updating properties of system partition %(system_partition)s') % {
            'system_partition': self.drive['device']
        })

        system_partition = self._get_object().props.partition
        system_partition.call_set_type_sync(ESP_GUID, GLib.Variant('a{sv}', None))
        system_partition.call_set_name_sync(self.label, GLib.Variant('a{sv}', None))

        self._set_partition_flags(system_partition, SYSTEM_PARTITION_FLAGS)

    def is_partition_GPT(self):
        # Check if the partition scheme is GPT
        obj = self._get_object()
        partition_table = obj.props.partition_table
        if not partition_table:
            partition_table = self._udisksclient.get_partition_table(obj.props.partition)
        if partition_table.props.type == 'gpt':
            return True
        else:
            return False

    def save_full_drive(self):
        self._full_drive = self.drives[self._drive]

    def switch_drive_to_system_partition(self):
        full_drive_name  = self._full_drive['device']
        append = False
        if full_drive_name.startswith('/dev/sd'):
            append = '1'
        elif full_drive_name.startswith('/dev/mmcblk'):
            append = 'p1'
        if not append:
            self.log.warning(
                _("Unsupported device '%(device)s', please report a bug." %
                  {'device': full_drive_name})
            )
            self.log.info(_('Trying to continue anyway.'))
            append = '1'
        self.drive = '%s%s' % (full_drive_name, append)

    def switch_back_to_full_drive(self):
        self.drives[self._full_drive['device']] = self._full_drive
        self.drive = self._full_drive['device']

    def verify_filesystem(self):
        self.log.info(_("Verifying filesystem..."))
        if self.fstype not in self.valid_fstypes:
            if not self.fstype:
                raise LiveUSBError(_("Unknown filesystem.  Your device "
                                     "may need to be reformatted."))
            else:
                raise LiveUSBError(_("Unsupported filesystem: %s" %
                                     self.fstype))
        if self.drive['label'] != self.label:
            self.log.info("Setting %(device)s label to %(label)s" %
                          {'device': self.drive['device'],
                           'label': self.label})
            try:
                if self.fstype in ('vfat', 'msdos'):
                    try:
                        self.popen('/sbin/dosfslabel %s %s' % (
                                   self.drive['device'], self.label))
                    except LiveUSBError:
                        # dosfslabel returns an error code even upon success
                        pass
                else:
                    self.popen('/sbin/e2label %s %s' % (self.drive['device'],
                                                        self.label))
            except LiveUSBError, e:
                self.log.error(_("Unable to change volume label: %(message)s") % {'message': str(e)})

    def install_bootloader(self):
        """ Run syslinux to install the bootloader on our devices """
        LiveUSBCreator.install_bootloader(self)
        self.log.info(_("Installing bootloader..."))

        # Don't prompt about overwriting files from mtools (#491234)
        for ldlinux in [self.get_liveos_file_path(p, 'ldlinux.sys')
                        for p in ('syslinux', '')]:
            self.log.debug('Looking for %s' % ldlinux)
            if os.path.isfile(ldlinux):
                self.log.debug(_("Removing %(file)s") % {'file': ldlinux})
                os.unlink(ldlinux)

        # XXX: broken now that we use the syslinux binary from the
        # ISO, but installing on extN is not supported for Tails
        # anyway, and likely we've broken it in various other ways
        # already anyway.
        if self.drive['fstype'] in self.ext_fstypes:
            shutil.move(os.path.join(syslinux_path, "syslinux.cfg"),
                        os.path.join(syslinux_path, "extlinux.conf"))
            self.popen("extlinux -i '%s'" % syslinux_path)
        else: # FAT
            if platform.architecture()[0] == '64bit':
                syslinux_executable = 'syslinux-amd64';
            else:
                syslinux_executable = 'syslinux';
            self.log.debug('Will use %s as the syslinux binary'
                           % syslinux_executable)
            iso_syslinux = self.get_liveos_file_path('utils', 'linux', syslinux_executable)
            tmpdir = tempfile.mkdtemp()
            tmp_syslinux = os.path.join(tmpdir, syslinux_executable)
            shutil.copy(iso_syslinux, tmp_syslinux)
            os.chmod(tmp_syslinux,
                     os.stat(tmp_syslinux).st_mode | stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH)
            self.flush_buffers()
            self.unmount_device()
            # XXX: use call_open_for_restore_sync to avoid needing write
            # access to the raw block device
            self.popen('%s %s -d %s %s' %  (
                    tmp_syslinux,
                    ' '.join(self.syslinux_options()),
                    'syslinux', self.drive['device']))
            shutil.rmtree(tmpdir)

    def get_free_bytes(self, device=None):
        """ Return the number of available bytes on our device """
        import statvfs
        device = device and device or self.dest
        if device is None:
            return None
        stat = os.statvfs(device)
        return stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL]

    def _get_object(self, udi=None):
        """Return an UDisks.Object for our drive"""
        if not udi:
            udi = self.drive['udi']
        return self._udisksclient.get_object(udi)

    def terminate(self):
        for pid in self.pids:
            try:
                os.kill(pid, signal.SIGHUP)
                self.log.debug("Killed process %d" % pid)
            except OSError, e:
                self.log.debug(str(e))

    def get_proxies(self):
        """ Return the proxy settings.

        At the moment this implementation only works on KDE, and should
        eventually be expanded to support other platforms as well.
        """
        try:
            from PyQt4 import QtCore
        except ImportError:
            self.log.warning("PyQt4 module not installed; skipping KDE "
                             "proxy detection")
            return
        kioslaverc = QtCore.QDir.homePath() + '/.kde/share/config/kioslaverc'
        if not QtCore.QFile.exists(kioslaverc):
            return {}
        settings = QtCore.QSettings(kioslaverc, QtCore.QSettings.IniFormat)
        settings.beginGroup('Proxy Settings')
        proxies = {}
        # check for KProtocolManager::ManualProxy (the only one we support)
        if settings.value('ProxyType').toInt()[0] == 1:
            httpProxy = settings.value('httpProxy').toString()
            if httpProxy != '':
                proxies['http'] = httpProxy
            ftpProxy = settings.value('ftpProxy').toString()
            if ftpProxy != '':
                proxies['ftp'] = ftpProxy
        return proxies

    def bootable_partition(self):
        """ Ensure that the selected partition is flagged as bootable """
        if self.opts.partition:
            # already done at partitioning step
            return
        if self.drive.get('parent') is None:
            self.log.debug('No partitions on device; not attempting to mark '
                           'any partitions as bootable')
            return
        import parted
        try:
            disk, partition = self.get_disk_partition()
        except LiveUSBError, e:
            self.log.exception(e)
            return
        if partition.isFlagAvailable(parted.PARTITION_BOOT):
            if partition.getFlag(parted.PARTITION_BOOT):
                self.log.debug(_('%s already bootable') % self._drive)
            else:
                partition.setFlag(parted.PARTITION_BOOT)
                try:
                    disk.commit()
                    self.log.info('Marked %s as bootable' % self._drive)
                except Exception, e:
                    self.log.exception(e)
        else:
            self.log.warning('%s does not have boot flag' % self._drive)

    def get_disk_partition(self):
        """ Return the PedDisk and partition of the selected device """
        import parted
        parent = self.drives[self._drive]['parent']
        dev = parted.Device(path = parent)
        disk = parted.Disk(device = dev)
        for part in disk.partitions:
            if self._drive == "/dev/%s" %(part.getDeviceNodeName(),):
                return disk, part
        raise LiveUSBError(_("Unable to find partition"))

    def initialize_zip_geometry(self):
        """ This method initializes the selected device in a zip-like fashion.

        :Note: This feature is currently experimental, and will DESTROY ALL DATA
               on your device!

        More details on this can be found here:
            http://syslinux.zytor.com/doc/usbkey.txt
        """
        #from parted import PedDevice
        self.log.info('Initializing %s in a zip-like fashon' % self._drive)
        heads = 64
        cylinders = 32
        # Is this part even necessary?
        #device = PedDevice.get(self._drive[:-1])
        #cylinders = int(device.cylinders / (64 * 32))
        self.popen('/usr/lib/syslinux/mkdiskimage -4 %s 0 %d %d' % (
                   self._drive[:-1], heads, cylinders))

    def format_device(self):
        """ Format the selected partition as FAT32 """
        self.log.info(_('Formatting %(device)s as FAT32') % {'device': self._drive})
        dev = self._get_object()
        block = dev.props.block
        try:
            block.call_format_sync(
                'vfat',
                arg_options=GLib.Variant(
                    'a{sv}',
                    {'label': GLib.Variant('s', self.label),
                     'update-partition-type': GLib.Variant('s', 'FALSE')}))
        except GLib.Error as e:
            if ('GDBus.Error:org.freedesktop.UDisks2.Error.Failed' in e.message and
                ('Error synchronizing after formatting' in e.message
                 or 'Error synchronizing after initial wipe' in e.message)):
                self.log.debug("Failed to synchronize. Trying again, which usually solves the issue. Error was: %s" % e.message)
                self.flush_buffers(silent=True)
                time.sleep(5)
                block.call_format_sync(
                    'vfat',
                    arg_options=GLib.Variant(
                        'a{sv}',
                        {'label': GLib.Variant('s', self.label),
                         'update-partition-type': GLib.Variant('s', 'FALSE')}))
            else:
                raise

        self.fstype = self.drive['fstype'] = 'vfat'
        self.flush_buffers(silent=True)
        time.sleep(3)
        self._get_object().props.block.call_rescan_sync(GLib.Variant('a{sv}', None))

    def get_mbr(self):
        parent = self.drive.get('parent', self._drive)
        if parent is None:
            parent = self._drive
        parent = str(parent)
        self.log.debug('Checking the MBR of %s' % parent)
        drive = open(parent, 'rb')
        mbr = ''.join(['%02X' % ord(x) for x in drive.read(2)])
        drive.close()
        self.log.debug('mbr = %r' % mbr)
        return mbr

    def blank_mbr(self):
        """ Return whether the MBR is empty or not """
        return self.get_mbr() == '0000'

    def _get_mbr_bin(self):
        # We install syslinux' gptmbr.bin as mbr.bin there, for
        # compatibility with paths used by Tuxboot and possibly others
        return self.get_liveos_file_path('utils', 'mbr', 'mbr.bin')

    def mbr_matches_syslinux_bin(self):
        """
        Return whether or not the MBR on the drive matches the syslinux'
        gptmbr.bin found in the system being installed
        """
        mbr_bin = open(self._get_mbr_bin(), 'rb')
        mbr = ''.join(['%02X' % ord(x) for x in mbr_bin.read(2)])
        return mbr == self.get_mbr()

    def read_extracted_mbr(self):
        mbr_path = self._get_mbr_bin()
        self.log.info(_('Reading extracted MBR from %s') % mbr_path)
        with open(mbr_path, 'rb') as mbr_fd:
            self.extracted_mbr_content = mbr_fd.read()
        if not len(self.extracted_mbr_content):
            raise LiveUSBError(_("Could not read the extracted MBR from %(path)s"
                                 % {path: mbr_path}))

    def reset_mbr(self):
        parent = parent = self.drive.get('parent', self._drive)
        if parent is None:
            parent = self._drive
            parent_udi = self.drive['udi']
        else:
            parent_udi = self.drive['parent_udi']
        parent_udi = str(parent_udi)
        parent = str(parent)
        if '/dev/loop' not in self.drive:
            self.log.info(_('Resetting Master Boot Record of %s') % parent)
            self.log.debug(_('Resetting Master Boot Record of %s') % parent_udi)
            obj = self._get_object(udi=parent_udi)
            block = obj.props.block
            write_to_block_device(block, self.extracted_mbr_content)
        else:
            self.log.info(_('Drive is a loopback, skipping MBR reset'))

    def calculate_device_checksum(self, progress=None):
        """ Calculate the SHA1 checksum of the device """
        self.log.info(_("Calculating the SHA1 of %s") % self._drive)
        if not progress:
            class DummyProgress:
                def set_max_progress(self, value): pass
                def update_progress(self, value): pass
            progress = DummyProgress()
        # Get size of drive
        #progress.set_max_progress(self.source.size / 1024)
        checksum = hashlib.sha1()
        device_name = str(self.drive['parent'])
        device = file(device_name, 'rb')
        bytes = 1024**2
        total = 0
        while bytes:
            data = device.read(bytes)
            checksum.update(data)
            bytes = len(data)
            total += bytes
            progress.update_progress(total / 1024)
        hexdigest = checksum.hexdigest()
        self.log.info("sha1(%s) = %s" % (device_name, hexdigest))
        return hexdigest

    def flush_buffers(self, silent=False):
        if not silent:
            self.log.info(_("Synchronizing data on disk..."))
        self.popen('sync')

    def is_admin(self):
        return os.getuid() == 0

    def get_extlinux_version(self):
        """ Return the version of extlinux. None if it isn't installed """
        import subprocess
        version = None
        p = subprocess.Popen('extlinux -v', shell=True,
                stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        out = unicode_to_utf8(out)
        err = unicode_to_utf8(err)
        if p.returncode == 0:
            version = int(err.split()[1].split('.')[0])
        elif p.returncode == 127:
            self.log.warning('extlinux not found! Only FAT filesystems will be supported')
        else:
            self.log.debug('Unknown return code from extlinux: %s' % p.returncode)
            self.log.debug('stdout: %s\nstderr: %s' % (out, err))
        return version

    def connect_drive_monitor(self, callback, data=None):
        self._udisksclient.connect('changed', callback, data)

class WindowsLiveUSBCreator(LiveUSBCreator):

    def detect_supported_drives(self, callback=None):
        import win32file, win32api, pywintypes
        self.drives = {}
        for drive in [l + ':' for l in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ']:
            try:
                if win32file.GetDriveType(drive) == win32file.DRIVE_REMOVABLE or \
                   drive == self.opts.force:
                    vol = [None]
                    try:
                        vol = win32api.GetVolumeInformation(drive)
                    except pywintypes.error, e:
                        self.log.error('Unable to get GetVolumeInformation(%s): %s' % (drive, str(e)))
                        continue
                    self.drives[drive] = {
                        'label': vol[0],
                        'mount': drive,
                        'uuid': self._get_device_uuid(drive),
                        'free': self.get_free_bytes(drive) / 1024**2,
                        'fstype': 'vfat',
                        'device': drive,
                        'fsversion': vol[-1],
                        'size': self._get_device_size(drive)
                    }
            except Exception, e:
                self.log.exception(e)
                self.log.error(_("Error probing device"))
        if not len(self.drives):
            raise LiveUSBError(_("Unable to find any supported device"))
        if callback:
            callback()

    def verify_filesystem(self):
        import win32api, win32file, pywintypes
        self.log.info(_("Verifying filesystem..."))
        try:
            vol = win32api.GetVolumeInformation(self.drive['device'])
        except Exception, e:
            raise LiveUSBError(_("Make sure your USB key is plugged in and "
                                 "formatted with the FAT filesystem"))
        if vol[-1] not in ('FAT32', 'FAT'):
            raise LiveUSBError(_("Unsupported filesystem: %s\nPlease backup "
                                 "and format your USB key with the FAT "
                                 "filesystem." % vol[-1]))
        self.fstype = 'vfat'
        if vol[0] != self.label:
            try:
                win32file.SetVolumeLabel(self.drive['device'], self.label)
                self.log.debug("Set %s label to %s" % (self.drive['device'],
                                                       self.label))
            except pywintypes.error, e:
                self.log.warning("Unable to SetVolumeLabel: " + str(e))

    def get_free_bytes(self, device=None):
        """ Return the number of free bytes on our selected drive """
        import win32file
        device = device and device or self.drive['device']
        try:
            (spc, bps, fc, tc) = win32file.GetDiskFreeSpace(device)
        except Exception, e:
            self.log.error("Problem determining free space: %s" % str(e))
            return 0
        return fc * (spc * bps) # free-clusters * bytes per-cluster

    def install_bootloader(self):
        """ Run syslinux to install the bootloader on our device """
        LiveUSBCreator.install_bootloader(self)
        self.log.info(_("Installing bootloader..."))
        device = self.drive['device']
        syslinuxdir = os.path.join(device + os.path.sep, "syslinux")
        if os.path.isdir(syslinuxdir):
            # Python for Windows is unable to delete read-only files, and some
            # may exist here if the LiveUSB stick was created in Linux
            for f in os.listdir(syslinuxdir):
                os.chmod(os.path.join(syslinuxdir, f), 0777)
            shutil.rmtree(syslinuxdir)
        _move_if_exists(os.path.join(device + os.path.sep, "isolinux"),
                        syslinuxdir)
        _unlink_if_exists(os.path.join(syslinuxdir, "isolinux.cfg"))

        # Don't prompt about overwriting files from mtools (#491234)
        for ldlinux in [os.path.join(device + os.path.sep, p, 'ldlinux.sys')
                        for p in (syslinuxdir, '')]:
            if os.path.isfile(ldlinux):
                os.chmod(ldlinux, 0777)
                self.log.debug(_("Removing %(file)s" % {'file': ldlinux}))
                os.unlink(ldlinux)

        self.popen('syslinux %s -m -a -d %s %s' %  (
                ' '.join(self.syslinux_options()), 'syslinux', device))

    # Cache these, because they are fairly expensive
    _win32_logicaldisk = {}

    def _get_win32_logicaldisk(self, drive):
        """ Return the Win32_LogicalDisk object for the given drive """
        import win32com.client
        cache = self._win32_logicaldisk.get('drive')
        if cache:
            return cache
        obj = None
        try:
            obj = win32com.client.Dispatch("WbemScripting.SWbemLocator") \
                         .ConnectServer(".", "root\cimv2") \
                         .ExecQuery("Select * from "
                                    "Win32_LogicalDisk where Name = '%s'" %
                                    drive)
            if not obj:
                self.log.error(_("Unable to get Win32_LogicalDisk; win32com "
                                 "query did not return any results"))
            else:
                obj = obj[0]
                self._win32_logicaldisk[drive] = obj
        except Exception, e:
            self.log.exception(e)
            self.log.error("Unable to get Win32_LogicalDisk")
        return obj

    def _get_device_uuid(self, drive):
        """ Return the UUID of our selected drive """
        if self.uuid:
            return self.uuid
        uuid = None
        try:
            uuid = self._get_win32_logicaldisk(drive).VolumeSerialNumber
            if uuid in (None, 'None', ''):
                uuid = None
            else:
                uuid = uuid[:4] + '-' + uuid[4:]
            self.log.debug("Found UUID %s for %s" % (uuid, drive))
        except Exception, e:
            self.log.exception(e)
            self.log.warning("Exception while fetching UUID: %s" % str(e))
        return uuid

    def _get_device_size(self, drive):
        """ Return the size of the given drive """
        size = None
        try:
            size = int(self._get_win32_logicaldisk(drive).Size)
            self.log.debug("Max size of %s: %d" % (drive, size))
        except Exception, e:
            self.log.exception(e)
            self.log.warning("Error getting drive size: %s" % str(e))
        return size

    def popen(self, cmd, **kwargs):
        import win32process
        if isinstance(cmd, basestring):
            cmd = cmd.split()
        prgmfiles = os.getenv('PROGRAMFILES')
        folder = 'LiveUSB Creator'
        paths = [os.path.join(x, folder) for x in (prgmfiles, prgmfiles + ' (x86)')]
        paths += [os.path.join(os.path.dirname(__file__), '..', '..'), '.']
        tool = None
        for path in paths:
            exe = os.path.join(path, 'tools', '%s.exe' % cmd[0])
            if os.path.exists(exe):
                tool = '"%s"' % exe
                break
        else:
            raise LiveUSBError(_("Cannot find") + ' %s.  ' % (cmd[0]) +
                               _("Make sure to extract the entire "
                                 "liveusb-creator zip file before "
                                 "running this program."))
        return LiveUSBCreator.popen(self, ' '.join([tool] + cmd[1:]),
                                    creationflags=win32process.CREATE_NO_WINDOW,
                                    **kwargs)

    def terminate(self):
        """ Terminate any subprocesses that we have spawned """
        import win32api, win32con, pywintypes
        for pid in self.pids:
            try:
                handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE,
                                              False, pid)
                self.log.debug("Terminating process %s" % pid)
                win32api.TerminateProcess(handle, -2)
                win32api.CloseHandle(handle)
            except pywintypes.error:
                pass

    def mount_device(self):
        self.dest = self.drive['mount']

    def unmount_device(self):
        pass

    def get_proxies(self):
        proxies = {}
        try:
            import _winreg as winreg
            settings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
                                      'Software\\Microsoft\\Windows'
                                      '\\CurrentVersion\\Internet Settings')
            proxy = winreg.QueryValueEx(settings, "ProxyEnable")[0]
            if proxy:
                server = str(winreg.QueryValueEx(settings, 'ProxyServer')[0])
                if ';' in server:
                    for p in server.split(';'):
                        protocol, address = p.split('=')
                        proxies[protocol] = '%s://%s' % (protocol, address)
                else:
                    proxies['http'] = 'http://%s' % server
                    proxies['ftp'] = 'ftp://%s' % server
            settings.Close()
        except Exception, e:
            self.log.warning('Unable to detect proxy settings: %s' % str(e))
        self.log.debug('Using proxies: %s' % proxies)
        return proxies

    def calculate_device_checksum(self, progress=None):
        """ Calculate the SHA1 checksum of the device """
        self.log.info(_("Calculating the SHA1 of %s" % self._drive))
        time.sleep(3)
        if not progress:
            class DummyProgress:
                def set_max_progress(self, value): pass
                def update_progress(self, value): pass
            progress = DummyProgress()
        progress.set_max_progress(self.drive['size'])
        checksum = hashlib.sha1()
        device_name = r'\\.\%s' % self.drive['device']
        device = file(device_name, 'rb')
        bytes = 1
        total = 0
        while bytes:
            data = device.read(1024**2)
            checksum.update(data)
            bytes = len(data)
            total += bytes
            progress.update_progress(total)
        hexdigest = checksum.hexdigest()
        self.log.info("sha1(%s) = %s" % (self.drive['device'], hexdigest))
        return hexdigest

    def calculate_liveos_checksum(self):
        """ Calculate the hash of the extracted LiveOS """
        chunk_size = 1024 # FIXME: optimize this.  we hit bugs when this is *not* 1024
        checksums = []
        for img in (os.path.join('LiveOS', 'osmin.img'),
                    os.path.join('LiveOS', 'squashfs.img'),
                    os.path.join('syslinux', 'initrd0.img'),
                    os.path.join('syslinux', 'vmlinuz0'),
                    os.path.join('syslinux', 'isolinux.bin')):
            hash = getattr(hashlib, self.opts.hash, 'sha1')()
            liveos = os.path.join(self.drive['device'], img)
            device = file(liveos, 'rb')
            self.log.info("Calculating the %s of %s" % (hash.name, liveos))
            bytes = 1
            while bytes:
                data = device.read(chunk_size)
                hash.update(data)
                bytes = len(data)
            checksum = hash.hexdigest()
            checksums.append(checksum)
            self.log.info('%s(%s) = %s' % (hash.name, liveos, checksum))

        # Take a checksum of all of the checksums
        hash = getattr(hashlib, self.opts.hash, 'sha1')()
        map(hash.update, checksums)
        self.log.info("%s = %s" % (hash.name, hash.hexdigest()))

    def format_device(self):
        """ Format the selected partition as FAT32 """
        self.log.info('Formatting %s as FAT32' % self.drive['device'])
        self.popen('format /Q /X /y /V:Fedora /FS:FAT32 %s' % self.drive['device'])

    def is_admin(self):
        import pywintypes
        try:
            from win32com.shell import shell
            return shell.IsUserAnAdmin()
        except pywintypes.com_error:
            # Thrown on certain XP installs
            return True