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