This file is indexed.

/usr/lib/python3/dist-packages/lightdm_gtk_greeter_settings/helpers.py is in lightdm-gtk-greeter-settings 1.2.1-0ubuntu1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
#!/usr/bin/env python3
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
#   LightDM GTK Greeter Settings
#   Copyright (C) 2014 Andrew P. <pan.pav.7c5@gmail.com>
#
#   This program is free software: you can redistribute it and/or modify it
#   under the terms of the GNU General Public License version 3, as published
#   by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranties of
#   MERCHANTABILITY, SATISFACTORY QUALITY, 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, see <http://www.gnu.org/licenses/>.


import configparser
import glob
import locale
import os
import pwd
import stat

from collections import (
    namedtuple,
    OrderedDict,
    defaultdict)
from itertools import (
    chain,
    accumulate)
from locale import gettext as _

from gi.repository import (
    GdkPixbuf,
    GLib,
    GObject,
    Gtk,
    Pango)


__license__ = 'GPL-3'
__version__ = 'dev'
__data_directory__ = '../data/'
__config_path__ = 'lightdm/lightdm-gtk-greeter.conf'


try:
    from . installation_config import (
        __version__,
        __data_directory__,
        __config_path__)
except ImportError:
    pass


__all__ = [
    'bool2string',
    'C_',
    'clamp',
    'check_path_accessibility',
    'DefaultValueDict',
    'file_is_readable_by_greeter',
    'get_config_path',
    'get_data_path',
    'get_greeter_version'
    'get_markup_error',
    'get_version',
    'ModelRowEnum',
    'NC_',
    'pixbuf_from_file_scaled_down',
    'set_image_from_path',
    'show_message',
    'SimpleEnum',
    'SimpleDictWrapper',
    'string2bool',
    'TreeStoreDataWrapper',
    'WidgetsEnum',
    'WidgetsWrapper']


def C_(context, message):
    separator = '\x04'
    message_with_context = '{}{}{}'.format(context, separator, message)
    result = locale.gettext(message_with_context)
    if separator in result:
        return message
    return result


def NC_(context, message):
    return message


def get_data_path(*parts):
    return os.path.abspath(os.path.join(os.path.dirname(__file__),
                                        __data_directory__, *parts))


def get_config_path():
    return os.path.abspath(__config_path__)


def get_version():
    return __version__


def get_greeter_version():
    try:
        return get_greeter_version._version
    except AttributeError:
        try:
            get_greeter_version._version = int(os.getenv('GTK_GREETER_VERSION', '0x010900'), 16)
        except ValueError:
            get_greeter_version._version = 0x010900

    return get_greeter_version._version


def bool2string(value, skip_none=False):
    if isinstance(value, str):
        value = string2bool(value)
    return 'true' if value else 'false' if not skip_none or value is not None else None


def string2bool(value, fallback=False):
    if isinstance(value, str):
        if value in ('true', 'yes', '1'):
            return True
        if value in ('false', 'no', '0'):
            return False
    return fallback


def show_message(**kwargs):
    dialog = Gtk.MessageDialog(parent=Gtk.Window.list_toplevels()[0],
                               buttons=Gtk.ButtonsType.CLOSE, **kwargs)
    dialog.run()
    dialog.destroy()


def pixbuf_from_file_scaled_down(path, width, height):
    pixbuf = GdkPixbuf.Pixbuf.new_from_file(path)
    scale = max(pixbuf.props.width / width, pixbuf.props.height / height)

    if scale > 1:
        return GdkPixbuf.Pixbuf.scale_simple(pixbuf,
                                             pixbuf.props.width / scale,
                                             pixbuf.props.height / scale,
                                             GdkPixbuf.InterpType.BILINEAR)
    return pixbuf


def set_image_from_path(image, path):
    if not path or not os.path.isfile(path):
        image.props.icon_name = 'unknown'
    else:
        try:
            width, height = image.get_size_request()
            if -1 in (width, height):
                width, height = 64, 64
            pixbuf = pixbuf_from_file_scaled_down(path, width, height)
            image.set_from_pixbuf(pixbuf)
            return True
        except GLib.Error:
            image.props.icon_name = 'file-broken'
    return False


