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