~aw/sabayon-template/trunk

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
#
# Copyright (C) 2005 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import os
import os.path
import sys
import shutil
import tempfile
import pwd
import gobject
import gtk
import storage
import editorwindow
import usersdialog
import groupsdialog
import util
import systemdb
import protosession
import debuglog
import errors
from config import *

#
# Try to import selinux
#

try:
    import selinux
    has_selinux = True;
except ImportError:
    has_selinux = False;

def dprint (fmt, *args):
    debuglog.debug_log (False, debuglog.DEBUG_LOG_DOMAIN_ADMIN_TOOL, fmt % args)

def mprint (fmt, *args):
    debuglog.debug_log (True, debuglog.DEBUG_LOG_DOMAIN_ADMIN_TOOL, fmt % args)

def _get_profile_path_for_name (profile_name):
    return os.path.join (PROFILESDIR, profile_name + ".zip")

class Session (gobject.GObject):
    __gsignals__ = {
        "finished" : (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ())
        }

    def __init__ (self, username, profile_name):
        gobject.GObject.__init__ (self)

        self.username     = username
        self.profile_name = profile_name
        self.profile_path = _get_profile_path_for_name (profile_name)

        self.pw = pwd.getpwnam (self.username)

        self.user_profile_path = None
        self.temp_homedir      = None

        self.session_pid             = 0
        self.session_child_watch     = 0
        self.session_stderr          = None
        self.session_stderr_watch_id = 0
        self.session_log_str         = ""

    def __del__ (self):
        if self.temp_homedir:
            protosession.reset_shell_and_homedir (self.username, self.temp_homedir)
            self.temp_homedir = None
        if self.user_profile_path:
            os.remove (self.user_profile_path)
            self.user_profile_path = None
        if self.temp_xauth_path:
            os.remove (self.temp_xauth_path)
            self.temp_xauth_path = None

    def __copy_xauthority (self):
        if not os.environ.has_key ("XAUTHORITY"):
            return None

        xauthority = os.environ["XAUTHORITY"]

        (fd, temp_path) = tempfile.mkstemp (prefix = "xauth-%s-" % self.username)
        os.close (fd)

        shutil.copy2 (xauthority, temp_path)

        os.chown (temp_path, self.pw.pw_uid, self.pw.pw_gid)

        dprint ("Copied $XAUTHORITY (%s) temporarily to %s", xauthority, temp_path)

        return temp_path

    def __copy_to_user (self, profile_path):
        (fd, user_path) = tempfile.mkstemp (prefix = "profile-%s-" % self.username, suffix = ".zip")
        os.close (fd)

        shutil.copy2 (profile_path, user_path)

        os.chown (user_path, self.pw.pw_uid, self.pw.pw_gid)

        dprint ("Copied %s temporarily to %s", profile_path, user_path)

        return user_path

    def __copy_from_user (self, user_path, profile_path):
        global has_selinux
        os.chown (user_path, os.geteuid (), os.getegid ())
        shutil.move (user_path, profile_path)
        if has_selinux:
            if selinux.is_selinux_enabled() > 0:
                rc, con = selinux.matchpathcon(profile_path, 0)
                if rc == 0:
                    selinux.setfilecon(profile_path, con)

        dprint ("Moved %s back from %s", user_path, profile_path)

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_ADMIN_TOOL)
    def __session_child_watch_handler (self, pid, status):
        if not os.WIFEXITED (status):
            exit_code = util.EXIT_CODE_FATAL

            if os.WIFSIGNALED (status):
                signal_num = os.WTERMSIG (status)

                mprint ("sabayon-session exited with SIGNAL %s", signal_num)
            else:
                mprint ("sabayon-session exited for an unknown reason")
        else:
            exit_code = os.WEXITSTATUS (status)

            # Here we cannot throw an exception for the error cases,
            # since we are a callback running out of the Glib main
            # loop.  So we have to set a flag and let the code
            # *outside* the main loop pick it up.

            if exit_code == util.EXIT_CODE_NORMAL:
                mprint ("sabayon-session exited normally")
                success = True
            elif exit_code == util.EXIT_CODE_RECOVERABLE:
                errors.errors_log_recoverable_error (debuglog.DEBUG_LOG_DOMAIN_ADMIN_TOOL,
                                                     "sabayon-session exited with RECOVERABLE exit status")
                # FIXME: throw a warning dialog
            else:
                errors.errors_log_fatal_error (debuglog.DEBUG_LOG_DOMAIN_ADMIN_TOOL,
                                               "sabayon-session exited with a FATAL ERROR (exit code %s)" % exit_code)
                gtk.main_quit () # so that the toplevel 'sabayon' will exit the main loop and show the fatal error

        protosession.clobber_user_processes (self.username)
        protosession.reset_shell_and_homedir (self.username, self.temp_homedir)
        self.temp_homedir = None

        if self.temp_xauth_path:
            os.remove (self.temp_xauth_path)
            self.temp_xauth_path = None

        self.__copy_from_user (self.user_profile_path, self.profile_path)
        self.user_profile_path = None

        self.session_pid         = 0
        self.session_child_watch = 0

        #gobject.source_remove (self.session_stderr_watch_id)
        #self.session_stderr_watch_id = 0

        #self.session_stderr.close ()
        #self.session_stderr = None

        self.emit ("finished")

        return False

    def build_envp_for_child (self):
        # gobject.spawn_async() wants a sequence, not a dictionary, so we build a sequence...
        new_environ = []
        for key in PASSTHROUGH_ENVIRONMENT:
            if os.environ.has_key (key):
                new_environ.append ("%s=%s" % (key, os.environ[key]))

        new_environ = new_environ + ["PATH=%s"     % DEFAULT_PATH,
                                     "SHELL=%s"    % DEFAULT_SHELL,
                                     "DISPLAY=%s"  % os.environ["DISPLAY"],
                                     "HOME=%s"     % self.temp_homedir,
                                     "LOGNAME=%s"  % self.pw.pw_name,
                                     "USER=%s"     % self.pw.pw_name,
                                     "USERNAME=%s" % self.pw.pw_name]

        if self.temp_xauth_path:
            new_environ.append ("XAUTHORITY=%s" % self.temp_xauth_path)

            if os.environ.has_key ("XAUTHLOCALHOSTNAME"):
                new_environ.append ("XAUTHLOCALHOSTNAME=%s" % os.environ["XAUTHLOCALHOSTNAME"])

        return new_environ

    #@errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_ADMIN_TOOL)
    #def session_stderr_io_cb (self, source_fd, condition, session):
    #    if condition & gobject.IO_IN:
    #        s = session.session_stderr.read ()
    #        session.session_log_str = session.session_log_str + s
    #        print "%s: got from sabayon-session stderr: \n<BEGIN SABAYON-SESSION STDERR>\n%s\n<END SABAYON-SESSION STDERR>" % (os.getpid (), s)
    #
    #    if condition & gobject.IO_HUP:
    #        mprint ("========== BEGIN SABAYON-SESSION LOG ==========\n"
    #                "%s\n"
    #                "========== END SABAYON-SESSION LOG ==========",
    #                session.session_log_str)
    #        return False
    #
    #    return True

    def start (self):
        self.user_profile_path = self.__copy_to_user (self.profile_path)
        protosession.clobber_user_processes (self.username)
        self.temp_homedir = protosession.setup_shell_and_homedir (self.username)

        display_number = protosession.find_free_display ()

        self.temp_xauth_path = self.__copy_xauthority ()

        def child_setup_fn (self):
            os.setgid (self.pw.pw_gid)
            os.setuid (self.pw.pw_uid)
            os.setsid ()
            os.umask (022)

        # FIXME: get_readable_log_config_filename() doesn't work here.
        # Create a temporary copy of the log config file and use *that*.
        argv = SESSION_TOOL_ARGV + [ ("--admin-log-config=%s" % util.get_admin_log_config_filename ()),
                                     ("--readable-log-config=%s" % util.get_readable_log_config_filename ()),
                                     self.profile_name,
                                     self.user_profile_path,
                                     str (display_number) ]
        envp = self.build_envp_for_child ()
        cwd = self.temp_homedir

        # FIXME: do we need any special processing if this throws an exception?
        # We'll catch it in the toplevel and exit with a fatal error code, anyway.
        (pid, oink, oink, oink) = gobject.spawn_async (argv, envp, cwd,
                                                       gobject.SPAWN_DO_NOT_REAP_CHILD,
                                                       child_setup_fn, self,
                                                       None, None, None)# stdin, stdout, stderr

        self.session_pid = pid;
        #self.session_stderr = os.fdopen (stderr_fd)
        #self.session_stderr_watch_id = gobject.io_add_watch (stderr_fd,
        #                                                     gobject.IO_IN | gobject.IO_HUP,
        #                                                     self.session_stderr_io_cb, self)
        self.session_child_watch = gobject.child_watch_add (self.session_pid,
                                                            self.__session_child_watch_handler)

