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