summaryrefslogtreecommitdiff
path: root/src/rygel/application.vala
blob: 1f30d2a8697b80461586db9d16fe36e9ef85e885 (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
using Gee;
using GUPnP;

public class Rygel.Application : GLib.Application {
    // Default time to wait for plugins showing up
    private static int PLUGIN_TIMEOUT = 5;

    private PluginLoader plugin_loader;
    private ContextManager context_manager;
    private ArrayList <RootDeviceFactory> factories;
    private ArrayList <RootDevice> root_devices;

    private Configuration config;
    private LogHandler log_handler;
    private Acl acl;

    private bool activation_pending = false;

    public Application() {
        Object(application_id : "org.gnome.Rygel",
               flags : ApplicationFlags.HANDLES_COMMAND_LINE |
                       ApplicationFlags.ALLOW_REPLACEMENT);

        this.add_main_option_entries (CmdlineConfig.OPTIONS);

        Unix.signal_add (ProcessSignal.INT, () => { this.release (); return false; });
        Unix.signal_add (ProcessSignal.TERM, () => { this.release (); return false; });
        Unix.signal_add (ProcessSignal.HUP, () => { this.release (); return false; });
    }

    public override int handle_local_options (VariantDict options) {
        int count;
        if (options.lookup ("version", "b", out count)) {
            print ("%s\n", BuildConfig.PACKAGE_STRING);

            return 0;
        }

        // Further options to be handled remotely
        return -1;
    }

    public override int command_line (GLib.ApplicationCommandLine command_line) {
        var options = command_line.get_options_dict ();
        if (options.contains ("shutdown")) {
            release ();

            return 0;
        }

        CmdlineConfig.get_default ().set_options (options);

        activate ();

        return -1;
    }

    private void register_default_configurations () {

        var cmdline_config = CmdlineConfig.get_default ();

        MetaConfig.register_configuration (cmdline_config);
        MetaConfig.register_configuration (EnvironmentConfig.get_default ());

        try {
            var config_file = cmdline_config.get_config_file ();
            var user_config = new UserConfig (config_file);
            MetaConfig.register_configuration (user_config);
        } catch (Error error) {
            try {
                var user_config = UserConfig.get_default ();
                MetaConfig.register_configuration (user_config);
            } catch (Error err) {
                warning (_("Failed to load user configuration: %s"), err.message);
            }
        }
    }

    private void run_everything () {
        this.register_default_configurations ();

        this.log_handler = LogHandler.get_default ();
        this.config = MetaConfig.get_default ();
        this.plugin_loader = new PluginLoader ();
        this.root_devices = new ArrayList <RootDevice> ();
        this.factories = new ArrayList <RootDeviceFactory> ();
        this.acl = new Acl ();

        this.plugin_loader.plugin_available.connect (this.on_plugin_loaded);
        this.context_manager = this.create_context_manager ();
        this.plugin_loader.load_modules ();
        this.activation_pending = false;

        var timeout = PLUGIN_TIMEOUT;
        try {
            var config = MetaConfig.get_default ();
            timeout = config.get_int ("plugin",
                                      "TIMEOUT",
                                      0,
                                      int.MAX);
        } catch (Error error) {};

        if (timeout == 0) {
            debug ("Plugin timeout disabled...");

            return;
        }

        Timeout.add_seconds (timeout, () => {
            if (this.plugin_loader.list_plugins ().size == 0) {
                warning (ngettext ("No plugins found in %d second; giving up…",
                                   "No plugins found in %d seconds; giving up…",
                                   PLUGIN_TIMEOUT),
                         PLUGIN_TIMEOUT);
                this.release ();
            }

            return false;
        });
    }

    public override void activate () {
        base.activate ();
        if (this.context_manager == null || this.activation_pending) {
            hold ();
            if (ApplicationFlags.REPLACE in this.flags) {
                this.activation_pending = true;
                // Delay context manager creation to give the other instance a chance to
                // give up the socket
                Timeout.add_seconds (1, () => { this.run_everything (); return false; });
            } else {
                this.run_everything ();
            }
        }
    }

    public override void startup () {
        base.startup ();

        message (_("Rygel v%s starting…"), BuildConfig.PACKAGE_VERSION);
    }

    public override void shutdown () {
        this.root_devices = null;
        base.shutdown ();
    }

    public override bool name_lost () {
        this.root_devices = null;
        this.release ();

        return true;
    }

    private void on_plugin_loaded (PluginLoader plugin_loader,
                                   Plugin       plugin) {
        var iterator = this.factories.iterator ();
        while (iterator.next ()) {
            this.create_device.begin (plugin, iterator.get ());
        }
    }

    private async void create_device (Plugin            plugin,
                                      RootDeviceFactory factory) {
        // The call to factory.create(), although synchronous spins the
        // the mainloop and therefore might in turn triger some of the signal
        // handlers here that modify one of the lists that we might be iterating
        // while this function is called. Modification of an ArrayList while
        // iterating it is currently unsuppored and leads to a crash and that is
        // why defer to mainloop here.
        Idle.add (create_device.callback);
        yield;

        try {
            var device = factory.create (plugin);

            device.available = plugin.active;

            // Due to pure evilness of unix sinals this might actually happen
            // if someone shuts down rygel while the call-back is running,
            // leading to a crash on shutdown
            if (this.root_devices != null) {
                this.root_devices.add (device);

                plugin.notify["active"].connect (this.on_plugin_active_notify);
            }
        } catch (GLib.Error error) {
            warning (_("Failed to create RootDevice for %s. Reason: %s"),
                     plugin.name,
                     error.message);
        }
    }

    private void on_plugin_active_notify (Object    obj,
                                          ParamSpec spec) {
        if (unlikely (this.root_devices == null)) {
            return;
        }

        var plugin = obj as Plugin;

        foreach (var device in this.root_devices) {
            if (device.resource_factory == plugin) {
                device.available = plugin.active;
            }
        }
    }


    private ContextManager create_context_manager () {
        int port = 0;
        bool ipv6 = false;

        try {
            port = this.config.get_port ();
        } catch (GLib.Error err) {}

        try {
            ipv6 = this.config.get_bool ("general", "ipv6");
        } catch (GLib.Error err) {
            debug ("No ipv6 config key found, using default %s", ipv6.to_string ());
        }

        // INVALID means "all"
        var family = GLib.SocketFamily.INVALID;
        if (!ipv6) {
            family = GLib.SocketFamily.IPV4;
        }

        var manager = ContextManager.create_full (GSSDP.UDAVersion.VERSION_1_0,
                                                  family,
                                                  port);

        manager.context_available.connect (this.on_context_available);
        manager.context_unavailable.connect (this.on_context_unavailable);

        return manager;
    }

    private void on_context_available (GUPnP.ContextManager manager,
                                       GUPnP.Context        context) {
        string[] ifaces = null;

        debug ("New network %s (%s) context available. IP: %s",
               context.network,
               context.interface,
               context.host_ip);

        context.acl = this.acl;

        try {
            ifaces = this.config.get_interfaces ();
        } catch (GLib.Error err) {
        }

        if (ifaces == null ||
            context.interface in ifaces ||
            context.network in ifaces ||
            context.host_ip in ifaces) {
            try {
                var factory = new RootDeviceFactory (context);
                this.factories.add (factory);

                var iterator = this.plugin_loader.list_plugins ().iterator ();
                while (iterator.next ()) {
                    this.create_device.begin (iterator.get (), factory);
                }
            } catch (GLib.Error err) {
                warning (_("Failed to create root device factory: %s"),
                         err.message);
            }
        } else {
            debug ("Ignoring network %s (%s) context.",
                   context.network,
                   context.interface);
            context.active = false;
        }
    }

    private void on_context_unavailable (GUPnP.ContextManager manager,
                                         GUPnP.Context        context) {
        debug ("Network %s (%s) context now unavailable. IP: %s",
               context.network,
               context.interface,
               context.host_ip);

        var factory_iter = this.factories.iterator ();
        while (factory_iter.next ()) {
            if (context == factory_iter.get ().context) {
                factory_iter.remove ();
            }
        }

        var device_iter = this.root_devices.iterator ();
        while (device_iter.next ()) {
            if (context == device_iter.get ().context) {
                device_iter.remove ();
            }
        }
    }

    public static int main(string[] args) {
        Environment.set_application_name (_(BuildConfig.PACKAGE_NAME));

        Intl.setlocale (LocaleCategory.ALL, "");
        Intl.bindtextdomain (BuildConfig.GETTEXT_PACKAGE,
                             BuildConfig.LOCALEDIR);
        Intl.bind_textdomain_codeset (BuildConfig.GETTEXT_PACKAGE, "UTF-8");
        Intl.textdomain (BuildConfig.GETTEXT_PACKAGE);

        Rygel.Application app = new Rygel.Application ();

        return app.run (args);
    }
}