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