Squashed merge of many commits, including (but not limited to) :
[moonshot-ui.git] / src / moonshot-identity-manager-app.vala
1 /*
2  * Copyright (c) 2011-2016, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31 */
32 using Gee;
33 using Gtk;
34
35 #if IPC_DBUS
36 [DBus (name = "org.janet.Moonshot")]
37 interface IIdentityManager : GLib.Object {
38 #if IPC_DBUS_GLIB
39     public abstract bool show_ui() throws DBus.Error;
40 #else
41     public abstract bool show_ui() throws IOError;
42 #endif
43 }
44 #endif
45
46
47 public class IdentityManagerApp {
48     public static MoonshotLogger logger = get_logger("IdentityManagerApp");
49
50     public IdentityManagerModel model;
51     public IdCard default_id_card;
52     public bool explicitly_launched;
53     public IdentityManagerView view;
54     private MoonshotServer ipc_server;
55     private bool name_is_owned;
56     private bool show_requested;
57     public bool use_flat_file_store {public get; private set;}
58
59 #if OS_MACOS
60     public OSXApplication osxApp;
61   
62     // the signal handler function.
63     // the current instance of our app class is passed in the 
64     // id_manager_app_instanceparameter 
65     public static bool on_osx_open_files(OSXApplication osx_app_instance, 
66                                          string file_name, 
67                                          IdentityManagerApp id_manager_app_instance ) {
68         int added_cards = id_manager_app_instance.ipc_server.install_from_file(file_name);
69         return true;
70     }
71 #endif
72
73     /** If we're successfully registered with DBus, then show the UI. Otherwise, wait until we're registered. */
74     public void show() {
75         if (name_is_owned) {
76             if (view != null) {
77                 view.make_visible();
78             }
79         }
80         else {
81             show_requested = true;
82         }
83     }
84     
85 #if USE_LOG4VALA
86     // Call this from main() to ensure that the logger is initialized
87     internal IdentityManagerApp.dummy() {}
88 #endif
89
90     public IdentityManagerApp(bool headless, bool use_flat_file_store) {
91         use_flat_file_store |= UserForcesFlatFileStore();
92         this.use_flat_file_store = use_flat_file_store;
93
94 #if GNOME_KEYRING
95         bool keyring_available = (!use_flat_file_store) && GnomeKeyring.is_available();
96 #else
97         bool keyring_available = false;
98 #endif
99
100         IIdentityCardStore.StoreType store_type;
101         if (headless || use_flat_file_store || !keyring_available)
102             store_type = IIdentityCardStore.StoreType.FLAT_FILE;
103         else
104             store_type = IIdentityCardStore.StoreType.KEYRING;
105
106         model = new IdentityManagerModel(this, store_type);
107         /* if headless, but we have nothing in the flat file store
108          * and keyring is available, switch to keyring */
109         if (headless && keyring_available && !use_flat_file_store && !model.HasNonTrivialIdentities())
110             model.set_store_type(IIdentityCardStore.StoreType.KEYRING);
111
112         if (!headless)
113             view = new IdentityManagerView(this, use_flat_file_store);
114         LinkedList<IdCard> card_list = model.get_card_list();
115         if (card_list.size > 0)
116             this.default_id_card = card_list.last();
117
118         init_ipc_server();
119
120 #if OS_MACOS
121         osxApp = OSXApplication.get_instance();
122         // The 'correct' way of connecting won't work in Mac OS with Vala 0.12; e.g.
123         //     osxApp.ns_application_open_file.connect(install_from_file);
124         // so we have to use this old way
125         Signal.connect(osxApp, "NSApplicationOpenFile", (GLib.Callback)(on_osx_open_files), this);
126 #endif
127     }
128
129     public bool add_identity(IdCard id, bool force_flat_file_store, out ArrayList<IdCard>? old_duplicates=null) {
130         if (view != null) 
131         {
132             logger.trace("add_identity: calling view.add_identity");
133             return view.add_identity(id, force_flat_file_store, out old_duplicates);
134         }
135         else {
136             logger.trace("add_identity: calling model.add_card");
137             model.add_card(id, force_flat_file_store, out old_duplicates);
138             return true;
139         }
140     }
141
142     public void select_identity(IdentityRequest request) {
143         logger.trace("select_identity: request.nai=%s".printf(request.nai ?? "[null]"));
144
145         IdCard identity = null;
146
147         if (request.select_default)
148         {
149             identity = default_id_card;
150         }
151
152         if (identity == null)
153         {
154             bool has_nai = request.nai != null && request.nai != "";
155             bool has_srv = request.service != null && request.service != "";
156             bool confirm = false;
157
158             foreach (IdCard id in model.get_card_list())
159             {
160                 /* If NAI matches, use this id card */
161                 if (has_nai && request.nai == id.nai)
162                 {
163                     logger.trace("select_identity: request has nai; returning " + id.display_name);
164                     identity = id;
165                     break;
166                 }
167
168                 /* If any service matches we add id card to the candidate list */
169                 if (has_srv)
170                 {
171                     if (id.services.contains(request.service)) {
172                         logger.trace(@"select_identity: request has service '$(request.service); matched on '$(id.display_name)'");
173                         request.candidates.append(id);
174                     }
175                 }
176             }
177
178             /* If more than one candidate we dissasociate service from all ids */
179             if ((identity == null) && has_srv && request.candidates.length() > 1)
180             {
181                 logger.trace(@"select_identity: multiple candidates; removing service '$(request.service) from all.");
182                 foreach (IdCard id in request.candidates)
183                 {
184                     id.services.remove(request.service);
185                 }
186             }
187
188             /* If there are no candidates we use the service matching rules */
189             if ((identity == null) && (request.candidates.length() == 0))
190             {
191                 logger.trace("select_identity: No candidates; using service matching rules.");
192                 foreach (IdCard id in model.get_card_list())
193                 {
194                     foreach (Rule rule in id.rules)
195                     {
196                         if (!match_service_pattern(request.service, rule.pattern))
197                             continue;
198
199                         logger.trace(@"select_identity: ID $(id.display_name) matched on service matching rules.");
200                         request.candidates.append(id);
201
202                         if (rule.always_confirm == "true")
203                             confirm = true;
204                     }
205                 }
206             }
207             
208             if ((identity == null) && has_nai) {
209                 logger.trace("select_identity: Creating temp identity");
210                 // create a temp identity
211                 string[] components = request.nai.split("@", 2);
212                 identity = new IdCard();
213                 identity.display_name = request.nai;
214                 identity.username = components[0];
215                 if (components.length > 1)
216                     identity.issuer = components[1];
217                 identity.password = request.password;
218                 identity.temporary = true;
219             }
220             if (identity == null) {
221                 if (request.candidates.length() != 1) {
222                     logger.trace("select_identity: Have %u candidates; user must make selection.".printf(request.candidates.length()));
223                     confirm = true;
224                 } else {
225                     identity = request.candidates.nth_data(0);                    
226                 }
227             }
228
229             if (confirm && (view != null))
230             {
231                 if (!explicitly_launched)
232                     show();
233                 view.queue_identity_request(request);
234                 return;
235             }
236         }
237         // Send back the identity (we can't directly run the
238         // callback because we may be being called from a 'yield')
239         GLib.Idle.add(
240             () => {
241                 if (view != null) {
242                     logger.trace("select_identity (Idle handler): calling check_add_password");
243                     identity = view.check_add_password(identity, request, model);
244                 }
245                 request.return_identity(identity);
246 // The following occasionally causes the app to exit without sending the dbus
247 // reply, so for now we just don't exit
248 //                if (!explicitly_launched)
249 //                    Idle.add(() => { Gtk.main_quit(); return false; } );
250                 return false;
251             }
252             );
253         return;
254     }
255
256     private bool match_service_pattern(string service, string pattern) {
257         var pspec = new PatternSpec(pattern);
258         return pspec.match_string(service);
259     }   
260     
261 #if IPC_MSRPC
262     private void init_ipc_server() {
263         // Errors will currently be sent via g_log - ie. to an
264         // obtrusive message box, on Windows
265         //
266         this.ipc_server = MoonshotServer.get_instance();
267         MoonshotServer.start(this);
268     }
269 #elif IPC_DBUS_GLIB
270     private void init_ipc_server() {
271         try {
272             var conn = DBus.Bus.get(DBus.BusType.SESSION);
273             dynamic DBus.Object bus = conn.get_object("org.freedesktop.DBus",
274                                                       "/org/freedesktop/DBus",
275                                                       "org.freedesktop.DBus");
276
277             // try to register service in session bus
278             uint reply = bus.request_name("org.janet.Moonshot", (uint) 0);
279             if (reply == DBus.RequestNameReply.PRIMARY_OWNER)
280             {
281                 this.ipc_server = new MoonshotServer(this);
282                 logger.trace("init_ipc_server(IPC_DBUS_GLIB) : Constructed new MoonshotServer");
283                 conn.register_object("/org/janet/moonshot", ipc_server);
284             } else {
285                 logger.trace("init_ipc_server: reply != PRIMARY_OWNER");
286                 bool shown = false;
287                 GLib.Error e;
288                 DBus.Object manager_proxy = conn.get_object("org.janet.Moonshot",
289                                                             "/org/janet/moonshot",
290                                                             "org.janet.Moonshot");
291                 if (manager_proxy != null)
292                     manager_proxy.call("ShowUi", out e, GLib.Type.INVALID, typeof(bool), out shown, GLib.Type.INVALID);
293
294                 if (!shown) {
295                     GLib.error("Couldn't own name org.janet.Moonshot on dbus or show previously launched identity manager.");
296                 } else {
297                     stdout.printf(_("Showed previously launched identity manager.\n"));
298                     GLib.Process.exit(0);
299                 }
300             }
301         }
302         catch (DBus.Error e)
303         {
304             logger.trace("bus_acquired_cb");
305             try {
306                 conn.register_object ("/org/janet/moonshot", ipc_server);
307             }
308             catch (Error e)
309             {
310                 stderr.printf ("%s\n", e.message);
311                 logger.error("bus_acquired_cb: Caught error: " + e.message);
312             }
313         }
314     }
315 #else
316     private void bus_acquired_cb(DBusConnection conn) {
317         logger.trace("bus_acquired_cb");
318         try {
319             conn.register_object("/org/janet/moonshot", ipc_server);
320         }
321         catch (Error e)
322         {
323             this.ipc_server = new MoonshotServer (this);
324             logger.trace("init_ipc_server: Constructed new MoonshotServer");
325             GLib.Bus.own_name (GLib.BusType.SESSION,
326                                "org.janet.Moonshot",
327                                GLib.BusNameOwnerFlags.NONE,
328                                bus_acquired_cb,
329                                (conn, name) => {logger.trace("init_ipc_server: name_acquired_closure");},
330                                (conn, name) => {
331                                    logger.trace("init_ipc_server: name_lost_closure");
332                                    bool shown=false;
333                                    try {
334                                        IIdentityManager manager = Bus.get_proxy_sync (BusType.SESSION, name, "/org/janet/moonshot");
335                                        shown = manager.show_ui();
336                                    } catch (IOError e) {
337                                        logger.error("init_ipc_server.name_lost_closure: Caught error: ");
338                                    }
339                                    if (!shown) {
340                                        logger.error("init_ipc_server.name_lost_closure: Couldn't own name %s on dbus or show previously launched identity manager".printf(name));
341                                        GLib.error ("Couldn't own name %s on dbus or show previously launched identity manager.", name);
342                                    } else {
343                                        logger.trace("init_ipc_server.name_lost_closure: Showed previously launched identity manager.");
344                                        stdout.printf("Showed previously launched identity manager.\n");
345                                        GLib.Process.exit(0);
346                                    }
347                                });
348         }
349     }
350
351     private void init_ipc_server() {
352         this.ipc_server = new MoonshotServer(this);
353         bool shown = false;
354         GLib.Bus.own_name(GLib.BusType.SESSION,
355                           "org.janet.Moonshot",
356                           GLib.BusNameOwnerFlags.NONE,
357                           bus_acquired_cb,
358
359                           // Name acquired callback:
360                           (conn, name) => {
361                               logger.trace(@"init_ipc_server: name_acquired_closure; show_requested=$show_requested");
362
363                               name_is_owned = true;
364
365                               // Now that we know that we own the name, it's safe to show the UI.
366                               if (show_requested) {
367                                   show();
368                                   show_requested = false;
369                               }
370                               shown = true;
371                           },
372
373                           // Name lost callback:
374                           (conn, name) => {
375                               logger.trace("init_ipc_server: name_lost_closure");
376
377                               // This callback usually means that another moonshot is already running.
378                               // But it *might* mean that we lost the name for some other reason
379                               // (though it's unclear to me yet what those reasons are.)
380                               // Clearing these flags seems like a good idea for that case. -- dbreslau
381                               name_is_owned = false;
382                               show_requested = false;
383
384                               try {
385                                   if (!shown) {
386                                       IIdentityManager manager = Bus.get_proxy_sync(BusType.SESSION, name, "/org/janet/moonshot");
387                                       shown = manager.show_ui();
388                                   }
389                               } catch (IOError e) {
390                                   logger.error("init_ipc_server.name_lost_closure: Caught IOError: " + e.message);
391                               }
392                               if (!shown) {
393                                   logger.error("init_ipc_server.name_lost_closure: Couldn't own name %s on dbus or show previously launched identity manager".printf(name));
394                                   GLib.error("Couldn't own name %s on dbus or show previously launched identity manager.", name);
395                               } else {
396                                   logger.trace("init_ipc_server.name_lost_closure: Showed previously launched identity manager.");
397                                   stdout.printf("Showed previously launched identity manager.\n");
398                                   GLib.Process.exit(0);
399                               }
400                           });
401     }
402 #endif
403 }
404
405 static bool explicitly_launched = true;
406 static bool use_flat_file_store = false;
407 const GLib.OptionEntry[] options = {
408     {"dbus-launched", 0, GLib.OptionFlags.REVERSE, GLib.OptionArg.NONE,
409      ref explicitly_launched, "launch for dbus rpc use", null},
410     {"flat-file-store", 0, 0, GLib.OptionArg.NONE,
411      ref use_flat_file_store, "force use of flat file identity store (used by default only for headless operation)", null},
412     {null}
413 };
414
415
416 public static int main(string[] args) {
417
418 #if USE_LOG4VALA
419     // Initialize the logger.
420     new IdentityManagerApp.dummy();
421 #endif
422
423 #if IPC_MSRPC
424     bool headless = false;
425 #else
426     bool headless = GLib.Environment.get_variable("DISPLAY") == null;
427 #endif
428
429     if (headless) {
430         try {
431             var opt_context = new OptionContext(null);
432             opt_context.set_help_enabled(true);
433             opt_context.add_main_entries(options, null);
434             opt_context.parse(ref args);
435         } catch (OptionError e) {
436             stdout.printf(_("error: %s\n"),e.message);
437             stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
438             return -1;
439         }
440         explicitly_launched = false;
441     } else {
442         try {
443             if (!Gtk.init_with_args(ref args, _(""), options, null)) {
444                 stdout.printf(_("unable to initialize window\n"));
445                 return -1;
446             }
447         } catch (GLib.Error e) {
448             stdout.printf(_("error: %s\n"),e.message);
449             stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
450             return -1;
451         }
452         gtk_available = true;
453     }
454
455 #if OS_WIN32
456     // Force specific theme settings on Windows without requiring a gtkrc file
457     Gtk.Settings settings = Gtk.Settings.get_default();
458     settings.set_string_property("gtk-theme-name", "ms-windows", "moonshot");
459     settings.set_long_property("gtk-menu-images", 0, "moonshot");
460 #endif
461
462     //TODO?? Do we need to call Intl.setlocale(LocaleCategory.MESSAGES, "");
463     Intl.bindtextdomain(Config.GETTEXT_PACKAGE, Config.LOCALEDIR);
464     Intl.bind_textdomain_codeset(Config.GETTEXT_PACKAGE, "UTF-8");
465     Intl.textdomain(Config.GETTEXT_PACKAGE);
466        
467        
468     var app = new IdentityManagerApp(headless, use_flat_file_store);
469     app.explicitly_launched = explicitly_launched;
470     IdentityManagerApp.logger.trace(@"main: explicitly_launched=$explicitly_launched");
471         
472     if (app.explicitly_launched) {
473         app.show();
474     }
475
476     if (headless) {
477 #if !IPC_MSRPC
478         MainLoop loop = new MainLoop();
479         loop.run();
480 #endif
481     }
482     else {
483         Gtk.main();
484     }
485
486     return 0;
487 }
488