aboutsummaryrefslogtreecommitdiff
path: root/rwa/support/sessionservice/service.py
blob: 9a843ae1dc683b6bf514e587ff74af8dd268f281 (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
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
581
582
583
584
585
586
587
588
#!/usr/bin/env python3

# This file is part of Remote Support Desktop
# https://gitlab.das-netzwerkteam.de/RemoteWebApp/rwa.support.sessionservice
# Copyright 2020, 2021 Jonathan Weth <dev@jonathanweth.de>
# Copyright 2020, 2021 Daniel Teichmann <daniel.teichmann@das-netzwerkteam.de>
# Copyright 2020 Mike Gabriel <mike.gabriel@das-netzwerkteam.de>
# SPDX-License-Identifier: GPL-2.0-or-later
#
# 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.,
# 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import json
import signal
import time
from threading import Thread
from typing import Dict, Union
from uuid import uuid4

import click
import dbus
import dbus.mainloop.glib
import dbus.service
import requests
import usersettings
import validators
from gi.repository import GLib

from .config import ALLOW_ONLY_ONE_SESSION, API_PATH, SUPPORTED_API_VERSIONS
from .lock import is_locked, lock, unlock
from .log import logging
from .session import Session, combine
from .trigger import TriggerServerThread


class RWASupportSessionService(dbus.service.Object):
    """D-Bus Session Service for RWA.Support.

    D-Bus namespace: ``org.ArcticaProject.RWASupportSessionService``

    D-Bus object name: ``/RWASupportSessionService``

    :param loop: GLib main loop running the service
    :param mockup_mode: Starts the service in mock up mode
    """

    def __init__(self, loop: GLib.MainLoop, mockup_mode: bool = False, one_time: bool = False):
        self.loop = loop
        self.mockup_mode = mockup_mode
        self.one_time = one_time

        self.bus = dbus.SessionBus()
        name = dbus.service.BusName("org.ArcticaProject.RWASupportSessionService", bus=self.bus)

        self.check_lock_thread = Thread(target=self._check_lock)
        self.check_lock_thread.start()

        self.trigger_service = TriggerServerThread(self._trigger)
        self.trigger_service.start()

        self.update_service_running = False
        self.sessions = {}

        self.settings = usersettings.Settings("org.ArcticaProject.RWASupportSessionService")
        self.settings.add_setting("web_app_hosts", dict)
        self.settings.load_settings()

        # Ensure default value for web app hosts settings
        if not self.settings.web_app_hosts:
            self.settings.web_app_hosts = {}
            self.settings.save_settings()

        super().__init__(name, "/RWASupportSessionService")

        logging.info("D-Bus service has been started.")

    def _is_url(self, url: str) -> bool:
        """Test if the given string is an url.

        :param url: The string which should be an URL.
        :return: Whether the string is an URL.
        """
        valid = validators.url(url)
        logging.debug(f"Is {url} an URL: {valid}")
        return valid

    def _get_web_app_hosts(self) -> str:
        """Get all registered RWA.Support.WebApp hosts.

        Helper function: No D-Bus API.
        """
        hosts = [
            self._build_host_dict(key, value) for key, value in self.settings.web_app_hosts.items()
        ]
        return json.dumps(hosts)

    def _build_host_dict(self, host_id: str, host: dict) -> dict:
        """Include the host ID in the host dictionary."""
        return host | {"id": host_id}

    @dbus.service.method("org.ArcticaProject.RWASupportSessionService", out_signature="s")
    def get_web_app_hosts(self) -> str:
        """Get all registered RWA.Support.WebApp hosts.

        :return: All registered hosts as JSON array (D-Bus string)

        **Structure of returned JSON:**

        ::

            [{"id": <host_id>, "https://example.org"}, {"id": <host_id>, "http://127.0.0.1:8000"}]
        """
        logging.info("D-Bus method call: %s()", "get_web_app_hosts")

        logging.debug('Return to D-Bus caller: "%s"', self._get_web_app_hosts())
        return self._get_web_app_hosts()

    def _do_api_handshake(self, host: str) -> Dict[str, str]:
        """Contact a RWA.Support.WebApp host and find out API version.

        :param host: The full hostname.
        :return: Status information as dictionary.

        **Structure of returned JSON (success):**

        ::

            {"status": "success", "type": "valid_host"}

         **Structure of returned JSON (error):**

        ::

            {"status": "error", "type": "<type>"}

        **Possible choices for error types:**

            * ``connection``
            * ``permission_denied``
            * ``unsupported_server``
        """
        url = host + API_PATH + "handshake/"
        logging.info(f"API handshake with {url} ...")
        try:
            r = requests.post(url)

        except requests.exceptions.ConnectionError:
            logging.warning("  resulted in a connection error.")
            return {"status": "error", "type": "connection"}

        if not r.ok:
            logging.warning("  resulted in a connection error.")
            return {"status": "error", "type": "connection"}

        if not r.json()["allowed"]:
            logging.warning("  was not permitted.")
            return {"status": "error", "type": "permission_denied"}

        if r.json().get("api_version") not in SUPPORTED_API_VERSIONS:
            logging.warning("  resulted in a incompatible API version.")
            return {"status": "error", "type": "unsupported_server"}

        logging.info("  was successful.")

        return {"status": "success", "type": "valid_host"}

    @dbus.service.method(
        "org.ArcticaProject.RWASupportSessionService", in_signature="s", out_signature="s"
    )
    def add_web_app_host(self, host: str) -> str:
        """Add a RWA.Support.WebApp host.

        :param host: Exact hostname of the RWA.Support.WebApp host (D-Bus string)
        :return: The registered host as JSOn object (D-Bus string)

        **Structure of returned JSON (success):**

        ::

            {"id": <host_id>, "http://127.0.0.1:8000"}

        **Structure of returned JSON (error):**

        ::

            {"status": "error", "type": "<type>"}

        **Possible choices for error types:**

            * ``connection``
            * ``permission_denied``
            * ``unsupported_server``
            * ``invalid_url``
            * ``duplicate``
        """
        host = str(host).rstrip("/")

        logging.info('D-Bus method call: %s("%s")', "add_web_app_host", host)

        if not self._is_url(host):
            logging.warning("Given URL is not valid!")
            logging.debug('Did not add "%s" to "web_app_hosts" in user_settings', host)
            return json.dumps({"status": "error", "type": "invalid_url"})

        if host in self.settings.web_app_hosts:
            logging.warning("Given URL is already present!")
            logging.debug('Did not add "%s" to "web_app_hosts" in user_settings', host)
            return json.dumps({"status": "error", "type": "duplicate"})

        res = self._do_api_handshake(host)
        if res["status"] == "error":
            logging.debug('Did not add "%s" to "web_app_hosts" in user_settings', host)
            return json.dumps(res)

        host_id = str(uuid4())
        host_object = {"url": host}

        self.settings.web_app_hosts[host_id] = host_object
        self.settings.save_settings()

        logging.debug('Added "%s" to "web_app_hosts" in user_settings', host)

        return json.dumps(self._build_host_dict(host_id, host_object))

    @dbus.service.method(
        "org.ArcticaProject.RWASupportSessionService", in_signature="i", out_signature="s"
    )
    def remove_web_app_host(self, host_id: str) -> str:
        """Remove a RWA.Support.WebApp host.

        :param host_id: ID of web app host (D-Bus string)
        :return: All registered hosts as JSON array (D-Bus string)

        **Structure of returned JSON:**

        ::

            [{"id": <host_id>, "https://example.org"}, {"id": <host_id>, "http://127.0.0.1:8000"}]
        """
        logging.info("D-Bus method call: %s(%s)", "remove_web_app_host", host_id)

        if host_id in self.settings.web_app_hosts:
            host_object = self.settings.web_app_hosts[host_id]
            del self.settings.web_app_hosts[host_id]
            self.settings.save_settings()
            logging.debug('Removed web_app_hosts[%s]="%s" in user settings', host_id, host_object)
        else:
            logging.warning("Given host index is not valid!")
            logging.debug(
                "Did not remove web_app_hosts[%s] (not existent!) in " "user settings", host_id
            )
            return json.dumps({"status": "error", "type": "host_not_found"})

        return self._get_web_app_hosts()

    @dbus.service.method(
        "org.ArcticaProject.RWASupportSessionService", in_signature="i", out_signature="s"
    )
    def start(self, host_id: str) -> str:
        """Start a new remote session and register it in RWA.Support.WebApp.

        :param host_id: ID of web app host (D-Bus string)
        :return: Result as JSON (D-Bus string)

        **Structure of returned JSON (success):**

        ::

            {
                "status": "success",
                "host_id": "<host_id>",
                "session_id": <session_id>,
                "url": "<url>",
                "pin": <pin>
            }

        **Structure of returned JSON (error):**

        ::

            {"status": "error", "type": "<type>"}

        **Possible choices for error types:**

            * ``multiple``
            * ``connection``
            * ``host_not_found``
            * ``permission_denied``
            * ``unsupported_server``
        """
        logging.info("D-Bus method call: %s(%s)", "start", host_id)

        if ALLOW_ONLY_ONE_SESSION and len(self.sessions.values()) > 0:
            logging.warning(
                "There is already one session running and the service "
                "is configured to allow only one "
                "session, so this session won't be started."
            )
            response = json.dumps({"status": "error", "type": "multiple"})
            logging.debug("The response to the D-Bus caller: '%s'", response)
            return response

        try:
            host_object = self.settings.web_app_hosts[host_id]
            host_object = self._build_host_dict(host_id, host_object)
            logging.debug('web_app_hosts[%s] is the following host: "%s"', host_id, host_object)
        except IndexError:
            logging.error("web_app_hosts[%s] does not exist!", host_id)
            response = json.dumps({"status": "error", "type": "host_not_found"})
            logging.debug("The response to the D-Bus caller: '%s'", response)
            return response

        # Check host by doing a handshake
        res = self._do_api_handshake(host_object["url"])
        if res["status"] == "error":
            return json.dumps(res)

        # Start session
        try:
            session = Session(host_object, self.trigger_service.port, self.mockup_mode)

            # Add session to sessions list
            self.sessions[session.combined_id] = session

            # Start session update service
            self._ensure_update_service()

            return_json = session.client_meta
            return_json["status"] = "success"

            logging.info(f"New session #{session.pid} was started with meta {return_json}.")

            response = json.dumps(return_json)
            logging.debug("The response to the D-Bus caller: '%s'", response)
            return response
        except ConnectionError:
            logging.error(
                "There was a connection error while trying to reach "
                "the RWA.Support.WebApp server."
            )

        response = json.dumps({"status": "error", "type": "connection"})
        logging.debug("The response to the D-Bus caller: '%s'", response)
        return response

    @dbus.service.method(
        "org.ArcticaProject.RWASupportSessionService", in_signature="si", out_signature="s"
    )
    def status(self, host_id: str, session_id: int) -> str:
        """Return the status of a session.

        .. note::

            This uses the last status version got by the update service in the background.

        :param host_id: Host ID (D-Bus string)
        :param session_id: Session ID (D-Bus integer)

        :return: Session status as JSON (D-Bus string)

        **Structure of returned JSON:**

        ::

            {"host_id": "<host_id>", "session_id": <session_id>, "status": <status>}

        **Possible status options:**

        ============ ======================
        ``running``  The session is running and ready for connecting.
        ``active``   The session is running and a the remote connected to the session.
        ``stopped``  The session was stopped.
        ``dead``     There was a problem, so that the session is dead.
        ============ ======================
        """
        logging.info("D-Bus method call: %s(%s, %d)", "status", host_id, session_id)
        response = self._get_status(host_id, session_id)
        logging.debug("The response to the D-Bus caller: '%s'", response)
        return response

    @dbus.service.method(
        "org.ArcticaProject.RWASupportSessionService", in_signature="si", out_signature="s"
    )
    def refresh_status(self, host_id: str, session_id: int) -> str:
        """Update status from WebApp before returning it here like :meth:`status`."""
        logging.info("D-Bus method call: %s(%s, %d)", "refresh_status", host_id, session_id)

        self._update_session(host_id, session_id)
        response = self._get_status(host_id, session_id)
        logging.debug("The response to the D-Bus caller: '%s'", response)
        return response

    @dbus.service.method(
        "org.ArcticaProject.RWASupportSessionService", in_signature="si", out_signature="s"
    )
    def stop(self, host_id: str, session_id: int) -> str:
        """Stop a remote session.

        :param host_id: Host ID (D-Bus string)
        :param session_id: Session ID (D-Bus integer)
        :return: Session status as JSON (D-Bus string)

        **Structure of returned JSON:**

        ::

            {"host_id": "<host_id>", "session_id": <session_id>, "status": "stopped"}
        """
        logging.info("D-Bus method call: %s(%s, %d)", "stop", host_id, session_id)

        combined_id = combine(host_id, session_id)
        try:
            session = self.sessions[combined_id]
        except KeyError:
            response = json.dumps(
                {"host_id": host_id, "session_id": session_id, "status": "stopped"}, sort_keys=True
            )
            logging.debug("The response to the D-Bus caller: '%s'", response)
            return response
        session.stop()
        response = json.dumps(
            {"host_id": host_id, "session_id": session_id, "status": "stopped"}, sort_keys=True
        )
        logging.debug("The response to the D-Bus caller: '%s'", response)
        return response

    def _get_status(self, host_id: str, session_id: int) -> str:
        combined_id = combine(host_id, session_id)
        try:
            session = self.sessions[combined_id]
        except KeyError:
            return json.dumps(
                {"host_id": host_id, "session_id": session_id, "status": "dead"}, sort_keys=True
            )
        return json.dumps(session.status)

    def _ensure_update_service(self):
        """Start session update thread if it isn't already running."""
        if not self.update_service_running:
            self.update_thread = Thread(target=self._update_sessions)
            self.update_thread.start()

    def _update_session(self, host_id: str, session_id: int):
        """Update the status of a session."""
        combined_id = combine(host_id, session_id)
        try:
            session = self.sessions[combined_id]
        except KeyError:
            logging.info(f"Update status for session #{session_id} on host {host_id} …")
            logging.warning("  Session is dead.")
            return

        # Check if VNC process is still running
        running = session.vnc_process_running
        if running:
            pass
        elif session.status_text == "stopped" and session.pid in self.sessions:
            logging.info(f"Update status for session #{session_id} on host {host_id} …")
            logging.warning("  Session is dead.")

            del self.sessions[combined_id]
        else:
            logging.info(f"Update status for session #{session_id} on host {host_id} …")
            logging.warning("  VNC was stopped, so session is dead.")

            session.stop()
            del self.sessions[combined_id]

    def _update_sessions(self):
        """Go through all running sessions and update their status using ``_update_session``."""
        logging.info("Started update service for sessions.")
        while len(self.sessions.values()) > 0:
            for session in list(self.sessions.values()):
                self._update_session(session.host_id, session.session_id)

            time.sleep(2)

        self.update_service_running = False
        logging.info("Stopped update service for sessions.")
        if self.one_time:
            self._stop_all()

    def _trigger(self, session_id: int, data: dict, method: str = "trigger") -> Union[dict, bool]:
        """Trigger a specific session via trigger token."""
        logging.info(f"Triggered with session ID {session_id} and {data}")

        for session in self.sessions.values():
            if session.session_id == session_id:
                r = session.trigger(data, method)
                logging.info(
                    f"Session #{session.session_id} on host {session.host_id} matches the ID: {r}"
                )
                return r

        logging.warning("  No matching session found for this ID.")
        return False

    def _stop_all(self):
        """Stop all sessions."""
        logging.info("Stop all sessions.")
        for session in list(self.sessions.values()):
            session.stop()
            del self.sessions[session.combined_id]

    def _stop_daemon(self):
        """Stop all sessions and this daemon."""
        logging.info("Shut down session service.")
        self._stop_all()
        self.trigger_service.shutdown()
        self.loop.quit()

    def _check_lock(self):
        """Check if lock file exists."""
        while True:
            if not is_locked():
                logging.error("The lock file was removed, so stop this service.")
                self._stop_all()
                break
            time.sleep(1)


@click.command()
@click.option(
    "-m",
    "--mockup",
    is_flag=True,
    default=False,
    help="Activates mock up mode. Acts like the real Session Service "
    "but don't do changes or call RWA.Support.WebApp.",
)
@click.option(
    "-o",
    "--once",
    is_flag=True,
    default=False,
    help="Runs as one-time-service. Stops after one session.",
)
def main(mockup, once):
    # Check for lock file
    if is_locked():
        logging.error("The service is already running.")
        exit(1)

    # Create lock file
    lock()

    if mockup:
        logging.warning("All API responses are faked and should NOT BE USED IN PRODUCTION!")

    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    loop = GLib.MainLoop()
    service_object = RWASupportSessionService(loop, mockup, once)

    def sigint_handler(sig, frame):
        logging.info("Service was terminated.")
        service_object._stop_daemon()

    def sigquit_handler(sig, frame):
        logging.info("Session was terminated.")
        service_object._stop_all()

    signal.signal(signal.SIGINT, sigint_handler)
    signal.signal(signal.SIGQUIT, sigquit_handler)

    loop.run()

    logging.info("Remove lock file ...")
    unlock()


if __name__ == "__main__":
    main()