Modify identity selection logic / fix bugs
[moonshot-ui.git] / src / moonshot-identity-manager-app.vala
1 using Gee;
2 using Gtk;
3
4 #if IPC_DBUS
5 [DBus (name = "org.janet.Moonshot")]
6 interface IIdentityManager : GLib.Object {
7 #if IPC_DBUS_GLIB
8     public abstract bool show_ui() throws DBus.Error;
9 #else
10     public abstract bool show_ui() throws IOError;
11 #endif
12 }
13 #endif
14
15 public class IdentityManagerApp {
16     public IdentityManagerModel model;
17     public IdCard default_id_card;
18     public bool explicitly_launched;
19     public IdentityManagerView view;
20     private MoonshotServer ipc_server;
21
22 #if OS_MACOS
23         public OSXApplication osxApp;
24   
25     // the signal handler function.
26     // the current instance of our app class is passed in the 
27     // id_manager_app_instanceparameter 
28         public static bool on_osx_open_files (OSXApplication osx_app_instance, 
29                                         string file_name, 
30                                         IdentityManagerApp id_manager_app_instance ) {
31     int added_cards = id_manager_app_instance.ipc_server.install_from_file(file_name);
32     return true;
33         }
34 #endif
35
36     private const int WINDOW_WIDTH = 400;
37     private const int WINDOW_HEIGHT = 500;
38     public void show() {
39         if (view != null) view.show();    
40     }
41         
42     public IdentityManagerApp (bool headless, bool use_flat_file_store) {
43         use_flat_file_store |= UserForcesFlatFileStore();
44 #if GNOME_KEYRING
45         bool keyring_available = (!use_flat_file_store) && GnomeKeyring.is_available();
46 #else
47         bool keyring_available = false;
48 #endif
49         IIdentityCardStore.StoreType store_type;
50         if (headless || use_flat_file_store || !keyring_available)
51             store_type = IIdentityCardStore.StoreType.FLAT_FILE;
52         else
53             store_type = IIdentityCardStore.StoreType.KEYRING;
54
55         model = new IdentityManagerModel(this, store_type);
56         /* if headless, but we have nothing in the flat file store
57          * and keyring is available, switch to keyring */
58         if (headless && keyring_available && !use_flat_file_store && !model.HasNonTrivialIdentities())
59             model.set_store_type(IIdentityCardStore.StoreType.KEYRING);
60
61         if (!headless)
62             view = new IdentityManagerView(this);
63         LinkedList<IdCard> card_list = model.get_card_list() ;
64         if (card_list.size > 0)
65             this.default_id_card = card_list.first();
66
67         init_ipc_server ();
68
69 #if OS_MACOS
70
71         osxApp = OSXApplication.get_instance();
72         // The 'correct' way of connrcting wont work in Mac OS with Vala 0.12   e.g.    
73         //              osxApp.ns_application_open_file.connect(install_from_file);
74         // so we have to use this old way
75         Signal.connect(osxApp, "NSApplicationOpenFile", (GLib.Callback)(on_osx_open_files), this);
76
77 #endif
78     }
79
80     public bool add_identity (IdCard id, bool force_flat_file_store) {
81         if (view != null) return view.add_identity(id, force_flat_file_store);
82         model.add_card(id, force_flat_file_store);
83         return true;
84     }
85
86     public void select_identity (IdentityRequest request) {
87         IdCard identity = null;
88
89         if (request.select_default)
90         {
91             identity = default_id_card;
92         }
93
94         if (identity == null)
95         {
96             bool has_nai = request.nai != null && request.nai != "";
97             bool has_srv = request.service != null && request.service != "";
98             bool confirm = false;
99
100             foreach (IdCard id in model.get_card_list())
101             {
102                 /* If NAI matches, use this id card */
103                 if (has_nai && request.nai == id.nai)
104                 {
105                     identity = id;
106                     break;
107                 }
108
109                 /* If any service matches we add id card to the candidate list */
110                 if (has_srv)
111                 {
112                     foreach (string srv in id.services)
113                     {
114                         if (request.service == srv)
115                         {
116                             request.candidates.append (id);
117                             continue;
118                         }
119                     }
120                 }
121             }
122
123             /* If more than one candidate we dissasociate service from all ids */
124             if ((identity == null) && has_srv && request.candidates.length() > 1)
125             {
126                 foreach (IdCard id in request.candidates)
127                 {
128                     int i = 0;
129                     SList<string> services_list = null;
130                     bool has_service = false;
131
132                     foreach (string srv in id.services)
133                     {
134                         if (srv == request.service)
135                         {
136                             has_service = true;
137                             continue;
138                         }
139                         services_list.append (srv);
140                     }
141                     
142                     if (!has_service)
143                         continue;
144
145                     if (services_list.length () == 0)
146                     {
147                         id.services = {};
148                         continue;
149                     }
150
151                     string[] services = new string[services_list.length ()];
152                     foreach (string srv in services_list)
153                     {
154                         services[i] = srv;
155                         i++;
156                     }
157
158                     id.services = services;
159                 }
160             }
161
162             /* If there are no candidates we use the service matching rules */
163             if ((identity==null) && (request.candidates.length () == 0))
164             {
165                 foreach (IdCard id in model.get_card_list())
166                 {
167                     foreach (Rule rule in id.rules)
168                     {
169                         if (!match_service_pattern (request.service, rule.pattern))
170                             continue;
171
172                         request.candidates.append (id);
173
174                         if (rule.always_confirm == "true")
175                             confirm = true;
176                     }
177                 }
178             }
179             
180             if ((identity == null) && has_nai) {
181                 // create a temp identity
182                 string[] components = request.nai.split("@", 2);
183                 identity = new IdCard();
184                 identity.display_name = request.nai;
185                 identity.username = components[0];
186                 if (components.length > 1)
187                     identity.issuer = components[1];
188                 identity.password = request.password;
189                 identity.temporary = true;
190             }
191             if (identity == null) {
192                 if (request.candidates.length () != 1) {
193                     confirm = true;
194                 } else {
195                     identity = request.candidates.nth_data (0);                    
196                 }
197             }
198
199             if (confirm && (view != null))
200             {
201                 if (!explicitly_launched)
202                     show();
203                 view.queue_identity_request(request);
204                 return;
205             }
206         }
207         // Send back the identity (we can't directly run the
208         // callback because we may be being called from a 'yield')
209         Idle.add(
210             () => {
211                 if (view != null) {
212                     identity = view.check_add_password(identity, request, model);
213                 }
214                 request.return_identity (identity);
215 // The following occasionally causes the app to exit without sending the dbus
216 // reply, so for now we just don't exit
217 //                if (!explicitly_launched)
218 //                    Idle.add( () => { Gtk.main_quit(); return false; } );
219                 return false;
220             }
221         );
222         return;
223     }
224
225     private bool match_service_pattern (string service, string pattern)
226     {
227         var pspec = new PatternSpec (pattern);
228         return pspec.match_string (service);
229     }   
230     
231 #if IPC_MSRPC
232     private void init_ipc_server ()
233     {
234         // Errors will currently be sent via g_log - ie. to an
235         // obtrusive message box, on Windows
236         //
237         this.ipc_server = MoonshotServer.get_instance ();
238         MoonshotServer.start (this);
239     }
240 #elif IPC_DBUS_GLIB
241     private void init_ipc_server ()
242     {
243         try {
244             var conn = DBus.Bus.get (DBus.BusType.SESSION);
245             dynamic DBus.Object bus = conn.get_object ("org.freedesktop.DBus",
246                                                        "/org/freedesktop/DBus",
247                                                        "org.freedesktop.DBus");
248
249             // try to register service in session bus
250             uint reply = bus.request_name ("org.janet.Moonshot", (uint) 0);
251             if (reply == DBus.RequestNameReply.PRIMARY_OWNER)
252             {
253                 this.ipc_server = new MoonshotServer (this);
254                 conn.register_object ("/org/janet/moonshot", ipc_server);
255             } else {
256                 bool shown=false;
257                 GLib.Error e;
258                 DBus.Object manager_proxy = conn.get_object ("org.janet.Moonshot",
259                                                              "/org/janet/moonshot",
260                                                              "org.janet.Moonshot");
261                 if (manager_proxy != null)
262                     manager_proxy.call("ShowUi", out e, GLib.Type.INVALID, typeof(bool), out shown, GLib.Type.INVALID);
263
264                 if (!shown) {
265                     GLib.error ("Couldn't own name org.janet.Moonshot on dbus or show previously launched identity manager.");
266                 } else {
267                     stdout.printf("Showed previously launched identity manager.\n");
268                     GLib.Process.exit(0);
269                 }
270             }
271         }
272         catch (DBus.Error e)
273         {
274             stderr.printf ("%s\n", e.message);
275         }
276     }
277 #else
278     private void bus_acquired_cb (DBusConnection conn)
279     {
280         try {
281             conn.register_object ("/org/janet/moonshot", ipc_server);
282         }
283         catch (Error e)
284         {
285             stderr.printf ("%s\n", e.message);
286         }
287     }
288
289     private void init_ipc_server ()
290     {
291         this.ipc_server = new MoonshotServer (this);
292         GLib.Bus.own_name (GLib.BusType.SESSION,
293                            "org.janet.Moonshot",
294                            GLib.BusNameOwnerFlags.NONE,
295                            bus_acquired_cb,
296                            (conn, name) => {},
297                            (conn, name) => {
298                                bool shown=false;
299                                try {
300                                    IIdentityManager manager = Bus.get_proxy_sync (BusType.SESSION, name, "/org/janet/moonshot");
301                                    shown = manager.show_ui();
302                                } catch (IOError e) {
303                                }
304                                if (!shown) {
305                                    GLib.error ("Couldn't own name %s on dbus or show previously launched identity manager.", name);
306                                } else {
307                                    stdout.printf("Showed previously launched identity manager.\n");
308                                    GLib.Process.exit(0);
309                                }
310                            });
311     }
312 #endif
313 }
314
315 static bool explicitly_launched = true;
316 static bool use_flat_file_store = false;
317 const GLib.OptionEntry[] options = {
318     {"dbus-launched",0,GLib.OptionFlags.REVERSE,GLib.OptionArg.NONE,
319      ref explicitly_launched,"launch for dbus rpc use",null},
320     {"flat-file-store",0,0,GLib.OptionArg.NONE,
321      ref use_flat_file_store,"force use of flat file identity store (used by default only for headless operation)",null},
322     {null}
323 };
324
325
326 public static int main(string[] args){
327 #if IPC_MSRPC
328         bool headless = false;
329 #else
330         bool headless = GLib.Environment.get_variable("DISPLAY") == null;
331 #endif
332
333         if (headless) {
334             try {
335                 var opt_context = new OptionContext(null);
336                 opt_context.set_help_enabled (true);
337                 opt_context.add_main_entries (options, null);
338                 opt_context.parse(ref args);
339             } catch (OptionError e) {
340                 stdout.printf(_("error: %s\n"),e.message);
341                 stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
342                 return -1;
343             }
344             explicitly_launched = false;
345         } else {
346             try {
347                 if (!Gtk.init_with_args(ref args, _(""), options, null)) {
348                     stdout.printf(_("unable to initialize window\n"));
349                     return -1;
350                 }
351             } catch (GLib.Error e) {
352                 stdout.printf(_("error: %s\n"),e.message);
353                 stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
354                 return -1;
355             }
356             gtk_available = true;
357         }
358
359 #if OS_WIN32
360         // Force specific theme settings on Windows without requiring a gtkrc file
361         Gtk.Settings settings = Gtk.Settings.get_default ();
362         settings.set_string_property ("gtk-theme-name", "ms-windows", "moonshot");
363         settings.set_long_property ("gtk-menu-images", 0, "moonshot");
364 #endif
365
366         Intl.bindtextdomain (Config.GETTEXT_PACKAGE, Config.LOCALEDIR);
367         Intl.bind_textdomain_codeset (Config.GETTEXT_PACKAGE, "UTF-8");
368         Intl.textdomain (Config.GETTEXT_PACKAGE);
369        
370            
371         var app = new IdentityManagerApp(headless, use_flat_file_store);
372         app.explicitly_launched = explicitly_launched;
373         
374         if (app.explicitly_launched) {
375             app.show();
376         }
377
378         if (headless) {
379 #if !IPC_MSRPC
380             MainLoop loop = new MainLoop();
381             loop.run();
382 #endif
383         } else {
384             Gtk.main();
385         }
386
387         return 0;
388     }
389