def check_path_accessibility(path, file=True, executable=False):
    """Return None  if file is readable by greeter and error message otherwise"""

    if not os.path.exists(path):
        return _('File not found: {path}').format(path=path)

    try:
        uid, gids = check_path_accessibility.id_cached_data
    except AttributeError:
        files = glob.glob('/etc/lightdm/lightdm.d/*.conf')
        files += ['/etc/lightdm/lightdm.conf']
        config = configparser.RawConfigParser(strict=False)
        config.read(files)
        username = config.get('LightDM', 'greeter-user', fallback='lightdm')

        pw = pwd.getpwnam(username)
        uid = pw.pw_uid
        gids = set(os.getgrouplist(username, pw.pw_gid))
        check_path_accessibility.id_cached_data = uid, gids

    parts = os.path.normpath(path).split(os.path.sep)
    if not parts[0]:
        parts[0] = os.path.sep

    def check(p):
        try:
            st = os.stat(p)
        except OSError as e:
            return _('Failed to check permissions: {error}'.format(error=e.strerror))

        if stat.S_ISDIR(st.st_mode) and not stat.S_IREAD:
            return _('Directory is not readable: {path}'.format(path=p))
        if st.st_uid == uid:
            return not (st.st_mode & stat.S_IRUSR) and \
                _('LightDM do not have permissions to read path: {path}'.format(path=p))
        if st.st_gid in gids:
            return not (st.st_mode & stat.S_IRGRP) and \
                _('LightDM do not have permissions to read path: {path}'.format(path=p))
        return not (st.st_mode & stat.S_IROTH) and \
            _('LightDM do not have permissions to read path: {path}'.format(path=p))

    errors = (check(p) for p in accumulate(parts, os.path.join))
    error = next((error for error in errors if error), None)

    if not error and file and not os.path.isfile(path):
        return _('Path is not a regular file: {path}'.format(path=path))

    if not error and executable:
        st = os.stat(path)
        if st.st_uid == uid:
            if not st.st_mode & stat.S_IXUSR:
                return _('LightDM do not have permissions to execute file: {path}'
                         .format(path=path))
        elif st.st_gid in gids:
            if not st.st_mode & stat.S_IXGRP:
                return _('LightDM do not have permissions to execute file: {path}'
                         .format(path=path))
        elif not st.st_mode & stat.S_IXOTH:
            return _('LightDM do not have permissions to execute file: {path}'.format(path=path))

    return error


def get_markup_error(markup):
    try:
        Pango.parse_markup(markup, -1, '\0')
    except GLib.Error as e:
        return e.message
    return None


def clamp(v, a, b):
    if v < a:
        return a
    if v > b:
        return b
    return v


class DefaultValueDict(defaultdict):

    def __init__(self, *items, default=None, factory=None, source=None):
        super().__init__(None, source or items)
        self._value = default
        self._factory = factory

    def __missing__(self, key):
        return self._factory(key) if self._factory else self._value


class SimpleEnumMeta(type):

    @classmethod
    def __prepare__(mcs, *args, **kwargs):
        return OrderedDict()

    def __new__(self, cls, bases, classdict):
        obj = super().__new__(self, cls, bases, classdict)
        obj._dict = OrderedDict((k, v)
                                for k, v in classdict.items() if obj._accept_member_(k, v))
        obj._tuple_type = namedtuple(obj.__class__.__name__ + 'Tuple', obj._dict.keys())
        keys = list(obj._dict.keys())
        for i in range(len(keys)):
            if obj._dict[keys[i]] is ():
                v = 0 if i == 0 else obj._dict[keys[i - 1]] + 1
                setattr(obj, keys[i], v)
                obj._dict[keys[i]] = v
        return obj

    def __contains__(self, value):
        return value in self._dict.values()

    def __iter__(self):
        return iter(self._dict.values())

    def _make(self, *args, **kwargs):
        return self._tuple_type._make(self._imake(*args, **kwargs))

    def _imake(self, *args, **kwargs):
        if args:
            return args
        elif kwargs:
            return (kwargs.get(k, v) for k, v in self._dict.items())
        else:
            return self._dict.values()


class SimpleEnum(metaclass=SimpleEnumMeta):
    _dict = None

    def __init__(self, *args, **kwargs):
        if kwargs:
            self.__dict__.update(kwargs)
        else:
            self.__dict__.update((k, args[i]) for i, k in enumerate(self._dict))

    def __iter__(self):
        return (self.__dict__[k] for k in self._dict)

    def __repr__(self):
        return repr(tuple((k, self.__dict__[k]) for k in self._dict))

    @classmethod
    def _accept_member_(cls, name, value):
        return not name.startswith('_') and not name.endswith('_')


class WidgetsEnum(SimpleEnum):

    def __init__(self, wrapper=None, builder=None):
        getter = wrapper.__getitem__ if wrapper else builder.get_object
        for k, v in self._dict.items():
            if isinstance(v, type) and issubclass(v, WidgetsEnum):
                self.__dict__[k] = v(WidgetsWrapper(wrapper or builder, k))
            else:
                self.__dict__[k] = getter(v or k)


class WidgetsWrapper:
    _builder = None
    _prefixes = None

    def __init__(self, source, *prefixes):
        if source is None:
            return
        if isinstance(source, Gtk.Builder):
            self._builder = source
            self._prefixes = tuple(prefixes)
        elif isinstance(source, WidgetsWrapper):
            self._builder = source._builder
            self._prefixes = source._prefixes + tuple(prefixes)
        else:
            raise TypeError(source)

    def __getitem__(self, args):
        if not self._builder:
            return None
        if not isinstance(args, tuple):
            args = (args,)
        return self._builder.get_object('_'.join(chain(self._prefixes, args)))

    @property
    def path(self):
        return '_'.join(self._prefixes) if self._prefixes else ''


class TreeStoreDataWrapper(GObject.Object):

    def __init__(self, data):
        super().__init__()
        self.data = data


class SimpleDictWrapper:

    def __init__(self, getter=None, setter=None, add=None, deleter=None, itergetter=None):
        self._getter = getter
        self._setter = setter
        self._deleter = deleter
        self._itergetter = itergetter
        self._add = add

    def __getitem__(self, key):
        return self._getter(key)

    def __setitem__(self, key, value):
        return self._setter(key, value)

    def __delitem__(self, key):
        return self._deleter(key)

    def __iter__(self):
        return self._itergetter()

    def add(self, value):
        return self._add(value)