Refactored the IdCard services list to fix new bugs and (hopefully) prevent even...
[moonshot-ui.git] / src / moonshot-identity-manager-app.vala
1 /*
2  * Copyright (c) 2011-2014, 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);
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) {
128         if (view != null) 
129         {
130             logger.trace("add_identity: calling view.add_identity");
131             return view.add_identity(id, force_flat_file_store);
132         }
133
134         logger.trace("add_identity: calling model.add_card");
135         model.add_card(id, force_flat_file_store);
136         return true;
137     }
138
139     public void select_identity(IdentityRequest request) {
140         logger.trace("select_identity");
141
142         IdCard identity = null;
143
144         if (request.select_default)
145         {
146             identity = default_id_card;
147         }
148
149         if (identity == null)
150         {
151             bool has_nai = request.nai != null && request.nai != "";
152             bool has_srv = request.service != null && request.service != "";
153             bool confirm = false;
154
155             foreach (IdCard id in model.get_card_list())
156             {
157                 /* If NAI matches, use this id card */
158                 if (has_nai && request.nai == id.nai)
159                 {
160                     identity = id;
161                     break;
162                 }
163
164                 /* If any service matches we add id card to the candidate list */
165                 if (has_srv)
166                 {
167                     if (id.services.contains(request.service)) {
168                         request.candidates.append(id);
169                     }
170                 }
171             }
172
173             /* If more than one candidate we dissasociate service from all ids */
174             if ((identity == null) && has_srv && request.candidates.length() > 1)
175             {
176                 foreach (IdCard id in request.candidates)
177                 {
178                     id.services.remove(request.service);
179                 }
180             }
181
182             /* If there are no candidates we use the service matching rules */
183             if ((identity == null) && (request.candidates.length() == 0))
184             {
185                 foreach (IdCard id in model.get_card_list())
186                 {
187                     foreach (Rule rule in id.rules)
188                     {
189                         if (!match_service_pattern(request.service, rule.pattern))
190                             continue;
191
192                         request.candidates.append(id);
193
194                         if (rule.always_confirm == "true")
195                             confirm = true;
196                     }
197                 }
198             }
199             
200             if ((identity == null) && has_nai) {
201                 // create a temp identity
202                 string[] components = request.nai.split("@", 2);
203                 identity = new IdCard();
204                 identity.display_name = request.nai;
205                 identity.username = components[0];
206                 if (components.length > 1)
207                     identity.issuer = components[1];
208                 identity.password = request.password;
209                 identity.temporary = true;
210             }
211             if (identity == null) {
212                 if (request.candidates.length() != 1) {
213                     logger.trace("select_identity: Have %u candidates; user must make selection.".printf(request.candidates.length()));
214                     confirm = true;
215                 } else {
216                     identity = request.candidates.nth_data(0);                    
217                 }
218             }
219
220             if (confirm && (view != null))
221             {
222                 if (!explicitly_launched)
223                     show();
224                 view.queue_identity_request(request);
225                 return;
226             }
227         }
228         // Send back the identity (we can't directly run the
229         // callback because we may be being called from a 'yield')
230         GLib.Idle.add(
231             () => {
232                 if (view != null) {
233                     logger.trace("select_identity (Idle handler): calling check_add_password");
234                     identity = view.check_add_password(identity, request, model);
235                 }
236                 request.return_identity(identity);
237 // The following occasionally causes the app to exit without sending the dbus
238 // reply, so for now we just don't exit
239 //                if (!explicitly_launched)
240 //                    Idle.add(() => { Gtk.main_quit(); return false; } );
241                 return false;
242             }
243             );
244         return;
245     }
246
247     private bool match_service_pattern(string service, string pattern) {
248         var pspec = new PatternSpec(pattern);
249         return pspec.match_string(service);
250     }   
251     
252 #if IPC_MSRPC
253     private void init_ipc_server() {
254         // Errors will currently be sent via g_log - ie. to an
255         // obtrusive message box, on Windows
256         //
257         this.ipc_server = MoonshotServer.get_instance();
258         MoonshotServer.start(this);
259     }
260 #elif IPC_DBUS_GLIB
261     private void init_ipc_server() {
262         try {
263             var conn = DBus.Bus.get(DBus.BusType.SESSION);
264             dynamic DBus.Object bus = conn.get_object("org.freedesktop.DBus",
265                                                       "/org/freedesktop/DBus",
266                                                       "org.freedesktop.DBus");
267
268             // try to register service in session bus
269             uint reply = bus.request_name("org.janet.Moonshot", (uint) 0);
270             if (reply == DBus.RequestNameReply.PRIMARY_OWNER)
271             {
272                 this.ipc_server = new MoonshotServer(this);
273                 logger.trace("init_ipc_server(IPC_DBUS_GLIB) : Constructed new MoonshotServer");
274                 conn.register_object("/org/janet/moonshot", ipc_server);
275             } else {
276                 logger.trace("init_ipc_server: reply != PRIMARY_OWNER");
277                 bool shown = false;
278                 GLib.Error e;
279                 DBus.Object manager_proxy = conn.get_object("org.janet.Moonshot",
280                                                             "/org/janet/moonshot",
281                                                             "org.janet.Moonshot");
282                 if (manager_proxy != null)
283                     manager_proxy.call("ShowUi", out e, GLib.Type.INVALID, typeof(bool), out shown, GLib.Type.INVALID);
284
285                 if (!shown) {
286                     GLib.error("Couldn't own name org.janet.Moonshot on dbus or show previously launched identity manager.");
287                 } else {
288                     stdout.printf("Showed previously launched identity manager.\n");
289                     GLib.Process.exit(0);
290                 }
291             }
292         }
293         catch (DBus.Error e)
294         {
295             logger.trace("bus_acquired_cb");
296             try {
297                 conn.register_object ("/org/janet/moonshot", ipc_server);
298             }
299             catch (Error e)
300             {
301                 stderr.printf ("%s\n", e.message);
302                 logger.error("bus_acquired_cb: Caught error: " + e.message);
303             }
304         }
305     }
306 #else
307     private void bus_acquired_cb(DBusConnection conn) {
308         logger.trace("bus_acquired_cb");
309         try {
310             conn.register_object("/org/janet/moonshot", ipc_server);
311         }
312         catch (Error e)
313         {
314             this.ipc_server = new MoonshotServer (this);
315             logger.trace("init_ipc_server: Constructed new MoonshotServer");
316             GLib.Bus.own_name (GLib.BusType.SESSION,
317                                "org.janet.Moonshot",
318                                GLib.BusNameOwnerFlags.NONE,
319                                bus_acquired_cb,
320                                (conn, name) => {logger.trace("init_ipc_server: name_acquired_closure");},
321                                (conn, name) => {
322                                    logger.trace("init_ipc_server: name_lost_closure");
323                                    bool shown=false;
324                                    try {
325                                        IIdentityManager manager = Bus.get_proxy_sync (BusType.SESSION, name, "/org/janet/moonshot");
326                                        shown = manager.show_ui();
327                                    } catch (IOError e) {
328                                        logger.error("init_ipc_server.name_lost_closure: Caught error: ");
329                                    }
330                                    if (!shown) {
331                                        logger.error("init_ipc_server.name_lost_closure: Couldn't own name %s on dbus or show previously launched identity manager".printf(name));
332                                        GLib.error ("Couldn't own name %s on dbus or show previously launched identity manager.", name);
333                                    } else {
334                                        logger.trace("init_ipc_server.name_lost_closure: Showed previously launched identity manager.");
335                                        stdout.printf("Showed previously launched identity manager.\n");
336                                        GLib.Process.exit(0);
337                                    }
338                                });
339         }
340     }
341
342     private void init_ipc_server() {
343         this.ipc_server = new MoonshotServer(this);
344         bool shown = false;
345         GLib.Bus.own_name(GLib.BusType.SESSION,
346                           "org.janet.Moonshot",
347                           GLib.BusNameOwnerFlags.NONE,
348                           bus_acquired_cb,
349
350                           // Name acquired callback:
351                           (conn, name) => {
352                               logger.trace(@"init_ipc_server: name_acquired_closure; show_requested=$show_requested");
353
354                               name_is_owned = true;
355
356                               // Now that we know that we own the name, it's safe to show the UI.
357                               if (show_requested) {
358                                   show();
359                                   show_requested = false;
360                               }
361                               shown = true;
362                           },
363
364                           // Name lost callback:
365                           (conn, name) => {
366                               logger.trace("init_ipc_server: name_lost_closure");
367
368                               // This callback usually means that another moonshot is already running.
369                               // But it *might* mean that we lost the name for some other reason
370                               // (though it's unclear to me yet what those reasons are.)
371                               // Clearing these flags seems like a good idea for that case. -- dbreslau
372                               name_is_owned = false;
373                               show_requested = false;
374
375                               try {
376                                   if (!shown) {
377                                       IIdentityManager manager = Bus.get_proxy_sync(BusType.SESSION, name, "/org/janet/moonshot");
378                                       shown = manager.show_ui();
379                                   }
380                               } catch (IOError e) {
381                                   logger.error("init_ipc_server.name_lost_closure: Caught IOError: " + e.message);
382                               }
383                               if (!shown) {
384                                   logger.error("init_ipc_server.name_lost_closure: Couldn't own name %s on dbus or show previously launched identity manager".printf(name));
385                                   GLib.error("Couldn't own name %s on dbus or show previously launched identity manager.", name);
386                               } else {
387                                   logger.trace("init_ipc_server.name_lost_closure: Showed previously launched identity manager.");
388                                   stdout.printf("Showed previously launched identity manager.\n");
389                                   GLib.Process.exit(0);
390                               }
391                           });
392     }
393 #endif
394 }
395
396 static bool explicitly_launched = true;
397 static bool use_flat_file_store = false;
398 const GLib.OptionEntry[] options = {
399     {"dbus-launched", 0, GLib.OptionFlags.REVERSE, GLib.OptionArg.NONE,
400      ref explicitly_launched, "launch for dbus rpc use", null},
401     {"flat-file-store", 0, 0, GLib.OptionArg.NONE,
402      ref use_flat_file_store, "force use of flat file identity store (used by default only for headless operation)", null},
403     {null}
404 };
405
406
407 public static int main(string[] args) {
408
409 #if LOG4VALA
410     new IdentityManagerApp.dummy();
411 #endif
412
413 #if IPC_MSRPC
414     bool headless = false;
415 #else
416     bool headless = GLib.Environment.get_variable("DISPLAY") == null;
417 #endif
418
419     if (headless) {
420         try {
421             var opt_context = new OptionContext(null);
422             opt_context.set_help_enabled(true);
423             opt_context.add_main_entries(options, null);
424             opt_context.parse(ref args);
425         } catch (OptionError e) {
426             stdout.printf(_("error: %s\n"),e.message);
427             stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
428             return -1;
429         }
430         explicitly_launched = false;
431     } else {
432         try {
433             if (!Gtk.init_with_args(ref args, _(""), options, null)) {
434                 stdout.printf(_("unable to initialize window\n"));
435                 return -1;
436             }
437         } catch (GLib.Error e) {
438             stdout.printf(_("error: %s\n"),e.message);
439             stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
440             return -1;
441         }
442         gtk_available = true;
443     }
444
445 #if OS_WIN32
446     // Force specific theme settings on Windows without requiring a gtkrc file
447     Gtk.Settings settings = Gtk.Settings.get_default();
448     settings.set_string_property("gtk-theme-name", "ms-windows", "moonshot");
449     settings.set_long_property("gtk-menu-images", 0, "moonshot");
450 #endif
451
452     Intl.bindtextdomain(Config.GETTEXT_PACKAGE, Config.LOCALEDIR);
453     Intl.bind_textdomain_codeset(Config.GETTEXT_PACKAGE, "UTF-8");
454     Intl.textdomain(Config.GETTEXT_PACKAGE);
455        
456        
457     var app = new IdentityManagerApp(headless, use_flat_file_store);
458     app.explicitly_launched = explicitly_launched;
459     IdentityManagerApp.logger.trace(@"main: explicitly_launched=$explicitly_launched");
460         
461     if (app.explicitly_launched) {
462         app.show();
463     }
464
465     if (headless) {
466 #if !IPC_MSRPC
467         MainLoop loop = new MainLoop();
468         loop.run();
469 #endif
470     }
471     else {
472         Gtk.main();
473     }
474
475     return 0;
476 }
477