summaryrefslogtreecommitdiff
path: root/src/leap/bitmask/services/__init__.py
blob: ba12ba4e971f66ad5f809359f97f1161cc4b113f (plain)
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
# -*- coding: utf-8 -*-
# __init__.py
# Copyright (C) 2013 LEAP
#
# 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 3 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, see <http://www.gnu.org/licenses/>.
"""
Services module.
"""
import logging
import os
import sys

from PySide import QtCore

from leap.bitmask.config import flags
from leap.bitmask.crypto.srpauth import SRPAuth
from leap.bitmask.util.constants import REQUEST_TIMEOUT
from leap.bitmask.util.privilege_policies import is_missing_policy_permissions
from leap.bitmask.util.request_helpers import get_content
from leap.bitmask import util

from leap.common.check import leap_assert
from leap.common.config.baseconfig import BaseConfig
from leap.common.files import get_mtime

logger = logging.getLogger(__name__)


EIP_SERVICE = u"openvpn"
MX_SERVICE = u"mx"
DEPLOYED = [EIP_SERVICE, MX_SERVICE]


def get_service_display_name(service):
    """
    Returns the name to display of the given service.
    If there is no configured name for that service, then returns the same
    parameter

    :param service: the 'machine' service name
    :type service: str

    :rtype: str
    """
    # qt translator method helper
    _tr = QtCore.QObject().tr

    # Correspondence for services and their name to display
    EIP_LABEL = _tr("Encrypted Internet")
    MX_LABEL = _tr("Encrypted Mail")

    service_display = {
        "openvpn": EIP_LABEL,
        "mx": MX_LABEL
    }

    # If we need to add a warning about eip needing
    # administrative permissions to start. That can be either
    # because we are running in standalone mode, or because we could
    # not find the needed privilege escalation mechanisms being operative.
    if flags.STANDALONE or is_missing_policy_permissions():
        EIP_LABEL += " " + _tr("(will need admin password to start)")

    return service_display.get(service, service)


def get_supported(services):
    """
    Returns a list of the available services.

    :param services: a list containing the services to be filtered.
    :type services: list of str

    :returns: a list of the available services
    :rtype: list of str
    """
    return filter(lambda s: s in DEPLOYED, services)


def download_service_config(provider_config, service_config,
                            session,
                            download_if_needed=True):
    """
    Downloads config for a given service.

    :param provider_config: an instance of ProviderConfig
    :type provider_config: ProviderConfig

    :param service_config: an instance of a particular Service config.
    :type service_config: BaseConfig

    :param session: an instance of a fetcher.session
                    (currently we're using requests only, but it can be
                    anything that implements that interface)
    :type session: requests.sessions.Session
    """
    service_name = service_config.name
    service_json = "{0}-service.json".format(service_name)
    headers = {}
    mtime = get_mtime(os.path.join(util.get_path_prefix(),
                                   "leap", "providers",
                                   provider_config.get_domain(),
                                   service_json))

    if download_if_needed and mtime:
        headers['if-modified-since'] = mtime

    api_version = provider_config.get_api_version()

    config_uri = "%s/%s/config/%s-service.json" % (
        provider_config.get_api_uri(),
        api_version,
        service_name)
    logger.debug('Downloading %s config from: %s' % (
        service_name.upper(),
        config_uri))

    # XXX make and use @with_srp_auth decorator
    srp_auth = SRPAuth(provider_config)
    session_id = srp_auth.get_session_id()
    token = srp_auth.get_token()
    cookies = None
    if session_id is not None:
        cookies = {"_session_id": session_id}

    # API v2 will only support token auth, but in v1 we can send both
    if token is not None:
        headers["Authorization"] = 'Token token="{0}"'.format(token)

    verify = provider_config.get_ca_cert_path()
    if verify:
        verify = verify.encode(sys.getfilesystemencoding())

    res = session.get(config_uri,
                      verify=verify,
                      headers=headers,
                      timeout=REQUEST_TIMEOUT,
                      cookies=cookies)
    res.raise_for_status()

    service_config.set_api_version(api_version)

    # Not modified
    service_path = ("leap", "providers", provider_config.get_domain(),
                    service_json)
    if res.status_code == 304:
        logger.debug(
            "{0} definition has not been modified".format(
                service_name.upper()))
        service_config.load(os.path.join(*service_path))
    else:
        service_definition, mtime = get_content(res)
        service_config.load(data=service_definition, mtime=mtime)
        service_config.save(service_path)


class ServiceConfig(BaseConfig):
    """
    Base class used by the different service configs
    """

    _service_name = None

    @property
    def name(self):
        """
        Getter for the service name.
        Derived classes should assign it.
        """
        leap_assert(self._service_name is not None)
        return self._service_name