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
|
#!/usr/bin/python3
from __future__ import print_function
import errno
import grp
import imp
import os
import pwd
import signal
import subprocess
import sys
import time
import debconf
sys.path.insert(0, '/usr/lib/ubiquity')
from ubiquity import gsettings, osextras
from ubiquity.casper import get_casper
from ubiquity.debconfcommunicator import DebconfCommunicator
import ubiquity.frontend
from ubiquity.misc import create_bool, utf8
def set_locale():
db = DebconfCommunicator('ubiquity', cloexec=True)
locale = ''
try:
locale = db.get('debian-installer/locale')
except debconf.DebconfError:
pass
db.shutdown()
if not locale:
return
with open('/etc/default/locale', 'w') as default_locale:
print('LANG="%s"' % locale, file=default_locale)
with open('/etc/environment') as environment:
environment_lines = environment.readlines()
with open('/etc/environment', 'w') as environment:
seen_lang = False
for line in environment_lines:
if line.startswith('LANG='):
print('LANG="%s"' % locale, file=environment)
seen_lang = True
else:
print(line.rstrip('\n'), file=environment)
if not seen_lang:
print('LANG="%s"' % locale, file=environment)
with open('/etc/locale.gen', 'w') as locale_gen:
print('%s UTF-8' % locale, file=locale_gen)
with open('/var/log/installer/dm', 'a') as logfile:
subprocess.call(['/usr/sbin/locale-gen', locale],
stdout=logfile, stderr=logfile)
class XStartupError(EnvironmentError):
pass
class MissingProgramError(EnvironmentError):
pass
class DM:
def __init__(self, vt, display, default_username):
self.vt = vt
self.display = display
self.server_started = False
self.username = get_casper('USERNAME', default_username)
try:
self.uid, self.gid = pwd.getpwnam(self.username)[2:4]
except KeyError:
import syslog
syslog.syslog('Could not find %s, falling back to root.' %
self.username)
self.username = 'root'
self.uid, self.gid = 0, 0
self.homedir = pwd.getpwnam(self.username)[5]
self.uid = int(self.uid)
self.gid = int(self.gid)
self.groups = []
for g in grp.getgrall():
if self.username in g[3] or g[0] == self.username:
self.groups.append(g[2])
# Look for a frontend module; we won't actually use it (yet), but
# this lets us find out which window manager etc. to launch. Be
# careful that importing this here will cause the underlying library
# to try to talk to the X server, which won't go well.
frontend_names = ['gtk_ui', 'kde_ui']
self.frontend = None
for f in frontend_names:
try:
imp.find_module(f, ubiquity.frontend.__path__)
self.frontend = f
break
except ImportError:
pass
else:
raise AttributeError('No frontend available; tried %s' %
', '.join(frontend_names))
db = DebconfCommunicator('ubiquity', cloexec=True)
try:
self.force_failsafe = create_bool(
db.get('ubiquity/force_failsafe_graphics'))
except debconf.DebconfError:
self.force_failsafe = False
db.shutdown()
def sigusr1_handler(self, signum, frame):
self.server_started = True
def active_vt(self):
import fcntl
import array
console = os.open('/dev/tty0', os.O_RDONLY | os.O_NOCTTY)
try:
VT_GETSTATE = 0x5603
vt_stat = array.array('H', [0, 0, 0])
fcntl.ioctl(console, VT_GETSTATE, vt_stat)
return vt_stat[0]
finally:
os.close(console)
def drop_privileges(self):
os.setgroups(self.groups)
os.setgid(self.gid)
os.setuid(self.uid)
def server_preexec(self):
signal.signal(signal.SIGUSR1, signal.SIG_IGN)
def run_hooks(self, hookdir):
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]
for hookentry in hooks:
hook = os.path.join(hookdir, hookentry)
with open('/var/log/installer/dm', 'a') as logfile:
subprocess.call(
hook, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges)
def run(self, *program):
# Extract the program basename to see if we are in oem-config or
# ubiquity.
program_basename = os.path.basename(program[0])
extras = []
null = open('/dev/null', 'w')
try:
os.makedirs('/var/log/installer')
except OSError as e:
# be happy if someone already created the path
if e.errno != errno.EEXIST:
raise
logfile = open('/var/log/installer/dm', 'w')
signal.signal(signal.SIGUSR1, self.sigusr1_handler)
signal.signal(signal.SIGTTIN, signal.SIG_IGN)
signal.signal(signal.SIGTTOU, signal.SIG_IGN)
servercommand = ['X', '-br', '-ac', '-noreset', '-nolisten', 'tcp']
try:
plymouth_running = subprocess.call(['plymouth', '--ping']) == 0
except OSError:
plymouth_running = False
if plymouth_running:
subprocess.call(['plymouth', 'deactivate'])
if subprocess.call(['plymouth', '--has-active-vt']) == 0:
self.vt = 'vt%d' % self.active_vt()
servercommand.extend(['-background', 'none'])
else:
subprocess.call(['plymouth', 'quit'])
plymouth_running = False
servercommand.extend([self.vt, self.display])
for attempt in ('main', 'fbdev', 'vesa'):
command = list(servercommand)
if attempt == 'main' and self.force_failsafe:
continue
elif attempt != 'main':
# TODO cjwatson 2010-02-11: This is a bodge. The
# duplication is nasty, but fortunately bullet-proof X
# actually turns out not to be very complicated nowadays.
# Most of the complexity is in the fallback session, which I
# haven't attempted to integrate here, so you won't get
# things like interactive reconfiguration. I believe Evan
# is working on doing that, but is blocked on a couple of
# Upstart bugs; once all that's resolved, we should back
# this out.
if attempt == 'fbdev' and not os.path.exists('/dev/fb0'):
continue
xorg_conf_failsafe = '/etc/X11/xorg.conf.failsafe'
command.extend(['-config', xorg_conf_failsafe])
command.extend(['-logfile', '/var/log/Xorg.%s.log' % attempt])
with open(xorg_conf_failsafe, 'w') as xorg_conf_failsafe_file:
print('''\
Section "Device"
\tIdentifier "Configured Video Device"
\tDriver "%s"
EndSection
Section "Monitor"
\tIdentifier "Configured Monitor"
EndSection
Section "Screen"
\tIdentifier "Default Screen"
\tMonitor "Configured Monitor"
\tDevice "Configured Video Device"
EndSection
''' % attempt, file=xorg_conf_failsafe_file)
server = subprocess.Popen(
command, stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.server_preexec)
# Really we should select on a pipe or something, but it's not
# worth the effort for now.
try:
timeout = 60
while not self.server_started:
status = server.poll()
if type(status) is int and status != 0:
if plymouth_running:
subprocess.call(['plymouth', 'quit'])
raise XStartupError('X server exited with return code '
+ str(status))
if timeout == 0:
if plymouth_running:
subprocess.call(['plymouth', 'quit'])
raise XStartupError('X server failed to start after 60'
' seconds')
time.sleep(1)
timeout -= 1
if plymouth_running:
subprocess.call(['plymouth', 'quit', '--retain-splash'])
except XStartupError:
if attempt == 'vesa':
raise
if self.server_started:
break
os.environ['DISPLAY'] = self.display
os.environ['HOME'] = self.homedir
os.environ['XDG_SESSION_ID'] = 'c1'
# Give ubiquity a UID and GID that it can drop privileges to.
os.environ['PKEXEC_UID'] = str(self.uid)
os.environ['GVFS_DISABLE_FUSE'] = '1'
# Overlay scrollbars are now a gtk module
os.environ['GTK_MODULES'] = 'overlay-scrollbar'
# run simple, custom scripts during install time
if program_basename == 'ubiquity':
self.run_hooks('/usr/lib/ubiquity/dm-scripts/install')
# run simple, custom scripts during oem-config
if program_basename == 'oem-config-wrapper':
self.run_hooks('/usr/lib/ubiquity/dm-scripts/oem')
# Session bus, apparently needed by most interfaces now
if ('DBUS_SESSION_BUS_ADDRESS' not in os.environ and
osextras.find_on_path('dbus-launch')):
dbus_subp = subprocess.Popen(
['dbus-launch', '--exit-with-session'],
stdin=null, stdout=subprocess.PIPE, stderr=logfile,
preexec_fn=self.drop_privileges, universal_newlines=True)
for line in dbus_subp.stdout:
try:
name, value = line.rstrip('\n').split('=', 1)
os.environ[name] = value
except ValueError:
pass
dbus_subp.stdout.close()
dbus_subp.wait()
# dconf writer
if os.path.exists("/usr/lib/dconf/dconf-service"):
extras.append(subprocess.Popen(
['/usr/lib/dconf/dconf-service'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
if self.frontend == 'gtk_ui':
# Set a desktop wallpaper.
with open('/proc/cmdline', 'r') as fp:
visual_a11y = 'access=v' in fp.readline()
background_image = None
for background in (
'/usr/share/backgrounds/edubuntu_default.png',
'/usr/share/xfce4/backdrops/ubuntustudio-rock.png',
'/usr/share/xfce4/backdrops/xubuntu-precise-right.png',
'/usr/share/lubuntu/wallpapers/'
'lubuntu-default-wallpaper.png',
'/usr/share/backgrounds/ubuntukylin-default-settings.jpg',
'/usr/share/backgrounds/warty-final-ubuntu.png',
'/usr/share/themes/Adwaita/backgrounds/adwaita-timed.xml'):
exists = os.access(background, os.R_OK)
if exists:
background_image = background
break
# Setting a wallpaper image, or solid color.
if visual_a11y or background_image is None:
picture_option = 'none'
background_image = False
else:
picture_option = 'zoom'
if background_image:
background_url = 'file://' + background_image
else:
background_url = "''"
accessibility = False
if gsettings._gsettings_exists():
accessibility = gsettings.get(
'org.gnome.desktop.interface', 'toolkit-accessibility',
self.username)
# Set gsettings keys
gsettings_keys = [
('org.gnome.desktop.lockdown', 'disable-lock-screen',
'true'),
('org.gnome.desktop.lockdown', 'disable-user-switching',
'true'),
('org.gnome.settings-daemon.plugins.background', 'active',
'true'),
('org.gnome.desktop.background', 'draw-background',
'true'),
('org.gnome.desktop.background', 'show-desktop-icons',
'false'),
('org.gnome.metacity', 'compositing-manager',
'true'),
('org.gnome.desktop.background', 'picture-options',
picture_option),
('org.gnome.desktop.background', 'picture-uri',
background_url),
('org.gnome.desktop.wm.preferences', 'num-workspaces',
'1'),
]
gsd = '/usr/lib/gnome-settings-daemon/gnome-settings-daemon'
if osextras.find_on_path(gsd):
extras.append(subprocess.Popen(
[gsd], stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
elif background_image and osextras.find_on_path('feh'):
subprocess.call(
['feh', '--bg-fill', background_image],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges)
for gs_schema, gs_key, gs_value in gsettings_keys:
subprocess.call(
['gsettings', 'set', gs_schema, gs_key, gs_value],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges)
# Accessibility infrastructure
with open('/proc/cmdline', 'r') as fp:
if (accessibility or 'maybe-ubiquity' in fp.readline() or
'only-ubiquity' in fp.readline() or
program_basename == 'oem-config-wrapper'):
launcher = '/usr/lib/at-spi2-core/at-spi-bus-launcher'
if os.path.exists(launcher):
extras.append(subprocess.Popen(
[launcher, '--launch-immediately'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
os.environ['GTK_MODULES'] += os.pathsep + 'gail'
if osextras.find_on_path('gnome-shell'):
wm_cmd = ['gnome-shell', '--sm-disable', '--mode=ubiquity']
elif osextras.find_on_path('metacity'):
wm_cmd = ['metacity', '--sm-disable']
elif osextras.find_on_path('xfwm4'):
wm_cmd = ['xfwm4', '--compositor=off']
elif osextras.find_on_path('matchbox-window-manager'):
wm_cmd = ['matchbox-window-manager']
elif osextras.find_on_path('openbox-lubuntu'):
wm_cmd = ['openbox-lubuntu']
elif osextras.find_on_path('openbox'):
wm_cmd = ['openbox']
elif osextras.find_on_path('compiz'):
wm_cmd = ['compiz', '--sm-disable', 'decor', 'resize', 'place',
'move']
else:
raise MissingProgramError(
'No window manager found (tried '
'metacity, xfwm4, matchbox-window-manager, '
'openbox-lubuntu, openbox, compiz)')
wm = subprocess.Popen(
wm_cmd, stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges)
if osextras.find_on_path('xfsettingsd'):
extras.append(subprocess.Popen(
['xsetroot', '-solid', 'black'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
extras.append(subprocess.Popen(
['xfsettingsd'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
if osextras.find_on_path('lxsession'):
extras.append(subprocess.Popen(
['lxsession', '-s', 'Lubuntu', '-e', 'LXDE', '-a'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
if (os.path.exists('/usr/lib/ubiquity/panel') and
"xfwm4" not in wm_cmd):
if ("openbox-lubuntu" not in wm_cmd and
"openbox" not in wm_cmd and
"gnome-shell" not in wm_cmd):
extras.append(subprocess.Popen(
['/usr/lib/ubiquity/panel'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
if (osextras.find_on_path('nm-applet') and
"gnome-shell" not in wm_cmd):
extras.append(subprocess.Popen(
['nm-applet'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
if osextras.find_on_path('ibus-daemon'):
extras.append(subprocess.Popen(
['ibus-daemon'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
# Simply start bluetooth-applet, ubiquity-bluetooth-agent will
# override it from casper to make sure it also covers the regular
# live session
if osextras.find_on_path('bluetooth-applet'):
extras.append(subprocess.Popen(
['bluetooth-applet'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
# Accessibility tools
if accessibility:
with open('/proc/cmdline', 'r') as fp:
if 'access=m2' in fp.readline():
if osextras.find_on_path('onboard'):
extras.append(subprocess.Popen(
['onboard'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
else:
if osextras.find_on_path('orca'):
time.sleep(15)
extras.append(subprocess.Popen(
['orca'],
stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges))
elif self.frontend == 'kde_ui':
# Don't show the background image in v1 accessibility profile.
os.setegid(self.gid)
os.seteuid(self.uid)
path = '/usr/share/wallpapers/kde-default.png'
with open('/proc/cmdline', 'r') as fp:
if (os.access(path, os.R_OK) and
not 'access=v1' in fp.readline()):
# Draw a background image for the install progress window.
from PyQt4.QtCore import Qt
from PyQt4 import QtGui
a = QtGui.QApplication(sys.argv)
root_win = a.desktop()
wallpaper = QtGui.QPixmap(path)
wallpaper = wallpaper.scaled(
root_win.width(), root_win.height(),
Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation)
palette = QtGui.QPalette()
palette.setBrush(root_win.backgroundRole(),
QtGui.QBrush(wallpaper))
root_win.setPalette(palette)
root_win.setCursor(Qt.ArrowCursor)
a.processEvents()
# Force garbage collection so we don't end up with stray X
# resources when we kill the X server (LP: #556555).
del a
os.seteuid(0)
os.setegid(0)
wm = subprocess.Popen(
'kwin', stdin=null, stdout=logfile, stderr=logfile,
preexec_fn=self.drop_privileges)
greeter = subprocess.Popen(
program, stdin=null, stdout=logfile, stderr=logfile)
ret = greeter.wait()
reboot = False
if ret != 0:
db = DebconfCommunicator('ubiquity', cloexec=True)
try:
error_cmd = db.get('ubiquity/failure_command')
if error_cmd:
subprocess.call(['sh', '-c', error_cmd])
except debconf.DebconfError:
pass
reboot = False
try:
if '--automatic' in program:
reboot = db.get('ubiquity/reboot_on_failure') == 'true'
except debconf.DebconfError:
pass
if reboot:
question = 'ubiquity/install_failed_reboot'
else:
question = 'ubiquity/install_failed'
title = ''
message = ''
try:
title = utf8(db.metaget(question, 'description'),
errors='replace')
message = utf8(db.metaget(question, 'extended_description'),
errors='replace')
except debconf.DebconfError:
pass
db.shutdown()
if title and message:
if self.frontend == 'gtk_ui':
cmd = ['zenity', '--error', '--title=%s' % title,
'--text=%s' % message]
subprocess.call(cmd)
elif self.frontend == 'kde_ui':
cmd = ['kdialog', '--title=%s' % title,
'--msgbox=%s' % message]
subprocess.call(cmd)
else:
# Not ideal, but if we cannot let the user know what's
# going on, it's best to drop them into a desktop and let
# them figure it out.
reboot = False
def kill_if_exists(pid, signum):
try:
os.kill(pid, signum)
except OSError as e:
if e.errno != errno.ESRCH:
raise
def sigalrm_handler(signum, frame):
kill_if_exists(wm.pid, signal.SIGKILL)
for extra in extras:
kill_if_exists(extra.pid, signal.SIGKILL)
kill_if_exists(wm.pid, signal.SIGTERM)
for extra in extras:
kill_if_exists(extra.pid, signal.SIGTERM)
signal.signal(signal.SIGALRM, sigalrm_handler)
signal.alarm(1) # low patience with WMs failing to exit on demand
processes = set(extras)
processes.add(wm)
while processes:
done = set()
for process in processes:
try:
process.wait()
done.add(process)
except OSError as e:
if e.errno == errno.EINTR:
continue
raise
processes -= done
signal.alarm(0)
# Clear the console so we don't see boot-time messages on switch
try:
with open('/dev/tty' + self.vt[2:], 'r+') as vthandle:
subprocess.call(['clear'], stdin=vthandle, stdout=vthandle)
except IOError:
pass
kill_if_exists(server.pid, signal.SIGTERM)
server.wait()
logfile.close()
null.close()
if reboot:
subprocess.Popen(['reboot'])
if ret is not None and ret >= 0:
return ret
else:
return 1
if len(sys.argv) < 4:
sys.stderr.write('Usage: %s <vt[1-N]> <:[0-N]> <username> <program> '
'[<arguments>]\n' % sys.argv[0])
sys.exit(1)
vt, display, username = sys.argv[1:4]
try:
dm = DM(vt, display, username)
except XStartupError:
sys.exit(1)
ret = dm.run(*sys.argv[4:])
if ret == 0:
set_locale()
sys.exit(ret)
|