Minor formatting changes
[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
76         #if GNOME_KEYRING
77             bool keyring_available = (!use_flat_file_store) && GnomeKeyring.is_available();
78         #else
79             bool keyring_available = false;
80         #endif
81
82         IIdentityCardStore.StoreType store_type;
83         if (headless || use_flat_file_store || !keyring_available)
84             store_type = IIdentityCardStore.StoreType.FLAT_FILE;
85         else
86             store_type = IIdentityCardStore.StoreType.KEYRING;
87
88         model = new IdentityManagerModel(this, store_type);
89         /* if headless, but we have nothing in the flat file store
90          * and keyring is available, switch to keyring */
91         if (headless && keyring_available && !use_flat_file_store && !model.HasNonTrivialIdentities())
92             model.set_store_type(IIdentityCardStore.StoreType.KEYRING);
93
94         if (!headless)
95             view = new IdentityManagerView(this);
96         LinkedList<IdCard> card_list = model.get_card_list();
97         if (card_list.size > 0)
98             this.default_id_card = card_list.last();
99
100         init_ipc_server();
101
102         #if OS_MACOS
103         osxApp = OSXApplication.get_instance();
104         // The 'correct' way of connecting won't work in Mac OS with Vala 0.12; e.g.
105         //     osxApp.ns_application_open_file.connect(install_from_file);
106         // so we have to use this old way
107         Signal.connect(osxApp, "NSApplicationOpenFile", (GLib.Callback)(on_osx_open_files), this);
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         // Errors will currently be sent via g_log - ie. to an
265         // obtrusive message box, on Windows
266         //
267         this.ipc_server = MoonshotServer.get_instance();
268         MoonshotServer.start(this);
269     }
270     #elif IPC_DBUS_GLIB
271     private void init_ipc_server() {
272         try {
273             var conn = DBus.Bus.get(DBus.BusType.SESSION);
274             dynamic DBus.Object bus = conn.get_object("org.freedesktop.DBus",
275                                                       "/org/freedesktop/DBus",
276                                                       "org.freedesktop.DBus");
277
278             // try to register service in session bus
279             uint reply = bus.request_name("org.janet.Moonshot", (uint) 0);
280             if (reply == DBus.RequestNameReply.PRIMARY_OWNER)
281             {
282                 this.ipc_server = new MoonshotServer(this);
283                 conn.register_object("/org/janet/moonshot", ipc_server);
284             } else {
285                 bool shown = false;
286                 GLib.Error e;
287                 DBus.Object manager_proxy = conn.get_object("org.janet.Moonshot",
288                                                             "/org/janet/moonshot",
289                                                             "org.janet.Moonshot");
290                 if (manager_proxy != null)
291                     manager_proxy.call("ShowUi", out e, GLib.Type.INVALID, typeof(bool), out shown, GLib.Type.INVALID);
292
293                 if (!shown) {
294                     GLib.error("Couldn't own name org.janet.Moonshot on dbus or show previously launched identity manager.");
295                 } else {
296                     stdout.printf("Showed previously launched identity manager.\n");
297                     GLib.Process.exit(0);
298                 }
299             }
300         }
301         catch (DBus.Error e)
302         {
303             stderr.printf("%s\n", e.message);
304         }
305     }
306     #else
307     private void bus_acquired_cb(DBusConnection conn) {
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         }
315     }
316
317     private void init_ipc_server() {
318         this.ipc_server = new MoonshotServer(this);
319         GLib.Bus.own_name(GLib.BusType.SESSION,
320                           "org.janet.Moonshot",
321                           GLib.BusNameOwnerFlags.NONE,
322                           bus_acquired_cb,
323                           (conn, name) => {},
324                           (conn, name) => {
325                               bool shown = false;
326                               try {
327                                   IIdentityManager manager = Bus.get_proxy_sync(BusType.SESSION, name, "/org/janet/moonshot");
328                                   shown = manager.show_ui();
329                               } catch (IOError e) {
330                               }
331                               if (!shown) {
332                                   GLib.error("Couldn't own name %s on dbus or show previously launched identity manager.", name);
333                               } else {
334                                   stdout.printf("Showed previously launched identity manager.\n");
335                                   GLib.Process.exit(0);
336                               }
337                           });
338     }
339     #endif
340 }
341
342 static bool explicitly_launched = true;
343 static bool use_flat_file_store = false;
344 const GLib.OptionEntry[] options = {
345     {"dbus-launched", 0, GLib.OptionFlags.REVERSE, GLib.OptionArg.NONE,
346      ref explicitly_launched, "launch for dbus rpc use", null},
347     {"flat-file-store", 0, 0, GLib.OptionArg.NONE,
348      ref use_flat_file_store, "force use of flat file identity store (used by default only for headless operation)", null},
349     {null}
350 };
351
352
353 public static int main(string[] args) {
354     #if IPC_MSRPC
355         bool headless = false;
356     #else
357         bool headless = (GLib.Environment.get_variable("DISPLAY") == null);
358     #endif
359
360     if (headless) {
361         try {
362             var opt_context = new OptionContext(null);
363             opt_context.set_help_enabled(true);
364             opt_context.add_main_entries(options, null);
365             opt_context.parse(ref args);
366         } catch (OptionError e) {
367             stdout.printf(_("error: %s\n"),e.message);
368             stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
369             return -1;
370         }
371         explicitly_launched = false;
372     } else {
373         try {
374             if (!Gtk.init_with_args(ref args, _(""), options, null)) {
375                 stdout.printf(_("unable to initialize window\n"));
376                 return -1;
377             }
378         } catch (GLib.Error e) {
379             stdout.printf(_("error: %s\n"),e.message);
380             stdout.printf(_("Run '%s --help' to see a full list of available options\n"), args[0]);
381             return -1;
382         }
383         gtk_available = true;
384     }
385
386     #if OS_WIN32
387     // Force specific theme settings on Windows without requiring a gtkrc file
388     Gtk.Settings settings = Gtk.Settings.get_default();
389     settings.set_string_property("gtk-theme-name", "ms-windows", "moonshot");
390     settings.set_long_property("gtk-menu-images", 0, "moonshot");
391     #endif
392
393     Intl.bindtextdomain(Config.GETTEXT_PACKAGE, Config.LOCALEDIR);
394     Intl.bind_textdomain_codeset(Config.GETTEXT_PACKAGE, "UTF-8");
395     Intl.textdomain(Config.GETTEXT_PACKAGE);
396        
397     var app = new IdentityManagerApp(headless, use_flat_file_store);
398     app.explicitly_launched = explicitly_launched;
399         
400     if (app.explicitly_launched) {
401         app.show();
402     }
403
404     if (headless) {
405         #if !IPC_MSRPC
406         MainLoop loop = new MainLoop();
407         loop.run();
408         #endif
409     }
410     else {
411         Gtk.main();
412     }
413
414     return 0;
415 }
416