~rodrigo-moya/system-service/fix-877088

« back to all changes in this revision

Viewing changes to UbuntuSystemService/utils.py

  • Committer: Michael Vogt
  • Date: 2011-11-28 10:44:45 UTC
  • mfrom: (62.1.9 new-interfaces)
  • Revision ID: michael.vogt@ubuntu.com-20111128104445-2o81yojdodbr0jog
* merged lp:~rodrigo-moya/system-service/new-interfaces:
  - add org.freedesktop.hostname1 and org.freedesktop.locale1
    interfaces for systemd compatbility

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
import os
1
2
import re
 
3
import dbus
 
4
import subprocess
 
5
 
 
6
CONSOLE_SETUP_DEFAULT = "/etc/default/keyboard"
 
7
 
 
8
class UnknownProxyTypeError(dbus.DBusException):
 
9
    " an unknown proxy type was passed "
 
10
    pass
 
11
class InvalidKeyboardTypeError(dbus.DBusException):
 
12
    " an invalid keyboard was set "
 
13
    pass
 
14
class PermissionDeniedError(dbus.DBusException):
 
15
    " permission denied by policy "
 
16
    pass
 
17
 
 
18
def authWithPolicyKit(sender, connection, priv, interactive=1):
 
19
    #print "_authWithPolicyKit()"
 
20
    system_bus = dbus.SystemBus()
 
21
    obj = system_bus.get_object("org.freedesktop.PolicyKit1", 
 
22
                                "/org/freedesktop/PolicyKit1/Authority", 
 
23
                                "org.freedesktop.PolicyKit1.Authority")
 
24
    policykit = dbus.Interface(obj, "org.freedesktop.PolicyKit1.Authority")
 
25
    info = dbus.Interface(connection.get_object('org.freedesktop.DBus',
 
26
                                                '/org/freedesktop/DBus/Bus', 
 
27
                                                False), 
 
28
                          'org.freedesktop.DBus')
 
29
    pid = info.GetConnectionUnixProcessID(sender) 
 
30
    #print "pid is:",pid
 
31
    #print "priv: ", priv
 
32
    subject = ('unix-process', 
 
33
               { 'pid' : dbus.UInt32(pid, variant_level=1),
 
34
                 'start-time' : dbus.UInt64(0),
 
35
                 }
 
36
               )
 
37
    details = { '' : '' }
 
38
    flags = dbus.UInt32(interactive) #   AllowUserInteraction = 0x00000001
 
39
    cancel_id = ''
 
40
    (ok, notused, details) = policykit.CheckAuthorization(subject,
 
41
                                                          priv, 
 
42
                                                          details,
 
43
                                                          flags,
 
44
                                                          cancel_id)
 
45
    #print "ok: ", ok
 
46
    return ok
 
47
 
 
48
def get_keyboard_from_etc():
 
49
    """ 
 
50
    helper that reads /etc/default/console-setup and gets the 
 
51
    keyboard settings there
 
52
    """
 
53
    model = ""
 
54
    layout = ""
 
55
    variant = ""
 
56
    options = ""
 
57
    try:
 
58
        f = open(CONSOLE_SETUP_DEFAULT)
 
59
        for line in f:
 
60
            if line.startswith("XKBMODEL="):
 
61
                model = line.split("=")[1].strip('"\n')
 
62
            elif line.startswith("XKBLAYOUT="):
 
63
                layout = line.split("=")[1].strip('"\n')
 
64
            elif line.startswith("XKBVARIANT="):
 
65
                variant = line.split("=")[1].strip('"\n')
 
66
            elif line.startswith("XKBOPTIONS="):
 
67
                options = line.split("=")[1].strip('"\n')
 
68
 
 
69
        f.close()
 
70
        print (model, layout, variant, options)
 
71
    except Exception:
 
72
        print "Couldn't read ", CONSOLE_SETUP_DEFAULT
 
73
 
 
74
    return (model, layout, variant, options)
 
75
 
 
76
def run_setupcon():
 
77
    """
 
78
    helper that runs setupcon to activate the settings, taken from 
 
79
    oem-config (/usr/lib/oem-config/console/console-setup-apply)
 
80
    """
 
81
    ret = subprocess.call(["setupcon","--save-only"])
 
82
    subprocess.Popen(["/usr/sbin/update-initramfs","-u"])
 
83
    return (ret == 0)
 
84
 
 
85
def set_keyboard_to_etc(model, layout, variant, options):
 
86
    """ 
 
87
    helper that writes /etc/default/console-setup 
 
88
    """
 
89
    # if no keyboard model is set, try to guess one
 
90
    # this is based on the "console-setup.config" code that
 
91
    # defaults to pc105
 
92
    if not model:
 
93
        model = "pc105"
 
94
        if layout == "us":
 
95
            model = "pc104"
 
96
        elif layout == "br":
 
97
            model = "abnt2"
 
98
        elif layout == "jp":
 
99
            model = "jp106"
 
100
 
 
101
    # verify the settings
 
102
    if not verify_keyboard_settings(model, layout, variant, options):
 
103
        #print "verify_keyboard failed"
 
104
        raise InvalidKeyboardTypeError, "Invalid keyboard set"
 
105
 
 
106
    # FIXME: what to do if not os.path.exists(CONSOLE_SETUP_DEFAULT)
 
107
    content = []
 
108
    for line in open(CONSOLE_SETUP_DEFAULT):
 
109
        if line.startswith("XKBMODEL="):
 
110
            line = 'XKBMODEL="%s"\n' % model
 
111
        elif line.startswith("XKBLAYOUT="):
 
112
            line = 'XKBLAYOUT="%s"\n' % layout
 
113
        elif line.startswith("XKBVARIANT="):
 
114
            line = 'XKBVARIANT="%s"\n' % variant
 
115
        elif line.startswith("XKBOPTIONS="):
 
116
            line = 'XKBOPTIONS="%s"\n' % options
 
117
        content.append(line)
 
118
    # if something changed, write 
 
119
    if content != open(CONSOLE_SETUP_DEFAULT).readlines():
 
120
        #print "content changed, writing"
 
121
        open(CONSOLE_SETUP_DEFAULT+".new","w").write("".join(content))
 
122
        os.rename(CONSOLE_SETUP_DEFAULT+".new", 
 
123
                  CONSOLE_SETUP_DEFAULT)
 
124
 
 
125
    if not run_setupcon():
 
126
        #print "setupcon failed"
 
127
        return False
 
128
 
 
129
    return True
 
130
 
 
131
def verify_keyboard_settings(model, layout, variant, options):
 
132
    " helper that verfies the settings "
 
133
    # check against char whitelist
 
134
    allowed = "^[0-9a-zA-Z:,_]*$"
 
135
    for s in (model, layout, variant, options):
 
136
        if not re.match(allowed, s):
 
137
            #print "illegal chars in '%s'" % s
 
138
            return False
 
139
    # check if 'ckbcomp' can compile it
 
140
    cmd = ["ckbcomp"]
 
141
    if model:
 
142
        cmd += ["-model",model]
 
143
    if layout:
 
144
        cmd += ["-layout", layout]
 
145
    if variant:
 
146
        cmd += ["-variant", variant]
 
147
    if options:
 
148
        cmd += ["-option", options]
 
149
    ret = subprocess.call(cmd, stdout=open(os.devnull))
 
150
    return (ret == 0)
2
151
 
3
152
def verify_proxy(proxy_type, proxy):
4
153
    """