def _get_disks_from_udisks():
    """List devices that can be ejected."""
    udisks = utils.import_from_gi('UDisks', '2.0')
    client = udisks.Client.new_sync()
    object_manager = client.get_object_manager()
    devices = []

    for obj in object_manager.get_objects():

        if not obj.get_block():
            continue

        block = obj.get_block()

        if block.props.id_usage != 'filesystem':
            continue

        device = {
            'device': block.props.device,
            'label': block.props.id_label,
            'size': format_bytes(block.props.size),
            'filesystem_type': block.props.id_type,
            'is_removable': not block.props.hint_system
        }
        try:
            device['mount_point'] = obj.get_filesystem().props.mount_points[0]
        except Exception:
            continue
        devices.append(device)

    return devices
def get_error_message(error):
    """Return an error message given an exception."""
    udisks = import_from_gi('UDisks', '2.0')
    if error.matches(udisks.Error.quark(), udisks.Error.FAILED):
        message = _('The operation failed.')
    elif error.matches(udisks.Error.quark(), udisks.Error.CANCELLED):
        message = _('The operation was cancelled.')
    elif error.matches(udisks.Error.quark(), udisks.Error.ALREADY_UNMOUNTING):
        message = _('The device is already unmounting.')
    elif error.matches(udisks.Error.quark(), udisks.Error.NOT_SUPPORTED):
        message = _('The operation is not supported due to '
                    'missing driver/tool support.')
    elif error.matches(udisks.Error.quark(), udisks.Error.TIMED_OUT):
        message = _('The operation timed out.')
    elif error.matches(udisks.Error.quark(), udisks.Error.WOULD_WAKEUP):
        message = _('The operation would wake up a disk that is '
                    'in a deep-sleep state.')
    elif error.matches(udisks.Error.quark(), udisks.Error.DEVICE_BUSY):
        message = _('Attempting to unmount a device that is busy.')
    elif error.matches(udisks.Error.quark(), udisks.Error.ALREADY_CANCELLED):
        message = _('The operation has already been cancelled.')
    elif error.matches(udisks.Error.quark(), udisks.Error.NOT_AUTHORIZED) or \
        error.matches(udisks.Error.quark(),
                      udisks.Error.NOT_AUTHORIZED_CAN_OBTAIN) or \
        error.matches(udisks.Error.quark(),
                      udisks.Error.NOT_AUTHORIZED_DISMISSED):
        message = _('Not authorized to perform the requested operation.')
    elif error.matches(udisks.Error.quark(), udisks.Error.ALREADY_MOUNTED):
        message = _('The device is already mounted.')
    elif error.matches(udisks.Error.quark(), udisks.Error.NOT_MOUNTED):
        message = _('The device is not mounted.')
    elif error.matches(udisks.Error.quark(),
                       udisks.Error.OPTION_NOT_PERMITTED):
        message = _('Not permitted to use the requested option.')
    elif error.matches(udisks.Error.quark(),
                       udisks.Error.MOUNTED_BY_OTHER_USER):
        message = _('The device is mounted by another user.')
    else:
        message = error.message

    return message
Example #3
0
def fixture_network_module_init():
    """Initialize network module in a separate thread."""
    from plinth import network as network_module
    glib = import_from_gi('GLib', '2.0')
    main_loop = glib.MainLoop()

    def main_loop_runner():
        """Initialize the network module and run glib main loop until quit."""
        network_module.init()
        main_loop.run()

    thread = threading.Thread(target=main_loop_runner)
    thread.start()

    while not network_module._client:
        time.sleep(0.1)

    yield

    if main_loop:
        main_loop.quit()

    thread.join()
Example #4
0
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

from django import forms
from django.core import validators
from django.utils.translation import ugettext_lazy as _

from plinth import network
from plinth.utils import import_from_gi
nm = import_from_gi('NM', '1.0')


def _get_interface_choices(device_type):
    """Return a list of choices for a given device type."""
    interfaces = network.get_interface_list(device_type)
    choices = [('', _('-- select --'))]
    for interface, mac in interfaces.items():
        display_string = '{interface} ({mac})'.format(interface=interface,
                                                      mac=mac)
        choices.append((interface, display_string))

    return choices


class ConnectionTypeSelectForm(forms.Form):
Example #5
0
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""
Helper functions for working with network manager.
"""

import collections
from django.utils.translation import ugettext_lazy as _
import logging
import socket
import struct
import subprocess
import uuid

from plinth.utils import import_from_gi
glib = import_from_gi('GLib', '2.0')
nm = import_from_gi('NM', '1.0')

logger = logging.getLogger(__name__)

CONNECTION_TYPE_NAMES = collections.OrderedDict([
    ('802-3-ethernet', _('Ethernet')),
    ('802-11-wireless', _('Wi-Fi')),
    ('pppoe', _('PPPoE')),
    ('generic', _('Generic')),
])


class ConnectionNotFound(Exception):
    """Network connection with a given name could not be found."""
    pass
"""

import contextlib
import logging

from django.utils.translation import ugettext_lazy as _

