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