summaryrefslogtreecommitdiffstats
path: root/tormonitor
blob: 123bdd628fc046a174672968bf5a1315f6271353 (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
589
590
591
592
593
594
595
596
597
598
599
#!/usr/bin/env python3
#
# Tor Monitor - a GTK applicaton to display Tor circuits and streams
# Copyright (C) 2015  Tails developers
#
# 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/>.

import datetime
import gettext
import logging
import os
import socket
import sys

try:
    import pycountry
except ImportError:
    pycountry = None

import stem
import stem.connection
import stem.control

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

gettext.install('tormonitor')

if 'DEBUG' in os.environ and os.environ['DEBUG']:
    logging.basicConfig(level=int(os.environ['DEBUG']))
else:
    logging.getLogger('stem').setLevel(logging.WARNING)

class TorMonitorWindow(Gtk.ApplicationWindow):
    """Tor Monitor main window

    This class contains all the UI and the logic to update.
    """

    # Constants used to distinguish circuits and streams in our TreeStore
    TYPE_CIRC = 0
    TYPE_STREAM = 1

    def __init__(self, app):
        """Create a new TorMonitorWindow

        :var Gtk.Application app: the application which own the window
        """
        Gtk.Window.__init__(self, application=app)

        self._listeners_initialized = False
        self._circ_to_iter = {}
        self._stream_to_iter = {}
        self.controller = self.get_application().controller

        self._create_ui()

        if self.controller:
            self.init_listeners()
            self.populate_treeview()
        else:
            GLib.timeout_add_seconds(1, self.controller_connect_cb)
            self._path.set_sensitive(False)
            self._treeview.set_sensitive(False)
            self._infobar_label.set_text(_("Cannot connect to the Tor daemon. "
                                           "Tor Monitor will try to reconnect..."))
            self._infobar.set_message_type(Gtk.MessageType.ERROR)
            self._infobar.show()

    def _create_ui(self):
        """Creates the user interface
        """
        self.set_default_size(600, 400)
        self.set_icon_name('tormonitor')
        self.connect('delete-event', self.delete_event_cb)

        headerbar = Gtk.HeaderBar()
        headerbar.set_title(_("Tor Monitor"))
        headerbar.set_subtitle(_("Display Tor circuits and streams"))
        headerbar.set_show_close_button(True)
        self.set_titlebar(headerbar)

        grid = Gtk.Grid()
        self.add(grid)

        self._infobar = Gtk.InfoBar()
        self._infobar.set_no_show_all(True)
        self._infobar_label = Gtk.Label("");
        self._infobar_label.show()
        self._infobar.get_content_area().add(self._infobar_label)
        self._infobar.add_button(_("OK"), Gtk.ResponseType.OK)
        self._infobar.connect('response', lambda infobar, rid, data=None: self._infobar.hide())
        grid.attach(self._infobar, 0, 0, 2, 1)

        # Circuits/streams list
        self._treestore = Gtk.TreeStore(GObject.TYPE_INT,    # TYPE_CIRC or TYPE_STREAM
                                        GObject.TYPE_STRING, # id
                                        GObject.TYPE_STRING, # path
                                        GObject.TYPE_STRING) # status
        self._treeview = Gtk.TreeView.new_with_model(self._treestore)
        self._treeview.get_selection().connect('changed', self.cb_treeselection_changed)
        def append_column(tv, col, name=None):
            tvcolumn = Gtk.TreeViewColumn(name)
            tv.append_column(tvcolumn)
            cell = Gtk.CellRendererText()
            tvcolumn.pack_start(cell, True)
            tvcolumn.add_attribute(cell, 'text', col)
        append_column(self._treeview, 2, _("Path"))
        append_column(self._treeview, 3, _("Status"))

        scrolledwindow_circuits = Gtk.ScrolledWindow()
        scrolledwindow_circuits.add(self._treeview)
        scrolledwindow_circuits.set_property('margin', 6)
        scrolledwindow_circuits.set_property('expand', True)
        scrolledwindow_circuits.set_property('halign', Gtk.Align.FILL)
        scrolledwindow_circuits.set_property('valign', Gtk.Align.FILL)
        scrolledwindow_circuits.set_policy(
                hscrollbar_policy=Gtk.PolicyType.NEVER,
                vscrollbar_policy=Gtk.PolicyType.AUTOMATIC)
        grid.attach(scrolledwindow_circuits, 0, 1, 1, 1)

        # Circuit details
        self._path = Gtk.ListBox()
        self._path.set_selection_mode(Gtk.SelectionMode.NONE)
        placeholder = Gtk.Label(_("Click on a path to get details"))
        placeholder.show()
        self._path.set_placeholder(placeholder)
        self._path.set_property('margin', 6)
        self._path.set_property('expand', True)
        self._path.set_property('halign', Gtk.Align.FILL)
        self._path.set_property('valign', Gtk.Align.FILL)
        grid.attach(self._path, 1, 1, 1, 1)

        self.show_all()

    def delete_event_cb(self, widget, event, data=None):
        """Hide the window immediately on close.

        This callback is connected to window's 'delete-event' and forces Gtk to
        hide the window while waiting for all threads to close.
        """
        logging.info("quitting, waiting all threads to return...")
        self.hide()
        while Gtk.events_pending():
            Gtk.main_iteration()
        return False

    # TOR CONTROL LISTENERS
    # =====================

    def init_listeners(self):
        """Connect our handlers to Tor event listeners
        """
        # These handlers won't be executed in the main thread, they will have to
        # do the real work in another method executed in the main thread by
        # GLib.idle_add in order not to make Gtk crazy.
        if not self._listeners_initialized:
            self.controller.add_event_listener(self.update_circ_handler,
                    stem.control.EventType.CIRC)
            self.controller.add_event_listener(self.update_stream_handler,
                    stem.control.EventType.STREAM)
            self.controller.add_status_listener(self.update_status_handler)
        self._listeners_initialized = True

    def update_circ_handler(self, circ_event):
        """Handler for stem.control.EventType.CIRC
        """
        # Handle the event in main thread
        GLib.idle_add(self.update_circ_cb, circ_event)

    def update_stream_handler(self, stream_event):
        """Handler for stem.control.EventType.STREAM
        """
        # Handle the event in main thread
        GLib.idle_add(self.update_stream_cb, stream_event)

    def update_status_handler(self, controller, state, timestamp):
        """Handler for stem.control.BaseController.add_status_listener
        """
        if state == stem.control.State.CLOSED:
            GLib.idle_add(self.connection_closed_cb)
            GLib.timeout_add_seconds(1, self.controller_reconnect_cb)
        elif state == stem.control.State.INIT:
            GLib.idle_add(self.connection_init_cb)

    # RECONNECTION MANAGEMENT
    # =======================

    def connection_closed_cb(self):
        """Update the UI after we lost conection to the Tor daemon

        This callback is called when we lost connection with the Tor daemon.

        :returns: **False**
        """
        logging.debug("Controller connection closed")
        self._path.set_sensitive(False)
        self._treeview.set_sensitive(False)
        self._infobar_label.set_text(_("Lost connection to the Tor daemon. "
                                       "Tor Monitor will try to reconnect..."))
        self._infobar.set_message_type(Gtk.MessageType.ERROR)
        self._infobar.show()
        self._treestore.clear()
        return False

    def connection_init_cb(self):
        """Update the UI after a (re)connection to the Tor daemon

        This callback is called when we (re)connect to the Tor daemon.

        :returns: **False**
        """
        logging.info("controller connected")
        self._path.set_sensitive(True)
        self._treeview.set_sensitive(True)
        self._infobar_label.set_text(_("Connected to the Tor daemon! "
                                       "You can use now Tor Monitor."))
        self._infobar.set_message_type(Gtk.MessageType.INFO)
        self._infobar.show()
        self.init_listeners()
        self.populate_treeview()

        return False

    def controller_reconnect_cb(self):
        """Try to reconnect to the Tor daemon

        This callback is called regularly by self.update_status_handler if the
        connection to the Tor daemon is lost. It calls self.connection_init_cb
        after a successful reconnection.

        :returns: **bool** that's **False** if we reconnected successfully and
        **True** if we failed to reconnect (so that GLib.timeout_add will call
        the method again).
        """
        logging.debug("trying to reconnect the controller")
        try:
            self.controller.connect()
            self.controller.authenticate()
        except stem.SocketError:
            return True
        self.connection_init_cb()
        return False

    def controller_connect_cb(self):
        """Try to connect to the Tor daemon for the 1st time

        This callback is called regularly by self.__init__ if there is no
        connection to the Tor daemon at startup. It calls
        self.connection_init_cb after a successful connection.

        :returns: **bool** that's **False** if we connected successfully and
        **True** if we failed to connect (so that GLib.timeout_add will call
        the method again).
        """
        logging.debug("trying to connect the controller")
        controller = self.get_application().connect_controller()
        if controller:
            self.controller = controller
            self.connection_init_cb()
            return False
        else:
            return True

    # CRICUITS AND STREAMS LIST
    # =========================

    def remove_treeiter(self, treeiter):
        """Remove a treeiter from our circuits/streams list if it is valid

        :var Gtk.TreeIter treeiter: the treeiter to remove

        :returns: **False**
        """
        if self._treestore.iter_is_valid(treeiter):
            self._treestore.remove(treeiter)
        else:
            # It may happen that the treeiter is not valid anymore
            # e.g. because it represents a stream that has been remapped
            # to another circuit.
            logging.warn("cannot remove %s which is not valid")
        return False # to cancel the repetition when used in timeout_add

    # Circuits
    # --------

    @staticmethod
    def circuit_label(circuit):
        """Returns a label for a circuit

        :var stem.response.events.CircuitEvent circuit: the circuit

        :returns: **str** representing the circuit
        """
        if circuit.path:
            circ_str = _(', ').join([nick for fp, nick in circuit.path])
        else:
            circ_str = _("Building...")
        return circ_str

    def add_circuit(self, circuit):
        """Adds a circuit to our circuits/streams list

        :var stem.response.events.CircuitEvent circuit: the circuit

        :returns: the :class:`Gtk.TreeIter` corresponding to the circuit
        """
        circ_iter = self._treestore.append(None,
                        [self.TYPE_CIRC,
                        circuit.id,
                        self.circuit_label(circuit),
                        str(circuit.status).capitalize()])
        self._circ_to_iter[circuit.id] = circ_iter
        return circ_iter

    def update_circuit(self, circuit):
        """Updates a circuit in our circuits/streams list

        :var stem.response.events.CircuitEvent circuit: the circuit
        """
        logging.debug("updating circuit %s" % circuit.id)
        if circuit.reason:
            status = _("%s: %s") % (str(circuit.status).capitalize(),
                                    str(circuit.reason).lower())
        else:
            status = str(circuit.status).capitalize()
        self._treestore.set(
            self._circ_to_iter[circuit.id],
            2, self.circuit_label(circuit),
            3, status)

    def remove_circuit(self, circuit):
        """Remove a circuit from our circuits/streams list

        :var stem.response.events.CircuitEvent circuit: the circuit
        """

        self.remove_treeiter(self._circ_to_iter[circuit.id])
        del self._circ_to_iter[circuit.id]

    def remove_circuit_delayed(self, circuit):
        """Remove a circuit from our circuits/streams list after a delay

        The delay gives the user time to read the reason of the removal.

        :var stem.response.events.CircuitEvent circuit: the circuit
        """
        circ_iter = self._circ_to_iter[circuit.id]
        del self._circ_to_iter[circuit.id]
        GLib.timeout_add_seconds(5, self.remove_treeiter, circ_iter)

    def update_circ_cb(self, circ_event):
        """Updates the circuits/streams list in response to a the
        :class:`stem.response.events.CircuitEvent`

        :var stem.response.events.CircuitEvent circ_event: the circuit event
        """
        if circ_event.id not in self._circ_to_iter:
            self.add_circuit(circ_event)
        else:
            self.update_circuit(circ_event)
            if (circ_event.status == stem.CircStatus.FAILED
                    or circ_event.status == stem.CircStatus.CLOSED):
                self.remove_circuit_delayed(circ_event)

    # Streams
    # -------

    @staticmethod
    def stream_label(stream):
        """Returns a label for a stream

        :var stem.response.events.StreamEvent stream: the stream

        :returns: **str** representing the stream
        """
        return "%s" % stream.target

    def add_stream(self, stream):
        """Adds a circuit to our circuits/streams list

        :var stem.response.events.StreamEvent stream: the stream

        :returns: the :class:`Gtk.TreeIter` corresponding to the stream
        """
        if not stream.circ_id:
            return None
        circ_iter = self._circ_to_iter[stream.circ_id]
        if not circ_iter:
            logging.warn("no iter found for %s" % circ_id)
            circ_iter = self.add_circuit(self.controller.get_circuit(circ_id))
        stream_iter = self._treestore.append(circ_iter,
                    [self.TYPE_STREAM,
                    stream.id,
                    self.stream_label(stream),
                    str(stream.status).capitalize()])
        self._stream_to_iter[stream.id] = stream_iter
        self._treeview.expand_to_path(self._treestore.get_path(stream_iter))
        return stream_iter

    def update_stream(self, stream):
        """Updates a stream in our circuits/streams list

        :var stem.response.events.StreamEvent stream: the stream
        """
        stream_iter = self._stream_to_iter[stream.id]
        circuit_iter = self._treestore.iter_parent(stream_iter)
        if stream.circ_id != self._treestore.get_value(circuit_iter, 1):
            # The stream doesn't belong to its parent circuit anymore. Remove it.
            self.remove_stream(stream)
            if stream.circ_id:
                # The stream has a new circuit, add it with its new parent.
                stream_iter = self.add_stream(stream)
        else:
            # The stream didn't change parent. Update it.
            #
            # We should not update the stream label because this would
            # replace the hostname by its IP address.
            if stream.status:
                self._treestore.set(stream_iter, 3, str(stream.status).capitalize())

    def remove_stream(self, stream):
        """Remove a stream from our circuits/streams list

        :var stem.response.events.StreamEvent stream: the stream
        """
        self.remove_treeiter(self._stream_to_iter[stream.id])
        del self._stream_to_iter[stream.id]

    def remove_stream_delayed(self, stream):
        """Remove a stream from our circuits/streams list after a delay

        The delay gives the user time to read the reason of the removal.

        :var stem.response.events.StreamEvent stream: the stream
        """
        stream_iter = self._stream_to_iter[stream.id]
        if stream_iter:
            del self._stream_to_iter[stream.id]
            GLib.timeout_add_seconds(5, self.remove_treeiter, stream_iter)

    def update_stream_cb(self, stream_event):
        """Updates the circuits/streams list in response to a the
        :class:`stem.response.events.StreamEvent`

        :var stem.response.events.StreamEvent stream_event: the stream event
        """
        if stream_event.id not in self._stream_to_iter:
            self.add_stream(stream_event)
        else:
            self.update_stream(stream_event)
            if (stream_event.status == stem.StreamStatus.FAILED
                    or stream_event.status == stem.StreamStatus.CLOSED
                    or stream_event.status == stem.StreamStatus.DETACHED):
                self.remove_stream_delayed(stream_event)

    def populate_treeview(self):
        """Synchronize the circuits/streams list with the Tor daemon
        """
        self._treestore.clear()
        self._circ_to_iter = {}
        self._stream_to_iter = {}

        for c in self.controller.get_circuits():
            self.add_circuit(c)
        for s in self.controller.get_streams():
            self.add_stream(s)
        self._treeview.expand_all()

    # CRICUIT DETAILS
    # ===============

    def cb_treeselection_changed(self, treeselection, data=None):
        """Handle selection change in the circuits/streams list

        Display details for the circuit selected in the circuits/streams list

        :var Gtk.TreeSelection treeselection: the selection

        :returns: **True**
        """
        (model, selected_iter) = treeselection.get_selected()
        if not selected_iter:
            self.clear_circuit_details()
            return False

        if model.get_value(selected_iter, 0) == self.TYPE_STREAM: # Stream
            circuit_iter = model.iter_parent(selected_iter)
        else: # Circuit
            circuit_iter = selected_iter

        circ_id = model.get_value(circuit_iter, 1)
        try:
            circuit = self.controller.get_circuit(circ_id)
        except ValueError as e: # The circuit doesn't exist anymore
            logging.warn("circuit %s not known by Tor: %s" % (circ_id, e))
            return False
        self.show_circuit_details(circuit)
        return False

    def clear_circuit_details(self):
        def remove_row(child, container):
            container.remove(child)
            return False
        self._path.foreach(remove_row, self._path)

    def show_circuit_details(self, circuit):
        """Display details for a circuit

        :var stem.response.events.CircuitEvent circuit: the circuit
        """
        self.clear_circuit_details()

        for fp in [fp for fp, nick in circuit.path]:
            self.display_node(self.controller.get_network_status(fp))

        self._path.show_all()

    def display_node(self, status_entry):
        """Display details for a node

        :var stem.descriptor.router_status_entry.RouterStatusEntryMicroV3
        status_entry: the status entry for the node
        """
        country = self.controller.get_info("ip-to-country/%s" % status_entry.address)
        if pycountry:
            try:
                country = pycountry.countries.get(alpha2=country.upper()).name
            except KeyError:
                # If pycountry can't find the country, just display the string
                # returned by Tor.
                pass

        grid = Gtk.Grid()
        grid.set_property('row-spacing', 6)
        grid.set_property('column-spacing', 12)
        grid.set_property('margin', 12)

        title = Gtk.Label()
        title.set_markup("<b>%s</b>" % status_entry.nickname)
        title.set_halign(Gtk.Align.START)
        grid.attach(title, 0, 0, 2, 1)

        line = 1
        for l, v in [(_("Fingerprint:"), status_entry.fingerprint),
                     (_("Published:"), status_entry.published),
                     (_("IP:"), _("%s (%s)") % (status_entry.address, country)),
                     (_("Bandwidth:"), _("%.2f Mb/s") % (status_entry.bandwidth/1024.)),
                    ]:
            label = Gtk.Label(l)
            label.set_halign(Gtk.Align.START)
            grid.attach(label, 0, line, 1, 1)
            value = Gtk.Label(v)
            value.set_halign(Gtk.Align.START)
            grid.attach(value, 1, line, 1, 1)
            line += 1

        self._path.add(grid)
        grid.show_all()

class TorMonitorApplication(Gtk.Application):
    """Tor Monitor application

    :var stem.control.Controller controller: a controller to the Tor daemon
    """

    def __init__(self):
        Gtk.Application.__init__(self)

        self.connect_controller()

    def connect_controller(self):
        """Connects the controller to the Tor daemon.
        """
        self.controller = stem.connection.connect_socket_file()
        return self.controller

    def do_activate(self):
        win = TorMonitorWindow(self)
        win.show_all()

    def do_startup(self):
        Gtk.Application.do_startup(self)

app = TorMonitorApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)