from plinth import actions
from plinth import app as app_module
from plinth import cfg, menu
from plinth.daemon import Daemon
from plinth.utils import Version, format_lazy, import_from_gi

from .manifest import backup  # noqa, pylint: disable=unused-import

gio = import_from_gi('Gio', '2.0')
glib = import_from_gi('GLib', '2.0')

version = 2

is_essential = True

managed_packages = ['firewalld', 'nftables']

managed_services = ['firewalld']

_description = [
    format_lazy(_(
        'Firewall is a security system that controls the incoming and '
        'outgoing network traffic on your {box_name}. Keeping a '
        'firewall enabled and properly configured reduces risk of '
Example #7
0
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

from django import forms
from django.core import validators
from django.utils.translation import ugettext_lazy as _

from plinth import network
from plinth.utils import import_from_gi
nm = import_from_gi('NM', '1.0')


def _get_interface_choices(device_type):
    """Return a list of choices for a given device type."""
    interfaces = network.get_interface_list(device_type)
    choices = [('', _('-- select --'))]
    for interface, mac in interfaces.items():
        display_string = '{interface} ({mac})'.format(interface=interface,
                                                      mac=mac)
        choices.append((interface, display_string))

    return choices


class ConnectionTypeSelectForm(forms.Form):
Example #8
0
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

"""
Framework for installing and updating distribution packages
"""

from django.contrib import messages
from django.utils.translation import ugettext as _
import functools
import logging
import threading

import plinth
from plinth.utils import import_from_gi
glib = import_from_gi('GLib', '2.0')
packagekit = import_from_gi('PackageKitGlib', '1.0')


logger = logging.getLogger(__name__)
transactions = {}
packages_resolved = {}


class PackageException(Exception):
    """A package operation has failed."""

    def __init__(self, error_string=None, error_details=None, *args, **kwargs):
        """Store packagekit error string and details."""
        super(PackageException, self).__init__(*args, **kwargs)
Example #9
0
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Expose some API over D-Bus.
"""

import logging
import threading

from plinth.utils import import_from_gi

from . import setup

gio = import_from_gi('Gio', '2.0')

logger = logging.getLogger(__name__)

_server = None


class PackageHandler():
    """D-Bus service to listen for messages when apt cache is updated."""

    introspection_xml = '''
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
  "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node name="/org/freedombox/Service/PackageHandler">
  <interface name="org.freedombox.Service.PackageHandler">
    <method name="CacheUpdated"/>
  </interface>
</node>
Example #10
0
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""
Framework for installing and updating distribution packages
"""

from django.contrib import messages
from django.utils.translation import ugettext as _
import functools
import logging
import threading

import plinth
from plinth.utils import import_from_gi
glib = import_from_gi('GLib', '2.0')
packagekit = import_from_gi('PackageKitGlib', '1.0')

logger = logging.getLogger(__name__)
transactions = {}
packages_resolved = {}


class PackageException(Exception):
    """A package operation has failed."""
    def __init__(self, error_string=None, error_details=None, *args, **kwargs):
        """Store packagekit error string and details."""
        super(PackageException, self).__init__(*args, **kwargs)

        self.error_string = error_string
        self.error_details = error_details
Example #11
0
#

"""
Helper functions for working with network manager.
"""

import collections
from django.utils.translation import ugettext_lazy as _
import logging
import socket
import struct
import subprocess
import uuid

from plinth.utils import import_from_gi
glib = import_from_gi('GLib', '2.0')
nm = import_from_gi('NM', '1.0')

logger = logging.getLogger(__name__)

CONNECTION_TYPE_NAMES = collections.OrderedDict([
    ('802-3-ethernet', _('Ethernet')),
    ('802-11-wireless', _('Wi-Fi')),
    ('pppoe', _('PPPoE'))
])


class ConnectionNotFound(Exception):
    """Network connection with a given name could not be found."""
    pass
Example #12
0
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
Module to handle glib main loop and provide asynchronous utilities.
"""

import logging
import threading

from plinth import dbus, network
from plinth.utils import import_from_gi

glib = import_from_gi('GLib', '2.0')

_thread = None
_main_loop = None

logger = logging.getLogger(__name__)


def run():
    """Run a glib main loop forever in a thread."""
    global _thread
    _thread = threading.Thread(target=_run)
    _thread.start()


def stop():
    """Exit glib main loop and end the thread."""
    if _main_loop:
        logger.info('Exiting glib main loop')
        _main_loop.quit()
Example #13
0
"""
Helper functions for working with network manager.
"""

import collections
from django.utils.translation import ugettext_lazy as _
import logging
import socket
import struct
import subprocess
import uuid

from plinth.utils import import_from_gi

glib = import_from_gi("GLib", "2.0")
nm = import_from_gi("NM", "1.0")

logger = logging.getLogger(__name__)

CONNECTION_TYPE_NAMES = collections.OrderedDict(
    [("802-3-ethernet", _("Ethernet")), ("802-11-wireless", _("Wi-Fi")), ("pppoe", _("PPPoE"))]
)


class ConnectionNotFound(Exception):
    """Network connection with a given name could not be found."""

    pass