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
|
#!/usr/bin/python3
'''
Installer
This is a installer program for a Ubuntu or Metadistros Live system.
This is the main program, but there are also a couple of libraries to
help it to work, such as the frontend.
The way it works is simple. It detects the frontend to use, then
load the module for that frontend. After that, it makes some calls
through the frontend in order to get the info necessary to install.
Once it has the info, partitioning, format, copy the distro to the disk
and configure everything.
'''
from __future__ import print_function
import atexit
import errno
import fcntl
import importlib
import locale
from operator import attrgetter
import optparse
import os
import pwd
import shutil
import subprocess
import sys
import syslog
sys.path.insert(0, '/usr/lib/ubiquity')
from ubiquity import im_switch, misc, osextras
VERSION = '@VERSION@'
TARGET = '/target'
LOCKFILE = '/var/lock/ubiquity'
lock = None
def force_utf8_locale():
"""We must have a UTF-8 locale. Try to get one."""
# apt now follows LC_NUMERIC; we must make sure it's set appropriately
# so that debconf-apt-progress and uses of python-apt will be able to
# parse pmstatus messages. (LP: #1611010)
os.environ["LC_NUMERIC"] = "C.UTF-8"
if locale.getpreferredencoding() != "UTF-8":
try:
os.environ["LC_ALL"] = "C.UTF-8"
locale.setlocale(locale.LC_ALL, "")
except locale.Error:
# Abandon hope.
print("Ubiquity requires a UTF-8 locale and cannot proceed "
"without one.", file=sys.stderr)
sys.exit(1)
def distribution():
"""Returns the name of the running distribution."""
proc = subprocess.Popen(
['lsb_release', '-is'], stdout=subprocess.PIPE,
universal_newlines=True)
return proc.communicate()[0].strip()
def disable_autologin():
import traceback
# Reverse actions of user-setup-apply.
for name in ('/etc/gdm3/custom.conf', '/etc/kde4/kdm/kdmrc',
'/etc/lxdm/lxdm.conf', '/etc/xdg/lubuntu/lxdm/lxdm.conf',
'/etc/lightdm/lightdm.conf'):
if os.path.exists('%s.oem' % name):
try:
os.rename('%s.oem' % name, name)
except OSError:
traceback.print_exc()
def open_terminal():
"""Set up the terminal to run ubiquity's debconf frontend."""
# Set up a framebuffer and start bterm if debian-installer/framebuffer
# says to do so. See, in rootskel:
# src/lib/debian-installer-startup.d/S40framebuffer-module-linux-x86
# TODO: more careful architecture handling
import debconf
# Start a new session and start a controlling terminal. Approach loosely
# borrowed from util-linux.
if 'UBIQUITY_CTTY' not in os.environ:
os.environ['UBIQUITY_CTTY'] = '1'
import termios
try:
os.setsid()
except OSError:
pass
ttyn = os.ttyname(0)
tty = os.open(ttyn, os.O_RDWR | os.O_NONBLOCK)
flags = fcntl.fcntl(tty, fcntl.F_GETFL)
fcntl.fcntl(tty, fcntl.F_SETFL, flags)
# Leave stderr alone in the following; it's already redirected to
# our log file. We also need to avoid closing the FD for
# /dev/urandom (http://bugs.python.org/issue21207).
dev_ino = attrgetter("st_dev", "st_ino")
urandom_dev_ino = dev_ino(os.stat("/dev/urandom"))
for i in range(tty):
if i != 2 and dev_ino(os.fstat(i)) != urandom_dev_ino:
os.close(i)
for i in range(2):
if tty != i:
os.dup2(tty, i)
if tty >= 3:
os.close(tty)
fcntl.ioctl(0, termios.TIOCSCTTY, 1)
if 'UBIQUITY_BTERM' not in os.environ:
os.environ['UBIQUITY_BTERM'] = '1'
framebuffer = False
dccomm = subprocess.Popen(['debconf-communicate',
'-fnoninteractive', 'ubiquity'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, close_fds=True,
universal_newlines=True)
try:
dc = debconf.Debconf(read=dccomm.stdout, write=dccomm.stdin)
try:
if dc.get('debian-installer/framebuffer') == 'true':
framebuffer = True
except debconf.DebconfError:
pass
finally:
dccomm.stdin.close()
dccomm.wait()
if framebuffer:
def fb_has(substring):
try:
with open('/proc/fb') as fb:
for line in fb:
if substring in line:
return True
except IOError:
pass
return False
got_fb = False
if fb_has('VESA'):
got_fb = True
devnull = open('/dev/null', 'w')
if not got_fb:
subprocess.call(['modprobe', '-q', 'vesafb'],
stdout=devnull, stderr=devnull)
if fb_has(''):
got_fb = True
if not got_fb:
subprocess.call(['modprobe', '-q', 'vga16fb'],
stdout=devnull, stderr=devnull)
if fb_has(''):
got_fb = True
if got_fb:
if not os.path.isdir('/sys/class/graphics/fbcon'):
subprocess.call(['modprobe', '-q', 'fbcon'],
stdout=devnull, stderr=devnull)
# TODO: import debian-installer-utils and use update-dev?
subprocess.call(['udevadm', 'settle'])
devnull.close()
if os.path.exists('/dev/fb0'):
bterm_args = ['bterm',
'-f', '/usr/share/ubiquity/unifont.bgf', '--']
bterm_args.extend(sys.argv)
os.execvp('bterm', bterm_args)
def start_debconf():
"""debconf_ui needs to run within a debconf frontend."""
if 'DEBIAN_HAS_FRONTEND' in os.environ:
# debconf already started, so just clean up the configuration file
# if any (debconf has already read it by now).
if 'DEBCONF_SYSTEMRC' in os.environ:
osextras.unlink_force(os.environ['DEBCONF_SYSTEMRC'])
return
print("debconf_ui selected; starting debconf frontend", file=sys.stderr)
if 'UBIQUITY_AUTOMATIC' in os.environ:
# In automatic mode, we don't want debconf to reshow seen questions,
# since that defeats the purpose of preseeding.
pass
elif 'DEBCONF_USE_CDEBCONF' not in os.environ:
# This is rather unsatisfactory. Perhaps it would be better to
# have a custom debconf program, a bit like dpkg-reconfigure.
import tempfile
debconfrc_fd, debconfrc = tempfile.mkstemp()
os.chmod(debconfrc, 0o644)
debconfrc_file = os.fdopen(debconfrc_fd, 'w')
orig_debconfrc = open('/etc/debconf.conf')
state = 0
for line in orig_debconfrc:
if (state == 0 and
line.rstrip('\n') and not line.startswith('#')):
state = 1
elif state == 1 and not line.rstrip('\n'):
print('Reshow: true', file=debconfrc_file)
state = 2
print(line, end="", file=debconfrc_file)
orig_debconfrc.close()
debconfrc_file.close()
os.environ['DEBCONF_SYSTEMRC'] = debconfrc
else:
os.environ['DEBCONF_SHOWOLD'] = 'true'
if 'DEBCONF_USE_CDEBCONF' not in os.environ:
os.environ['DEBCONF_PACKAGE'] = 'ubiquity'
# TODO: need to set owner somehow for the cdebconf case
import debconf
debconf.runFrontEnd() # re-execs this program
def install(frontend=None, query=False):
"""Get the type of frontend to use and load the module for that.
If frontend is None, defaults to the first of gtk_ui, kde_ui, and
debconf_ui that exists.
"""
if frontend is None:
frontends = ['gtk_ui', 'kde_ui', 'debconf_ui']
else:
frontends = [frontend]
chosen = None
for f in frontends:
try:
ui = importlib.import_module('ubiquity.frontend.%s' % f)
except ImportError:
continue
chosen = f
# Noninteractive implies automatic mode.
if f == 'noninteractive':
os.environ['UBIQUITY_AUTOMATIC'] = '1'
break
else:
raise AttributeError('No frontend available; tried %s' %
', '.join(frontends))
os.environ['UBIQUITY_FRONTEND'] = chosen
if query:
print(os.environ['UBIQUITY_FRONTEND'], file=sys.__stdout__)
sys.exit(0)
unmount_target()
distro = distribution().lower()
wizard = ui.Wizard(distro)
if os.environ['UBIQUITY_FRONTEND'] == 'debconf_ui':
open_terminal()
start_debconf()
ret = wizard.run()
wizard.stop_debconf()
if ret != 10 and 'UBIQUITY_GREETER' in os.environ:
import traceback
try:
apply_keyboard()
except Exception:
traceback.print_exc()
copy_debconf()
unmount_target()
if ret == 10:
wizard.do_reboot()
if ret == 11:
wizard.do_shutdown()
@misc.raise_privileges
def apply_keyboard():
"""Set the keyboard layout to the default layout for the language selected.
If a user wants a different layout, they can be reasonably expected to
change it in System -> Preferences -> Keyboard.
"""
# Mostly taken from ubi-console-setup.
# We need to get rid of /etc/default/keyboard, or keyboard-configuration
# will think it's already configured and behave differently. Try to save
# the old file for interest's sake, but it's not a big deal if we can't.
osextras.unlink_force('/etc/default/keyboard.pre-ubiquity')
try:
os.rename('/etc/default/keyboard',
'/etc/default/keyboard.pre-ubiquity')
except OSError:
osextras.unlink_force('/etc/default/keyboard')
import debconf
dccomm = subprocess.Popen(['debconf-communicate',
'-fnoninteractive', 'ubiquity'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, close_fds=True,
universal_newlines=True)
try:
dc = debconf.Debconf(read=dccomm.stdout, write=dccomm.stdin)
try:
# Make sure debconf doesn't do anything with crazy "preseeded"
# answers to these questions. If you want to preseed these, use the
# *code variants.
dc.fset('keyboard-configuration/layout', 'seen', 'false')
dc.fset('keyboard-configuration/variant', 'seen', 'false')
dc.fset('keyboard-configuration/model', 'seen', 'false')
dc.fset('console-setup/codeset47', 'seen', 'false')
except debconf.DebconfError:
return
finally:
dccomm.stdin.close()
dccomm.wait()
# Accept all the defaults, given the preseeded language.
child_env = dict(os.environ)
child_env['OVERRIDE_ALLOW_PRESEEDING'] = '1'
subprocess.call(['dpkg-reconfigure', '-fnoninteractive',
'keyboard-configuration'],
env=child_env)
misc.execute('setupcon', '--save-only')
# Reprocess /lib/udev/rules.d/64-xorg-xkb.rules
misc.execute('udevadm', 'trigger', '--subsystem-match=input',
'--action=change')
misc.execute('udevadm', 'settle')
def copy_debconf():
"""Copy a few important questions into the installed system."""
if not TARGET:
return
targetdb = TARGET + '/var/cache/debconf/config.dat'
patterns = ['^oem-config/']
oem = False
import debconf
dccomm = subprocess.Popen(['debconf-communicate',
'-fnoninteractive', 'ubiquity'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, close_fds=True,
universal_newlines=True)
try:
dc = debconf.Debconf(read=dccomm.stdout, write=dccomm.stdin)
try:
if dc.get('oem-config/enable') == 'true':
oem = True
except debconf.DebconfError:
pass
finally:
dccomm.stdin.close()
dccomm.wait()
if not oem:
patterns.append('^keyboard-configuration/')
patterns.append('^console-setup/')
for q in patterns:
misc.execute_root(
'debconf-copydb', 'configdb', 'targetdb', '-p', q,
'--config=Name:targetdb', '--config=Driver:File',
'--config=Mode:0644', '--config=Filename:%s' % targetdb)
def unmount_target():
if not TARGET:
return
paths = []
with open('/proc/mounts') as mounts:
for line in mounts:
path = line.split(' ')[1]
if path == TARGET or path.startswith(TARGET + '/'):
paths.append(path)
paths.sort()
paths.reverse()
for path in paths:
misc.execute_root('fuser', '-cv', path)
misc.execute_root('umount', path)
def prepend_path(directory):
if 'PATH' in os.environ and os.environ['PATH'] != '':
os.environ['PATH'] = '%s:%s' % (directory, os.environ['PATH'])
else:
os.environ['PATH'] = directory
def release_lock():
global lock
osextras.unlink_force(LOCKFILE)
if lock is not None:
lock.close()
lock = None
def acquire_lock():
global lock
lock = open(LOCKFILE, 'w')
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as e:
if e.errno in (errno.EACCES, errno.EAGAIN, errno.EWOULDBLOCK):
print("Ubiquity is already running!")
sys.exit(1)
raise
atexit.register(release_lock)
fcntl.fcntl(lock, fcntl.F_SETFD, fcntl.FD_CLOEXEC)
print(os.getpid(), file=lock)
lock.flush()
os.fsync(lock.fileno())
if 'DEBIAN_HAS_FRONTEND' not in os.environ:
# Do a quick check to see if the debconf database is locked by
# something else.
test_debconf = subprocess.Popen(
['debconf-communicate', '-fnoninteractive', 'ubiquity'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True,
universal_newlines=True)
try:
# It seems that in python3.4, the below print is not
# flushed by default, thus adding "flush=True" kargs and
# thus avoid a boot hang as seen in LP: #1326707 But flush
# karg was only introduced in python3.3, instead this is a
# big FIXME and should instead use
# test_debconf.communicate() I'll propose a merge proposal
# which does that, but not at 1 AM when it is still
# boiling hot in London and I can't fall asleep.
print('VERSION 2.0', file=test_debconf.stdin, flush=True)
test_debconf.stdout.readline()
except IOError:
pass
test_debconf.stdin.close()
test_debconf.stdout.close()
if test_debconf.wait() != 0:
print("Debconf database is locked!")
print("This may be because a package management program is "
"running.")
sys.exit(1)
def run_oem_hooks():
"""Run hook scripts from /usr/lib/oem-config/post-install."""
hookdir = '/usr/lib/oem-config/post-install'
if os.path.isdir(hookdir):
# Exclude hooks containing '.', so that *.dpkg-* et al are avoided.
hooks = [entry for entry in os.listdir(hookdir) if '.' not in entry]
child_env = dict(os.environ)
child_env['DEBIAN_FRONTEND'] = 'noninteractive'
if 'DEBIAN_HAS_FRONTEND' in child_env:
del child_env['DEBIAN_HAS_FRONTEND']
for hookentry in hooks:
hook = os.path.join(hookdir, hookentry)
if os.access(hook, os.X_OK):
# Errors are ignored at present, although this may change.
subprocess.call([hook], env=child_env)
def main(oem_config):
force_utf8_locale()
usage = '%prog [options] [frontend]'
parser = optparse.OptionParser(usage=usage, version=VERSION)
parser.set_defaults(
debug=('UBIQUITY_DEBUG' in os.environ),
debug_pdb=False,
cdebconf=False,
automatic=False,
query=False)
parser.add_option('-d', '--debug', dest='debug', action='store_true',
help='debug mode (warning: passwords will be logged!)')
parser.add_option('--pdb', dest='debug_pdb', action='store_true',
help='drop into Python debugger on a crash')
parser.add_option('--cdebconf', dest='cdebconf', action='store_true',
help='use cdebconf instead of debconf (experimental)')
parser.add_option('--automatic', dest='automatic', action='store_true',
help='do not ignore the "seen" flag (useful for '
'unattended installations).')
parser.add_option('--only', dest='only', action='store_true',
help='tell the application that it is the only desktop '
'program running so that it can customize its UI '
'to better suit a minimal environment.')
parser.add_option('-q', '--query', dest='query', action='store_true',
help='find out which frontend will be used by default')
parser.add_option('-g', '--greeter', dest='greeter', action='store_true',
help='allow the user to leave the installer and enter '
'a live desktop (for the initial boot).')
parser.add_option('-b', '--no-bootloader', dest='bootloader',
default=True, action='store_false',
help='Do not install a bootloader.')
parser.add_option('--ldtp', dest='ldtp',
action='store_true',
help='Name widgets in ATK by their GtkBuilder names, '
'to support LDTP testing.')
parser.add_option('--autopilot', dest='autopilot',
action='store_true',
help='Export variables needed for autopilot to drive '
'ubiquity UI.')
parser.add_option('--wireless', dest='wireless',
action='store_true',
help='Force enable the wireless page, even if network '
'is available.')
(options, args) = parser.parse_args()
if options.debug:
os.environ['UBIQUITY_DEBUG'] = '1'
if options.debug_pdb:
os.environ['UBIQUITY_DEBUG_PDB'] = '1'
if options.cdebconf:
# Note that this needs to be set before DebconfCommunicate is
# imported by anything.
os.environ['DEBCONF_USE_CDEBCONF'] = '1'
prepend_path('/usr/lib/cdebconf')
prepend_path('/usr/lib/ubiquity/compat')
if options.automatic:
os.environ['UBIQUITY_AUTOMATIC'] = '1'
if options.greeter:
os.environ['UBIQUITY_GREETER'] = '1'
if options.only:
os.environ['UBIQUITY_ONLY'] = '1'
if not options.bootloader:
os.environ['UBIQUITY_NO_BOOTLOADER'] = '1'
if oem_config:
os.environ['UBIQUITY_OEM_USER_CONFIG'] = '1'
global TARGET
TARGET = ''
if options.ldtp:
os.environ['UBIQUITY_LDTP'] = '1'
if options.wireless:
os.environ['UBIQUITY_WIRELESS'] = '1'
uid = os.getenv('PKEXEC_UID', False)
if uid:
# pkexec doesn't set username, but it's used in a few places.
# fake it from PKEXEC =)
os.environ['SUDO_USER'] = pwd.getpwuid(int(uid)).pw_name
os.environ['HOME'] = pwd.getpwuid(int(uid)).pw_dir
acquire_lock()
try:
os.makedirs('/var/log/installer')
except OSError as e:
# be happy if someone already created the path
if e.errno != errno.EEXIST:
raise
syslog.openlog('ubiquity', syslog.LOG_NOWAIT | syslog.LOG_PID)
if oem_config:
syslog.syslog("Ubiquity %s (oem-config)" % VERSION)
else:
syslog.syslog("Ubiquity %s" % VERSION)
with open('/var/log/installer/version', 'w') as version_file:
print('ubiquity %s' % VERSION, file=version_file)
if options.autopilot:
os.environ['UBIQUITY_AUTOPILOT'] = '1'
with open('/var/log/installer/autopilot', 'w') as autopilot_file:
print('DBUS_SESSION_BUS_ADDRESS=%s' %
os.environ['DBUS_SESSION_BUS_ADDRESS'], file=autopilot_file)
print('UBIQUITY_PID=%i' % os.getpid(), file=autopilot_file)
if 'UBIQUITY_DEBUG' in os.environ:
if 'UBIQUITY_DEBUG_CORE' not in os.environ:
os.environ['UBIQUITY_DEBUG_CORE'] = '1'
if 'DEBCONF_DEBUG' not in os.environ:
os.environ['DEBCONF_DEBUG'] = 'developer'
# The frontend should take care of displaying a helpful message if
# we are being run without root privileges.
if not (options.query and args and args[0] == 'noninteractive'):
try:
if oem_config:
logfile = '/var/log/oem-config.log'
else:
logfile = '/var/log/installer/debug'
log = os.open(logfile, os.O_WRONLY | os.O_CREAT | os.O_APPEND,
0o644)
os.dup2(log, 2)
os.close(log)
sys.stderr = os.fdopen(2, 'a', 1)
if oem_config:
print("Ubiquity %s (oem-config)" % VERSION, file=sys.stderr)
else:
print("Ubiquity %s" % VERSION, file=sys.stderr)
except (IOError, OSError) as err:
if err.errno != errno.EACCES:
raise
# Default to enabling internal (non-debconf) debugging except for when
# using --automatic.
if 'UBIQUITY_DEBUG_CORE' not in os.environ:
if options.automatic:
os.environ['UBIQUITY_DEBUG_CORE'] = '1'
# Initialise cdebconf if necessary, to work around
# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=451130.
if options.cdebconf:
for package in ('ubiquity', 'keyboard-configuration', 'console-setup'):
subprocess.call(['debconf-loadtemplate', package,
'/var/lib/dpkg/info/%s.templates' % package])
# Clean up old state.
for name in ('apt-installed', 'apt-install-direct', 'remove-kernels',
'apt-removed', 'encrypted-swap', 'started-installing'):
osextras.unlink_force(os.path.join('/var/lib/ubiquity', name))
shutil.rmtree("/var/lib/partman", ignore_errors=True)
misc.remove_os_prober_cache()
if oem_config and not options.query:
disable_autologin()
if args:
install(args[0], query=options.query)
else:
install(query=options.query)
if oem_config:
run_oem_hooks()
im_switch.kill_im()
if __name__ == '__main__':
# Are we running as ubiquity or oem-config?
oem_config = False
script_name = os.path.basename(sys.argv[0])
if script_name == 'oem-config':
oem_config = True
main(oem_config)
# vim:ai:et:sts=4:tw=80:sw=4:
|