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