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