gobject.type_register (Session)

class ProfilesModel (gtk.ListStore):
    (
        COLUMN_NAME,
    ) = range (1)

    def __init__ (self):
        gtk.ListStore.__init__ (self, str)
        self.reload ()

    def reload (self):
        self.clear ()
        profiles = systemdb.get_user_database ().get_profiles ()
        profiles.sort ()
        for profile in profiles:
            self.set (self.append (),
                      self.COLUMN_NAME, profile)

class AddProfileDialog:
    def __init__ (self, profiles_model):
        self.profiles_model = profiles_model
        self.ui_objects_list = [ "add_profile_dialog",
                                 "add_profile_add_button",
                                 "add_profile_name_entry",
                                 "add_profile_base_combo" ]

        self.builder = gtk.Builder ();
        self.builder.set_translation_domain (PACKAGE)
        self.builder.add_objects_from_file (os.path.join (BUILDERDIR, "sabayon.ui"), self.ui_objects_list)
         
        self.dialog = self.builder.get_object ("add_profile_dialog")
        self.dialog.connect ("destroy", gtk.main_quit)
        self.dialog.set_default_response (gtk.RESPONSE_ACCEPT)
        self.dialog.set_icon_name ("sabayon")

        self.add_button = self.builder.get_object ("add_profile_add_button")
        self.add_button.set_sensitive (False)

        self.name_entry = self.builder.get_object ("add_profile_name_entry")
        self.name_entry.connect ("changed", self.__name_entry_changed)
        self.name_entry.set_activates_default (True)

        self.base_combo = self.builder.get_object ("add_profile_base_combo")
        self.base_combo.set_model (self.profiles_model)
        if self.profiles_model.get_iter_first () is None:
            self.base_combo.set_sensitive (False)

        renderer = gtk.CellRendererText ()
        self.base_combo.pack_start (renderer, True)
        self.base_combo.set_attributes (renderer, text = ProfilesModel.COLUMN_NAME)

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __name_entry_changed (self, entry):
        text = entry.get_text ()
        if not text or text.isspace ():
            self.add_button.set_sensitive (False)
        else:
            self.add_button.set_sensitive (True)

    def run (self, parent):
        self.name_entry.grab_focus ()
        self.dialog.set_transient_for (parent)
        self.dialog.present ()
        response = self.dialog.run ()
        self.dialog.hide ()

        if response != gtk.RESPONSE_ACCEPT:
            return (None, None)

        row = self.base_combo.get_active_iter ()
        if row:
            base = self.profiles_model.get_value (row, ProfilesModel.COLUMN_NAME)
        else:
            base = None

        return (self.name_entry.get_text (), base)

