summaryrefslogtreecommitdiff
path: root/extensions/storage-monitor.vala
blob: 950377dd6ec070fdeb603a9843248afb34b093df (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
/* ds-registry.vala
 *
 * Copyright © 2011 Collabora Ltd.
 *             By Siegfried-Angel Gevatter Pujals <siegfried@gevatter.com>
 * Copyright © 2011 Stefano Candori <stefano.candori@gmail.com>
 * Copyright © 2012 Canonical Ltd.
 *             By Siegfried-A. Gevatter <siegfried.gevatter@collabora.co.uk>
 *
 * Based upon a Python implementation:
 *  Copyright © 2009 Mikkel Kamstrup Erlandsen <mikkel.kamstrup@gmail.com>
 *  Copyright © 2011 Canonical Ltd.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 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 Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

using Zeitgeist;

namespace Zeitgeist
{
    [DBus (name = "org.gnome.zeitgeist.StorageMonitor")]
    public interface RemoteStorageMonitor: Object
    {
        [DBus (signature = "a(sa{sv})")]
        public abstract Variant get_storages () throws Error;

        public signal void storage_available (string storage_id,
            [DBus (signature = "a{sv}")] Variant storage_description);
        public signal void storage_unavailable (string storage_id);
    }

    private interface NetworkMonitor: Object
    {
        // This method emits the on_network_up/on_network_up signals
        // basing on the initial state of the network.
        public abstract void setup ();

        public signal void on_network_up ();
        public signal void on_network_down ();
    }

    namespace StorageMedia
    {
        private Variant to_variant (string medium_name, bool available,
            string icon, string display_name)
        {
            var vb = new VariantBuilder (new VariantType ("(sa{sv})"));

            vb.add ("s", medium_name);
            vb.open (new VariantType ("a{sv}"));
            {
                vb.open (new VariantType ("{sv}"));
                vb.add ("s", "available");
                vb.add ("v", new Variant ("b", available));
                vb.close ();
                vb.open (new VariantType ("{sv}"));
                vb.add ("s", "icon");
                vb.add ("v", new Variant ("s", icon));
                vb.close ();
                vb.open (new VariantType ("{sv}"));
                vb.add ("s", "display-name");
                vb.add ("v", new Variant ("s", display_name));
                vb.close ();
            }
            vb.close ();

            return vb.end ();
        }
    }

    /*
     * The Storage Monitor monitors the availability of network interfaces
     * and storage devices (USB drives, data/audio/video CD/DVDs, etc) and
     * updates the Zeitgeist database with this information so clients can
     * efficiently query based on the storage identifier and availability
     * of the storage medium the event subjects reside on.
     *
     * Subject can have the following types of storage identifiers:
     *  - for local resources, the fixed identifier `local`;
     *  - for network URIs, the fixed identifier `net`;
     *  - for resources on storage devices, the UUID of the partition
     *    they reside in;
     *  - otherwise, the fixed identifier `unknown`.
     *
     * Subjects with storage `local` or `unknown` are always considered as
     * available; for network resources, the monitor will use either ConnMan
     * or NetworkManager (whichever is available).
     *
     * For subjects being inserted without a storage id set, this extension
     * will attempt to determine it and update the subject on the fly.
     */
    class StorageMonitor: Extension, RemoteStorageMonitor
    {
        private const string[] network_uri_schemes = {
            "dav", "davs", "ftp", "http", "https", "mailto",
            "sftp", "smb", "ssh" };

        private Zeitgeist.SQLite.Database database;
        private unowned Sqlite.Database db;
        private uint registration_id;

        private Sqlite.Statement get_storages_stmt;
        private Sqlite.Statement store_storage_medium_stmt;
        private Sqlite.Statement update_storage_medium_stmt;
        private Sqlite.Statement insert_unavailable_medium_stmt;
        private Sqlite.Statement update_medium_state_stmt;

        private NetworkMonitor network;
        private uint watch_connman;
        private uint watch_nm;

        StorageMonitor ()
        {
            Object ();
        }

        construct
        {
            try
            {
                prepare_queries ();
            }
            catch (EngineError e)
            {
                warning ("Storage Monitor couldn't communicate with DB - bye");
                return;
            }

            // This will be called after bus is acquired, so it shouldn't block
            try
            {
                var connection = Bus.get_sync (BusType.SESSION, null);
                registration_id = connection.register_object<RemoteStorageMonitor> (
                    "/org/gnome/zeitgeist/storagemonitor", this);
            }
            catch (Error err)
            {
                warning ("%s", err.message);
            }

            /*
             * This is disabled because it causes races on some hardware
             * (zg will be using 100% cpu, maybe eat up lots of memory etc.)
             */
            /*
            VolumeMonitor monitor = VolumeMonitor.get ();
            monitor.volume_added.connect (on_volume_added);
            monitor.volume_removed.connect (on_volume_removed);
            foreach (Volume volume in monitor.get_volumes ())
            {
                add_storage_medium (get_volume_id (volume),
                    volume.get_icon ().to_string (), volume.get_name ());
            }
            */

            // Dynamically decide whether to use Connman or NetworkManager
            watch_connman = Bus.watch_name (BusType.SYSTEM,
                                      "net.connman",
                                      BusNameWatcherFlags.NONE,
                                      name_appeared_handler,
                                      null);
            watch_nm = Bus.watch_name (BusType.SYSTEM,
                                      "org.freedesktop.NetworkManager",
                                      BusNameWatcherFlags.NONE,
                                      name_appeared_handler,
                                      null);

        }

        private void name_appeared_handler (DBusConnection connection, string name, string name_owner)
        {
            if (this.network != null)
                return;

            if (name == "net.connman")
                this.network = new ConnmanNetworkMonitor ();
            else if (name == "org.freedesktop.NetworkManager")
                this.network = new NMNetworkMonitor ();

            this.network.on_network_up.connect (() =>
                this.add_storage_medium ("net", "stock_internet", "Internet"));
            this.network.on_network_down.connect (() =>
                this.remove_storage_medium ("net"));

            this.network.setup ();

            Bus.unwatch_name (watch_connman);
            Bus.unwatch_name (watch_nm);
        }

        public override void unload ()
        {
            // FIXME: move all this D-Bus stuff to some shared
            // {request,release}_iface functions
            try
            {
                var connection = Bus.get_sync (BusType.SESSION, null);
                if (registration_id != 0)
                {
                    connection.unregister_object (registration_id);
                    registration_id = 0;
                }
            }
            catch (Error err)
            {
                warning ("%s", err.message);
            }

            debug ("%s, this.ref_count = %u", Log.METHOD, this.ref_count);
        }

        private void prepare_queries () throws EngineError
        {
            database = engine.database;
            db = database.database;

            int rc;
            string sql;

            // Prepare query to retrieve all storage medium information
            sql = """
                SELECT value, state, icon, display_name
                FROM storage
                """;
            rc = db.prepare_v2 (sql, -1, out get_storages_stmt);
            database.assert_query_success (rc, "Storage retrieval query error");

            sql = """
                INSERT INTO storage (
                    value, state, icon, display_name
                ) VALUES (
                    ?, ?, ?, ?
                )""";
            rc = db.prepare_v2 (sql, -1, out store_storage_medium_stmt);
            database.assert_query_success (rc, "Storage insertion query error");

            sql = """
                UPDATE storage SET 
                state=?, icon=?, display_name=? 
                WHERE value=?
                """;
            rc = db.prepare_v2 (sql, -1, out update_storage_medium_stmt);
            database.assert_query_success (rc, "Storage update query error");

            sql = """
                INSERT INTO storage (
                    state, value
                ) VALUES (
                    ?, ?
                )""";
            rc = db.prepare_v2 (sql, -1, out insert_unavailable_medium_stmt);
            database.assert_query_success (rc,
                "insert_unavailable_medium_stmt error");

            sql = """
                UPDATE storage
                SET state=?
                WHERE value=?
                """;
            rc = db.prepare_v2 (sql, -1, out update_medium_state_stmt);
            database.assert_query_success (rc,
                "update_medium_state_stmt error");
        }

        public override void pre_insert_events (GenericArray<Event?> events,
            BusName? sender)
        {
            for (int i = 0; i < events.length; ++i)
            {
                if (events[i] == null) continue;
                for (int j = 0; j < events[i].subjects.length; ++j)
                {
                    Subject subject = events[i].subjects[j];
                    if (Utils.is_empty_string (subject.storage))
                        subject.storage = find_storage_for_uri (subject.uri);
                }
            }
        }

        /*
         * Find the name of the storage medium the given URI resides on.
         */
        private string find_storage_for_uri (string uri)
        {
            File file = File.new_for_uri (uri);
            string uri_scheme = file.get_uri_scheme ();
            /*
            // FIXME: uncomment this once gvfs is our friend again
            if (uri_scheme == "file")
            {
                try
                {
                    Mount mount = file.find_enclosing_mount ();
                    return get_volume_id (mount.get_volume ());
                }
                catch (Error err)
                {
                    return "local";
                }
            }
            else*/
            if (uri_scheme in network_uri_schemes)
            {
                return "net";
            }

            return "unknown";
        }

        private void on_volume_added (Volume volume)
        {
            debug ("volume added");
            Icon icon = volume.get_icon ();
            string icon_name = "";
            // FIXME: why volume.get_icon ().to_string () above but not here?
            if (icon is ThemedIcon && ((ThemedIcon) icon).get_names ().length > 0)
                icon_name = ((ThemedIcon) icon).get_names ()[0];
            add_storage_medium (get_volume_id (volume), icon_name,
                volume.get_name ());
        }

        private void on_volume_removed (Volume volume)
        {
            debug ("Volume removed");
            remove_storage_medium (get_volume_id (volume));
        }

        /*
         * Return a string identifier for a GIO Volume. This id is constructed
         * as a `best effort` since we can not always uniquely identify
         * volumes, especially audio- and data CDs are problematic.
         */
        private string get_volume_id (Volume volume)
        {
            string volume_id;

            volume_id = volume.get_uuid ();
            if (volume_id != null)
                return volume_id;

            volume_id = volume.get_identifier ("uuid");
            if (volume_id != null)
                return volume_id;

            volume_id = volume.get_identifier ("label");
            if (volume_id != null)
                return volume_id;

            return "unknown";
        }

        public void add_storage_medium (string medium_name, string icon,
            string display_name)
        {
            debug ("VOLUME ADDED: %s".printf(medium_name));
            store_storage_medium_stmt.reset ();
            store_storage_medium_stmt.bind_text (1, medium_name);
            store_storage_medium_stmt.bind_int (2, 1);
            store_storage_medium_stmt.bind_text (3, icon);
            store_storage_medium_stmt.bind_text (4, display_name);
            if (store_storage_medium_stmt.step () != Sqlite.DONE)
            {
                update_storage_medium_stmt.reset ();
                update_storage_medium_stmt.bind_int (1, 1);
                update_storage_medium_stmt.bind_text (2, icon);
                update_storage_medium_stmt.bind_text (3, display_name);
                update_storage_medium_stmt.bind_text (4, medium_name);
                int rc = update_storage_medium_stmt.step ();
                database.assert_query_success (rc, "add_storage_medium", Sqlite.DONE);
            }
            storage_available (medium_name, StorageMedia.to_variant (
                medium_name, true, icon, display_name));
        }

        public void remove_storage_medium (string medium_name)
        {
            debug ("VOLUME REMOVED: %s".printf(medium_name));
            insert_unavailable_medium_stmt.reset ();
            insert_unavailable_medium_stmt.bind_int (1, 0);
            insert_unavailable_medium_stmt.bind_text (2, medium_name);
            if (insert_unavailable_medium_stmt.step () != Sqlite.DONE)
            {
                update_medium_state_stmt.reset ();
                update_medium_state_stmt.bind_int (1, 0);
                update_medium_state_stmt.bind_text (2, medium_name);
                int rc = update_medium_state_stmt.step ();
                database.assert_query_success (rc, "remove_storage_medium",
                    Sqlite.DONE);
            }
            storage_unavailable (medium_name);
        }

        public Variant get_storages () throws EngineError
        {
            var vb = new VariantBuilder (new VariantType ("a(sa{sv})"));

            int rc;
            get_storages_stmt.reset ();
            while ((rc = get_storages_stmt.step ()) == Sqlite.ROW)
            {
                // name, available?, icon, display name
                Variant medium = StorageMedia.to_variant (
                    get_storages_stmt.column_text (0),
                    get_storages_stmt.column_int (1) == 1,
                    get_storages_stmt.column_text (2) ?? "",
                    get_storages_stmt.column_text (3) ?? "");
                vb.add_value (medium);
            }
            database.assert_query_success (rc, "get_storages", Sqlite.DONE);

            return vb.end ();
        }

    }

    /*
     * Monitor the availability of working network connections using
     *  Network Manager (requires 0.8 or later).
     * See http://projects.gnome.org/NetworkManager/developers/spec-08.html
     */
    class NMNetworkMonitor : Object, NetworkMonitor
    {
        private const string NM_BUS_NAME = "org.freedesktop.NetworkManager";
        private const string NM_IFACE = "org.freedesktop.NetworkManager";
        private const string NM_OBJECT_PATH = "/org/freedesktop/NetworkManager";

        // NM 0.9 broke API so we have to check for two possible values for the state
        private const int NM_STATE_CONNECTED_PRE_09 = 3;
        private const int NM_STATE_CONNECTED_POST_09 = 70;

        private NetworkManagerDBus proxy;

        public NMNetworkMonitor ()
        {
            Object ();
        }

        public void setup ()
        {
            debug ("Creating NetworkManager network monitor");
            try
            {
                proxy = Bus.get_proxy_sync<NetworkManagerDBus> (BusType.SYSTEM,
                                            NM_BUS_NAME,
                                            NM_OBJECT_PATH);
                proxy.state_changed.connect (this.on_state_changed);

                uint32 state = proxy.state ();
                this.on_state_changed (state);
            }
            catch (IOError e )
            {
                warning ("%s", e.message);
            }
        }

        private void on_state_changed(uint32 state)
        {
            debug ("NetworkManager network state: %u", state);
            if (state == NMNetworkMonitor.NM_STATE_CONNECTED_PRE_09 ||
                state == NMNetworkMonitor.NM_STATE_CONNECTED_POST_09)
                on_network_up ();
            else
                on_network_down ();
        }
    }

    class ConnmanNetworkMonitor : Object, NetworkMonitor
    {
        private const string CM_BUS_NAME = "net.connman";
        private const string CM_IFACE = "net.connman.Manager";
        private const string CM_OBJECT_PATH = "/";

        private ConnmanManagerDBus proxy;

        public ConnmanNetworkMonitor ()
        {
            Object ();
        }

        public void setup ()
        {
            debug ("Creating ConnmanNetworkManager network monitor");

            try
            {
                proxy = Bus.get_proxy_sync<ConnmanManagerDBus> (
                    BusType.SYSTEM, CM_BUS_NAME, CM_OBJECT_PATH);

                // There is a bug in some Connman versions causing it
                // to not emit the net.connman.Manager.StateChanged
                // signal. We take our chances this instance is working
                // properly :-)
                proxy.state_changed.connect (this.on_state_changed);

                string state = proxy.get_state ();
                this.on_state_changed (state);
            }
            catch (IOError e )
            {
                warning ("%s", e.message);
            }
        }

        private void on_state_changed(string state)
        {
            debug ("ConnmanNetworkMonitor network state: %s", state);
            if (state == "online")
                on_network_up ();
            else
                on_network_down ();
        }
    }

    [ModuleInit]
#if BUILTIN_EXTENSIONS
    public static Type storage_monitor_init (TypeModule module)
    {
#else
    public static Type extension_register (TypeModule module)
    {
#endif
        return typeof (StorageMonitor);
    }
}

// vim:expandtab:ts=4:sw=4