class ProfilesDialog:
    def __init__ (self):
        assert os.geteuid () == 0
        self.ui_objects_list = [ "profiles_dialog",
                                 "profiles_list",
                                 "add_button",
                                 "remove_button",
                                 "edit_button",
                                 "details_button",
                                 "users_button",
                                 "groups_button" ]



        self.builder = gtk.Builder ();
        self.builder.set_translation_domain (PACKAGE)
        self.builder.add_objects_from_file (os.path.join (BUILDERDIR, "sabayon.ui"), self.ui_objects_list)

        self.dialog = self.builder.get_object ("profiles_dialog")
        self.dialog.connect ("destroy", gtk.main_quit)
        self.dialog.set_default_response (gtk.RESPONSE_ACCEPT)
        self.dialog.set_icon_name ("sabayon")

        self.profiles_list = self.builder.get_object ("profiles_list")
        self.__setup_profiles_list ()

        self.profiles_list.connect ("key-press-event", self.__handle_key_press)
        self.profiles_list.connect ("row-activated", self.__profile_row_activated)


        self.add_button = self.builder.get_object ("add_button")
        self.add_button.connect ("clicked", self.__add_button_clicked)

        self.remove_button = self.builder.get_object ("remove_button")
        self.remove_button.connect ("clicked", self.__remove_button_clicked)

        self.edit_button = self.builder.get_object ("edit_button")
        self.__fix_button_align (self.edit_button)
        self.edit_button.connect ("clicked", self.__edit_button_clicked)

        self.details_button = self.builder.get_object ("details_button")
        self.__fix_button_align (self.details_button)
        self.details_button.connect ("clicked", self.__details_button_clicked)

        self.users_button = self.builder.get_object ("users_button")
        self.__fix_button_align (self.users_button)
        self.users_button.connect ("clicked", self.__users_button_clicked)

        self.groups_button = self.builder.get_object ("groups_button")
        self.__fix_button_align (self.groups_button)
        self.groups_button.connect ("clicked", self.__groups_button_clicked)

        self.dialog.connect ("response", self.__dialog_response)

        (width, height) = self.profiles_list.size_request ()

        self.dialog.set_default_size (min (width + 250, 450),
                                      min (height + 190, 400))

        self.profiles_list.grab_focus ()
        self.__profile_selection_changed (self.profiles_list.get_selection ())

        self.dialog.show ()

    def __fix_button_align (self, button):
        child = button.get_child ()

        if isinstance (child, gtk.Alignment):
            child.set_property ("xalign", 0.0)
        elif isinstance (child, gtk.Label):
            child.set_property ("xalign", 0.0)

    def __setup_profiles_list (self):
        self.profiles_model = ProfilesModel ()
        self.profiles_list.set_model (self.profiles_model)

        self.profiles_list.get_selection ().set_mode (gtk.SELECTION_SINGLE)
        self.profiles_list.get_selection ().connect ("changed", self.__profile_selection_changed)

        c = gtk.TreeViewColumn (_("Name"),
                                gtk.CellRendererText (),
                                text = ProfilesModel.COLUMN_NAME)
        self.profiles_list.append_column (c)

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __dialog_response (self, dialog, response_id):
        dialog.destroy ()

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __add_button_clicked (self, button):
        (profile_name, base_profile) = AddProfileDialog (self.profiles_model).run (self.dialog)
        if profile_name:
            self.__create_new_profile (profile_name, base_profile)

    def __get_selected_profile (self):
        (model, row) = self.profiles_list.get_selection ().get_selected ()
        if not row:
            return None
        return model[row][ProfilesModel.COLUMN_NAME]

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_ADMIN_TOOL)
    def __session_finished (self, session):
        debuglog.uprint ("Finishing editing profile")
        self.dialog.set_sensitive (True)

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __edit_button_clicked (self, button):
        profile_name = self.__get_selected_profile ()
        if profile_name:
            self.dialog.set_sensitive (False)

            session = Session (PROTOTYPE_USER, profile_name)
            session.connect ("finished", self.__session_finished)
            debuglog.uprint ("Starting to edit profile '%s'", profile_name)
            session.start ()

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __profile_row_activated (self, treeview, path, column):
        profile_name = self.__get_selected_profile ()
        if profile_name:
            self.dialog.set_sensitive (False)

            session = Session (PROTOTYPE_USER, profile_name)
            session.connect ("finished", self.__session_finished)
            debuglog.uprint ("Starting to edit profile '%s'", profile_name)
            session.start ()

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __details_button_clicked (self, button):
        profile_name = self.__get_selected_profile ()
        if profile_name:
            editorwindow.ProfileEditorWindow (profile_name, self.dialog)

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __users_button_clicked (self, button):
        profile_name = self.__get_selected_profile ()
        if profile_name:
            usersdialog.UsersDialog (profile_name, self.dialog)

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __groups_button_clicked (self, button):
        profile_name = self.__get_selected_profile ()
        if profile_name:
            groupsdialog.GroupsDialog (profile_name, self.dialog)

    def __delete_currently_selected (self):
        (model, selected) = self.profiles_list.get_selection ().get_selected ()
        if selected:
            if model.iter_next (selected):
                select = model[model.iter_next (selected)][ProfilesModel.COLUMN_NAME]
            else:
                select = None
                row = model.get_iter_first ()
                while row and model.iter_next (row):
                    next = model.iter_next (row)
                    if model.get_string_from_iter (next) == model.get_string_from_iter (selected):
                        select = model[row][ProfilesModel.COLUMN_NAME]
                        break
                    row = next

            profile_name = model[selected][ProfilesModel.COLUMN_NAME]
            dprint ("Deleting '%s'", profile_name)
            os.remove (_get_profile_path_for_name (profile_name))

            db = systemdb.get_user_database ()
            if db.get_default_profile (False) == profile_name:
                db.set_default_profile (None)
            for user in db.get_users ():
                if db.get_profile (user, False, True) == profile_name:
                    db.set_profile (user, None)

            self.profiles_model.reload ()

            row = None
            if select:
                row = self.profiles_model.get_iter_first ()
                while row:
                    if select == model[row][ProfilesModel.COLUMN_NAME]:
                        break
                    row = model.iter_next (row)
            if not row:
                row = self.profiles_model.get_iter_first ()
            if row:
                self.profiles_list.get_selection ().select_iter (row)

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __remove_button_clicked (self, button):
        self.__delete_currently_selected ()

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __handle_key_press (self, profiles_list, event):
        if event.keyval in (gtk.keysyms.Delete, gtk.keysyms.KP_Delete):
            self.__delete_currently_selected ()

    def __make_unique_profile_name (self, profile_name):
        profiles = systemdb.get_user_database ().get_profiles ()

        name = profile_name
        idx = 1
        while name in profiles:
            #
            # Translators: this string specifies how a profile
            #              name is concatenated with an integer
            #              to form a unique profile name e.g.
            #              "Artist Workstation (5)"
            #
            name = _("%s (%s)") % (profile_name, idx)
            idx += 1

        return name

    def __create_new_profile (self, profile_name, base_profile):
        profile_name = self.__make_unique_profile_name (profile_name)

        if base_profile:
            base_storage = storage.ProfileStorage (base_profile)
            new_storage = base_storage.copy (profile_name)
        else:
            new_storage = storage.ProfileStorage (profile_name)
            new_storage.save ()

        self.profiles_model.reload ()
        row = self.profiles_model.get_iter_first ()
        while row:
            if self.profiles_model[row][ProfilesModel.COLUMN_NAME] == profile_name:
                self.profiles_list.get_selection ().select_iter (row)
                return
            row = self.profiles_model.iter_next (row)

    @errors.checked_callback (debuglog.DEBUG_LOG_DOMAIN_USER)
    def __profile_selection_changed (self, selection):
        profile_name = self.__get_selected_profile ()
        self.edit_button.set_sensitive (profile_name != None)
        self.details_button.set_sensitive (profile_name != None)
        self.users_button.set_sensitive (profile_name != None)
        self.groups_button.set_sensitive (profile_name != None)
        self.remove_button.set_sensitive (profile_name != None)