]> rtime.felk.cvut.cz Git - sojka/lightdm.git/blob - src/lightdm.c
Re-enable SIGPIPE for children so they have default behaviour
[sojka/lightdm.git] / src / lightdm.c
1 /*
2  * Copyright (C) 2010-2011 Robert Ancell.
3  * Author: Robert Ancell <robert.ancell@canonical.com>
4  *
5  * This program is free software: you can redistribute it and/or modify it under
6  * the terms of the GNU General Public License as published by the Free Software
7  * Foundation, either version 3 of the License, or (at your option) any later
8  * version. See http://www.gnu.org/copyleft/gpl.html the full text of the
9  * license.
10  */
11
12 #include <config.h>
13
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <sys/stat.h>
17 #include <glib.h>
18 #include <glib/gi18n.h>
19 #include <unistd.h>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <errno.h>
23
24 #include "configuration.h"
25 #include "display-manager.h"
26 #include "xdmcp-server.h"
27 #include "vnc-server.h"
28 #include "seat-xdmcp-session.h"
29 #include "seat-xvnc.h"
30 #include "x-server.h"
31 #include "process.h"
32 #include "session-child.h"
33 #include "shared-data-manager.h"
34 #include "user-list.h"
35 #include "login1.h"
36 #include "log-file.h"
37
38 static gchar *config_path = NULL;
39 static GMainLoop *loop = NULL;
40 static GTimer *log_timer;
41 static int log_fd = -1;
42 static gboolean debug = FALSE;
43
44 static DisplayManager *display_manager = NULL;
45 static XDMCPServer *xdmcp_server = NULL;
46 static VNCServer *vnc_server = NULL;
47 static guint bus_id = 0;
48 static GDBusConnection *bus = NULL;
49 static guint reg_id = 0;
50 static GDBusNodeInfo *seat_info;
51 static GHashTable *seat_bus_entries = NULL;
52 static guint seat_index = 0;
53 static GDBusNodeInfo *session_info;
54 static GHashTable *session_bus_entries = NULL;
55 static guint session_index = 0;
56 static gint exit_code = EXIT_SUCCESS;
57
58 typedef struct
59 {
60     gchar *path;
61     guint bus_id;
62 } SeatBusEntry;
63 typedef struct
64 {
65     gchar *path;
66     gchar *seat_path;
67     guint bus_id;
68 } SessionBusEntry;
69
70 #define LIGHTDM_BUS_NAME "org.freedesktop.DisplayManager"
71
72 static gboolean update_login1_seat (Login1Seat *login1_seat);
73
74 static void
75 log_cb (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer data)
76 {
77     const gchar *prefix;
78     gchar *text;
79
80     switch (log_level & G_LOG_LEVEL_MASK)
81     {
82     case G_LOG_LEVEL_ERROR:
83         prefix = "ERROR:";
84         break;
85     case G_LOG_LEVEL_CRITICAL:
86         prefix = "CRITICAL:";
87         break;
88     case G_LOG_LEVEL_WARNING:
89         prefix = "WARNING:";
90         break;
91     case G_LOG_LEVEL_MESSAGE:
92         prefix = "MESSAGE:";
93         break;
94     case G_LOG_LEVEL_INFO:
95         prefix = "INFO:";
96         break;
97     case G_LOG_LEVEL_DEBUG:
98         prefix = "DEBUG:";
99         break;
100     default:
101         prefix = "LOG:";
102         break;
103     }
104
105     text = g_strdup_printf ("[%+.2fs] %s %s\n", g_timer_elapsed (log_timer, NULL), prefix, message);
106
107     /* Log everything to a file */
108     if (log_fd >= 0)
109     {
110         ssize_t n_written;
111         n_written = write (log_fd, text, strlen (text));
112         if (n_written < 0)
113             ; /* Check result so compiler doesn't warn about it */
114     }
115
116     /* Log to stderr if requested */
117     if (debug)
118         g_printerr ("%s", text);
119     else
120         g_log_default_handler (log_domain, log_level, message, data);
121
122     g_free (text);
123 }
124
125 static void
126 log_init (void)
127 {
128     gchar *log_dir, *path;
129     gboolean backup_logs;
130
131     log_timer = g_timer_new ();
132
133     /* Log to a file */
134     log_dir = config_get_string (config_get_instance (), "LightDM", "log-directory");
135     path = g_build_filename (log_dir, "lightdm.log", NULL);
136     g_free (log_dir);
137
138     backup_logs = config_get_boolean (config_get_instance (), "LightDM", "backup-logs");
139     log_fd = log_file_open (path, backup_logs ? LOG_MODE_BACKUP_AND_TRUNCATE : LOG_MODE_APPEND);
140     fcntl (log_fd, F_SETFD, FD_CLOEXEC);
141     g_log_set_default_handler (log_cb, NULL);
142
143     g_debug ("Logging to %s", path);
144     g_free (path);
145 }
146
147 static GList*
148 get_config_sections (const gchar *seat_name)
149 {
150     gchar **groups, **i;
151     GList *config_sections = NULL;
152
153     /* Load seat defaults first */
154     config_sections = g_list_append (config_sections, g_strdup ("Seat:*"));
155
156     groups = config_get_groups (config_get_instance ());
157     for (i = groups; *i; i++)
158     {
159         if (g_str_has_prefix (*i, "Seat:") && strcmp (*i, "Seat:*") != 0)
160         {
161             const gchar *seat_name_glob = *i + strlen ("Seat:");
162             if (g_pattern_match_simple (seat_name_glob, seat_name ? seat_name : ""))
163                 config_sections = g_list_append (config_sections, g_strdup (*i));
164         }
165     }
166     g_strfreev (groups);
167
168     return config_sections;
169 }
170
171 static void
172 set_seat_properties (Seat *seat, const gchar *seat_name)
173 {
174     GList *sections, *link;
175     gchar **keys;
176     gint i;
177
178     sections = get_config_sections (seat_name);
179     for (link = sections; link; link = link->next)
180     {
181         const gchar *section = link->data;
182         keys = config_get_keys (config_get_instance (), section);
183
184         l_debug (seat, "Loading properties from config section %s", section);
185         for (i = 0; keys && keys[i]; i++)
186         {
187             gchar *value = config_get_string (config_get_instance (), section, keys[i]);
188             seat_set_property (seat, keys[i], value);
189             g_free (value);
190         }
191         g_strfreev (keys);
192     }
193     g_list_free_full (sections, g_free);
194 }
195
196 static void
197 signal_cb (Process *process, int signum)
198 {
199     switch (signum)
200     {
201     case SIGINT:
202     case SIGTERM:
203         g_debug ("Caught %s signal, shutting down", g_strsignal (signum));
204         display_manager_stop (display_manager);
205         // FIXME: Stop XDMCP server
206         break;
207     case SIGUSR1:
208     case SIGUSR2:
209     case SIGHUP:
210         break;
211     }
212 }
213
214 static void
215 display_manager_stopped_cb (DisplayManager *display_manager)
216 {
217     g_debug ("Stopping daemon");
218     g_main_loop_quit (loop);
219 }
220
221 static Seat *
222 create_seat (const gchar *module_name, const gchar *name)
223 {
224     if (strcmp (module_name, "xlocal") == 0) {
225         g_warning ("Seat type 'xlocal' is deprecated, use 'type=local' instead");
226         return seat_new ("local", name);
227     }
228     else
229         return seat_new (module_name, name);
230 }
231
232 static void
233 display_manager_seat_removed_cb (DisplayManager *display_manager, Seat *seat)
234 {
235     gchar **types;
236     gchar **iter;
237     Seat *next_seat = NULL;
238     GString *next_types;
239
240     /* If we have fallback types registered for the seat, let's try them
241        before giving up. */
242     types = seat_get_string_list_property (seat, "type");
243     next_types = g_string_new ("");
244     for (iter = types; iter && *iter; iter++)
245     {
246         if (iter == types)
247             continue; // skip first one, that is our current seat type
248
249         if (!next_seat)
250         {
251             next_seat = create_seat (*iter, seat_get_name (seat));
252             g_string_assign (next_types, *iter);
253         }
254         else
255         {
256             // Build up list of types to try next time
257             g_string_append_c (next_types, ';');
258             g_string_append (next_types, *iter);
259         }
260     }
261     g_strfreev (types);
262
263     if (next_seat)
264     {
265         set_seat_properties (next_seat, seat_get_name (seat));
266
267         // We set this manually on default seat.  Let's port it over if needed.
268         if (seat_get_boolean_property (seat, "exit-on-failure"))
269             seat_set_property (next_seat, "exit-on-failure", "true");
270
271         seat_set_property (next_seat, "type", next_types->str);
272
273         display_manager_add_seat (display_manager, next_seat);
274         g_object_unref (next_seat);
275     }
276     else if (seat_get_boolean_property (seat, "exit-on-failure"))
277     {
278         g_debug ("Required seat has stopped");
279         exit_code = EXIT_FAILURE;
280         display_manager_stop (display_manager);
281     }
282
283     g_string_free (next_types, TRUE);
284 }
285
286 static GVariant *
287 get_seat_list (void)
288 {
289     GVariantBuilder builder;
290     GHashTableIter iter;
291     gpointer value;
292
293     g_variant_builder_init (&builder, G_VARIANT_TYPE ("ao"));
294     g_hash_table_iter_init (&iter, seat_bus_entries);
295     while (g_hash_table_iter_next (&iter, NULL, &value))
296     {
297         SeatBusEntry *entry = value;
298         g_variant_builder_add_value (&builder, g_variant_new_object_path (entry->path));
299     }
300
301     return g_variant_builder_end (&builder);
302 }
303
304 static GVariant *
305 get_session_list (const gchar *seat_path)
306 {
307     GVariantBuilder builder;
308     GHashTableIter iter;
309     gpointer value;
310
311     g_variant_builder_init (&builder, G_VARIANT_TYPE ("ao"));
312
313     g_hash_table_iter_init (&iter, session_bus_entries);
314     while (g_hash_table_iter_next (&iter, NULL, &value))
315     {
316         SessionBusEntry *entry = value;
317         if (seat_path == NULL || strcmp (entry->seat_path, seat_path) == 0)
318             g_variant_builder_add_value (&builder, g_variant_new_object_path (entry->path));
319     }
320
321     return g_variant_builder_end (&builder);
322 }
323
324 static GVariant *
325 handle_display_manager_get_property (GDBusConnection       *connection,
326                                      const gchar           *sender,
327                                      const gchar           *object_path,
328                                      const gchar           *interface_name,
329                                      const gchar           *property_name,
330                                      GError               **error,
331                                      gpointer               user_data)
332 {
333     if (g_strcmp0 (property_name, "Seats") == 0)
334         return get_seat_list ();
335     else if (g_strcmp0 (property_name, "Sessions") == 0)
336         return get_session_list (NULL);
337
338     return NULL;
339 }
340
341 static void
342 handle_display_manager_call (GDBusConnection       *connection,
343                              const gchar           *sender,
344                              const gchar           *object_path,
345                              const gchar           *interface_name,
346                              const gchar           *method_name,
347                              GVariant              *parameters,
348                              GDBusMethodInvocation *invocation,
349                              gpointer               user_data)
350 {
351     if (g_strcmp0 (method_name, "AddSeat") == 0)
352         g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "AddSeat is deprecated");
353     else if (g_strcmp0 (method_name, "AddLocalXSeat") == 0)
354     {
355         gint display_number;
356         Seat *seat;
357
358         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(i)")))
359         {
360             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Invalid arguments");
361             return;
362         }
363
364         g_variant_get (parameters, "(i)", &display_number);
365
366         g_debug ("Adding local X seat :%d", display_number);
367
368         seat = create_seat ("xremote", "xremote0"); // FIXME: What to use for a name?
369         if (seat)
370         {
371             gchar *display_number_string;
372
373             set_seat_properties (seat, NULL);
374             display_number_string = g_strdup_printf ("%d", display_number);
375             seat_set_property (seat, "xserver-display-number", display_number_string);
376             g_free (display_number_string);
377         }
378
379         if (!seat)
380         {
381             // FIXME: Need to make proper error
382             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Unable to create local X seat");
383             return;
384         }
385
386         if (display_manager_add_seat (display_manager, seat))
387         {
388             SeatBusEntry *entry;
389
390             entry = g_hash_table_lookup (seat_bus_entries, seat);
391             g_dbus_method_invocation_return_value (invocation, g_variant_new ("(o)", entry->path));
392         }
393         else// FIXME: Need to make proper error
394             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Failed to start seat");
395         g_object_unref (seat);
396     }
397     else
398         g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Unknown method");
399 }
400
401 static GVariant *
402 handle_seat_get_property (GDBusConnection       *connection,
403                           const gchar           *sender,
404                           const gchar           *object_path,
405                           const gchar           *interface_name,
406                           const gchar           *property_name,
407                           GError               **error,
408                           gpointer               user_data)
409 {
410     Seat *seat = user_data;
411
412     if (g_strcmp0 (property_name, "CanSwitch") == 0)
413         return g_variant_new_boolean (seat_get_can_switch (seat));
414     if (g_strcmp0 (property_name, "HasGuestAccount") == 0)
415         return g_variant_new_boolean (seat_get_allow_guest (seat));
416     else if (g_strcmp0 (property_name, "Sessions") == 0)
417     {
418         SeatBusEntry *entry;
419
420         entry = g_hash_table_lookup (seat_bus_entries, seat);
421         return get_session_list (entry->path);
422     }
423
424     return NULL;
425 }
426
427 static void
428 handle_seat_call (GDBusConnection       *connection,
429                   const gchar           *sender,
430                   const gchar           *object_path,
431                   const gchar           *interface_name,
432                   const gchar           *method_name,
433                   GVariant              *parameters,
434                   GDBusMethodInvocation *invocation,
435                   gpointer               user_data)
436 {
437     Seat *seat = user_data;
438
439     if (g_strcmp0 (method_name, "SwitchToGreeter") == 0)
440     {
441         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("()")))
442             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Invalid arguments");
443
444         if (seat_switch_to_greeter (seat))
445             g_dbus_method_invocation_return_value (invocation, NULL);
446         else// FIXME: Need to make proper error
447             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Failed to switch to greeter");
448     }
449     else if (g_strcmp0 (method_name, "SwitchToUser") == 0)
450     {
451         const gchar *username, *session_name;
452
453         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(ss)")))
454             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Invalid arguments");
455
456         g_variant_get (parameters, "(&s&s)", &username, &session_name);
457         if (strcmp (session_name, "") == 0)
458             session_name = NULL;
459
460         if (seat_switch_to_user (seat, username, session_name))
461             g_dbus_method_invocation_return_value (invocation, NULL);
462         else// FIXME: Need to make proper error
463             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Failed to switch to user");
464     }
465     else if (g_strcmp0 (method_name, "SwitchToGuest") == 0)
466     {
467         const gchar *session_name;
468
469         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(s)")))
470             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Invalid arguments");
471
472         g_variant_get (parameters, "(&s)", &session_name);
473         if (strcmp (session_name, "") == 0)
474             session_name = NULL;
475
476         if (seat_switch_to_guest (seat, session_name))
477             g_dbus_method_invocation_return_value (invocation, NULL);
478         else// FIXME: Need to make proper error
479             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Failed to switch to guest");
480     }
481     else if (g_strcmp0 (method_name, "Lock") == 0)
482     {
483         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("()")))
484             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Invalid arguments");
485
486         /* FIXME: Should only allow locks if have a session on this seat */
487         if (seat_lock (seat, NULL))
488             g_dbus_method_invocation_return_value (invocation, NULL);
489         else// FIXME: Need to make proper error
490             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Failed to lock seat");
491     }
492     else
493         g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Unknown method");
494 }
495
496 static Seat *
497 get_seat_for_session (Session *session)
498 {
499     GList *seat_link;
500
501     for (seat_link = display_manager_get_seats (display_manager); seat_link; seat_link = seat_link->next)
502     {
503         Seat *seat = seat_link->data;
504         GList *session_link;
505
506         for (session_link = seat_get_sessions (seat); session_link; session_link = session_link->next)
507         {
508             Session *s = session_link->data;
509
510             if (s == session)
511                 return seat;
512         }
513     }
514
515     return NULL;
516 }
517
518 static GVariant *
519 handle_session_get_property (GDBusConnection       *connection,
520                              const gchar           *sender,
521                              const gchar           *object_path,
522                              const gchar           *interface_name,
523                              const gchar           *property_name,
524                              GError               **error,
525                              gpointer               user_data)
526 {
527     Session *session = user_data;
528     SessionBusEntry *entry;
529
530     entry = g_hash_table_lookup (session_bus_entries, session);
531     if (g_strcmp0 (property_name, "Seat") == 0)
532         return g_variant_new_object_path (entry ? entry->seat_path : "");
533     else if (g_strcmp0 (property_name, "UserName") == 0)
534         return g_variant_new_string (session_get_username (session));
535
536     return NULL;
537 }
538
539 static void
540 handle_session_call (GDBusConnection       *connection,
541                      const gchar           *sender,
542                      const gchar           *object_path,
543                      const gchar           *interface_name,
544                      const gchar           *method_name,
545                      GVariant              *parameters,
546                      GDBusMethodInvocation *invocation,
547                      gpointer               user_data)
548 {
549     Session *session = user_data;
550
551     if (g_strcmp0 (method_name, "Lock") == 0)
552     {
553         Seat *seat;
554
555         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("()")))
556             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_INVALID_ARGS, "Invalid arguments");
557
558         seat = get_seat_for_session (session);
559         /* FIXME: Should only allow locks if have a session on this seat */
560         seat_lock (seat, session_get_username (session));
561         g_dbus_method_invocation_return_value (invocation, NULL);
562     }
563     else
564         g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD, "Unknown method");
565 }
566
567 static SeatBusEntry *
568 seat_bus_entry_new (const gchar *path)
569 {
570     SeatBusEntry *entry;
571
572     entry = g_malloc0 (sizeof (SeatBusEntry));
573     entry->path = g_strdup (path);
574
575     return entry;
576 }
577
578 static SessionBusEntry *
579 session_bus_entry_new (const gchar *path, const gchar *seat_path)
580 {
581     SessionBusEntry *entry;
582
583     entry = g_malloc0 (sizeof (SessionBusEntry));
584     entry->path = g_strdup (path);
585     entry->seat_path = g_strdup (seat_path);
586
587     return entry;
588 }
589
590 static void
591 emit_object_value_changed (GDBusConnection *bus, const gchar *path, const gchar *interface_name, const gchar *property_name, GVariant *property_value)
592 {
593     GVariantBuilder builder;
594     GError *error = NULL;
595
596     g_variant_builder_init (&builder, G_VARIANT_TYPE_ARRAY);
597     g_variant_builder_add (&builder, "{sv}", property_name, property_value);
598
599     if (!g_dbus_connection_emit_signal (bus,
600                                         NULL,
601                                         path,
602                                         "org.freedesktop.DBus.Properties",
603                                         "PropertiesChanged",
604                                         g_variant_new ("(sa{sv}as)", interface_name, &builder, NULL),
605                                         &error))
606         g_warning ("Failed to emit PropertiesChanged signal: %s", error->message);
607     g_clear_error (&error);
608 }
609
610 static void
611 emit_object_signal (GDBusConnection *bus, const gchar *path, const gchar *signal_name, const gchar *object_path)
612 {
613     GError *error = NULL;
614
615     if (!g_dbus_connection_emit_signal (bus,
616                                         NULL,
617                                         path,
618                                         "org.freedesktop.DisplayManager",
619                                         signal_name,
620                                         g_variant_new ("(o)", object_path),
621                                         &error))
622         g_warning ("Failed to emit %s signal on %s: %s", signal_name, path, error->message);
623     g_clear_error (&error);
624 }
625
626 static void
627 seat_bus_entry_free (gpointer data)
628 {
629     SeatBusEntry *entry = data;
630
631     g_free (entry->path);
632     g_free (entry);
633 }
634
635 static void
636 session_bus_entry_free (gpointer data)
637 {
638     SessionBusEntry *entry = data;
639
640     g_free (entry->path);
641     g_free (entry->seat_path);
642     g_free (entry);
643 }
644
645 static void
646 running_user_session_cb (Seat *seat, Session *session)
647 {
648     static const GDBusInterfaceVTable session_vtable =
649     {
650         handle_session_call,
651         handle_session_get_property
652     };
653     SeatBusEntry *seat_entry;
654     SessionBusEntry *session_entry;
655     gchar *path;
656     GError *error = NULL;
657
658     /* Set environment variables when session runs */
659     seat_entry = g_hash_table_lookup (seat_bus_entries, seat);
660     session_set_env (session, "XDG_SEAT_PATH", seat_entry->path);
661     path = g_strdup_printf ("/org/freedesktop/DisplayManager/Session%d", session_index);
662     session_index++;
663     session_set_env (session, "XDG_SESSION_PATH", path);
664     g_object_set_data_full (G_OBJECT (session), "XDG_SESSION_PATH", path, g_free);
665
666     session_entry = session_bus_entry_new (g_object_get_data (G_OBJECT (session), "XDG_SESSION_PATH"), seat_entry ? seat_entry->path : NULL);
667     g_hash_table_insert (session_bus_entries, g_object_ref (session), session_entry);
668
669     g_debug ("Registering session with bus path %s", session_entry->path);
670
671     session_entry->bus_id = g_dbus_connection_register_object (bus,
672                                                                session_entry->path,
673                                                                session_info->interfaces[0],
674                                                                &session_vtable,
675                                                                g_object_ref (session), g_object_unref,
676                                                                &error);
677     if (session_entry->bus_id == 0)
678         g_warning ("Failed to register user session: %s", error->message);
679     g_clear_error (&error);
680
681     emit_object_value_changed (bus, "/org/freedesktop/DisplayManager", "org.freedesktop.DisplayManager", "Sessions", get_session_list (NULL));
682     emit_object_signal (bus, "/org/freedesktop/DisplayManager", "SessionAdded", session_entry->path);
683
684     emit_object_value_changed (bus, seat_entry->path, "org.freedesktop.DisplayManager.Seat", "Sessions", get_session_list (session_entry->seat_path));
685     emit_object_signal (bus, seat_entry->path, "SessionAdded", session_entry->path);
686 }
687
688 static void
689 session_removed_cb (Seat *seat, Session *session)
690 {
691     SessionBusEntry *entry;
692     gchar *seat_path = NULL;
693
694     g_signal_handlers_disconnect_matched (session, G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, seat);
695
696     entry = g_hash_table_lookup (session_bus_entries, session);
697     if (entry)
698     {
699         g_dbus_connection_unregister_object (bus, entry->bus_id);
700         emit_object_signal (bus, "/org/freedesktop/DisplayManager", "SessionRemoved", entry->path);
701         emit_object_signal (bus, entry->seat_path, "SessionRemoved", entry->path);
702         seat_path = g_strdup (entry->seat_path);
703     }
704
705     g_hash_table_remove (session_bus_entries, session);
706
707     if (seat_path)
708     {
709         emit_object_value_changed (bus, "/org/freedesktop/DisplayManager", "org.freedesktop.DisplayManager", "Sessions", get_session_list (NULL));
710         emit_object_value_changed (bus, seat_path, "org.freedesktop.DisplayManager.Seat", "Sessions", get_session_list (seat_path));
711         g_free (seat_path);
712     }
713 }
714
715 static void
716 seat_added_cb (DisplayManager *display_manager, Seat *seat)
717 {
718     static const GDBusInterfaceVTable seat_vtable =
719     {
720         handle_seat_call,
721         handle_seat_get_property
722     };
723     gchar *path;
724     SeatBusEntry *entry;
725     GError *error = NULL;
726
727     path = g_strdup_printf ("/org/freedesktop/DisplayManager/Seat%d", seat_index);
728     seat_index++;
729
730     entry = seat_bus_entry_new (path);
731     g_free (path);
732     g_hash_table_insert (seat_bus_entries, g_object_ref (seat), entry);
733
734     g_debug ("Registering seat with bus path %s", entry->path);
735
736     entry->bus_id = g_dbus_connection_register_object (bus,
737                                                        entry->path,
738                                                        seat_info->interfaces[0],
739                                                        &seat_vtable,
740                                                        g_object_ref (seat), g_object_unref,
741                                                        &error);
742     if (entry->bus_id == 0)
743         g_warning ("Failed to register seat: %s", error->message);
744     g_clear_error (&error);
745
746     emit_object_value_changed (bus, "/org/freedesktop/DisplayManager", "org.freedesktop.DisplayManager", "Seats", get_seat_list ());
747     emit_object_signal (bus, "/org/freedesktop/DisplayManager", "SeatAdded", entry->path);
748
749     g_signal_connect (seat, SEAT_SIGNAL_RUNNING_USER_SESSION, G_CALLBACK (running_user_session_cb), NULL);
750     g_signal_connect (seat, SEAT_SIGNAL_SESSION_REMOVED, G_CALLBACK (session_removed_cb), NULL);
751 }
752
753 static void
754 seat_removed_cb (DisplayManager *display_manager, Seat *seat)
755 {
756     SeatBusEntry *entry;
757
758     entry = g_hash_table_lookup (seat_bus_entries, seat);
759     if (entry)
760     {
761         g_dbus_connection_unregister_object (bus, entry->bus_id);
762         emit_object_signal (bus, "/org/freedesktop/DisplayManager", "SeatRemoved", entry->path);
763     }
764
765     g_hash_table_remove (seat_bus_entries, seat);
766   
767     emit_object_value_changed (bus, "/org/freedesktop/DisplayManager", "org.freedesktop.DisplayManager", "Seats", get_seat_list ());
768 }
769
770 static gboolean
771 xdmcp_session_cb (XDMCPServer *server, XDMCPSession *session)
772 {
773     SeatXDMCPSession *seat;
774     gboolean result;
775
776     seat = seat_xdmcp_session_new (session);
777     set_seat_properties (SEAT (seat), NULL);
778     result = display_manager_add_seat (display_manager, SEAT (seat));
779     g_object_unref (seat);
780
781     return result;
782 }
783
784 static void
785 vnc_connection_cb (VNCServer *server, GSocket *connection)
786 {
787     SeatXVNC *seat;
788
789     seat = seat_xvnc_new (connection);
790     set_seat_properties (SEAT (seat), NULL);
791     display_manager_add_seat (display_manager, SEAT (seat));
792     g_object_unref (seat);
793 }
794
795 static void
796 bus_acquired_cb (GDBusConnection *connection,
797                  const gchar     *name,
798                  gpointer         user_data)
799 {
800     const gchar *display_manager_interface =
801         "<node>"
802         "  <interface name='org.freedesktop.DisplayManager'>"
803         "    <property name='Seats' type='ao' access='read'/>"
804         "    <property name='Sessions' type='ao' access='read'/>"
805         "    <method name='AddSeat'>"
806         "      <arg name='type' direction='in' type='s'/>"
807         "      <arg name='properties' direction='in' type='a(ss)'/>"
808         "      <arg name='seat' direction='out' type='o'/>"
809         "    </method>"
810         "    <method name='AddLocalXSeat'>"
811         "      <arg name='display-number' direction='in' type='i'/>"
812         "      <arg name='seat' direction='out' type='o'/>"
813         "    </method>"
814         "    <signal name='SeatAdded'>"
815         "      <arg name='seat' type='o'/>"
816         "    </signal>"
817         "    <signal name='SeatRemoved'>"
818         "      <arg name='seat' type='o'/>"
819         "    </signal>"
820         "    <signal name='SessionAdded'>"
821         "      <arg name='session' type='o'/>"
822         "    </signal>"
823         "    <signal name='SessionRemoved'>"
824         "      <arg name='session' type='o'/>"
825         "    </signal>"
826         "  </interface>"
827         "</node>";
828     static const GDBusInterfaceVTable display_manager_vtable =
829     {
830         handle_display_manager_call,
831         handle_display_manager_get_property
832     };
833     const gchar *seat_interface =
834         "<node>"
835         "  <interface name='org.freedesktop.DisplayManager.Seat'>"
836         "    <property name='CanSwitch' type='b' access='read'/>"
837         "    <property name='HasGuestAccount' type='b' access='read'/>"
838         "    <property name='Sessions' type='ao' access='read'/>"
839         "    <method name='SwitchToGreeter'/>"
840         "    <method name='SwitchToUser'>"
841         "      <arg name='username' direction='in' type='s'/>"
842         "      <arg name='session-name' direction='in' type='s'/>"
843         "    </method>"
844         "    <method name='SwitchToGuest'>"
845         "      <arg name='session-name' direction='in' type='s'/>"
846         "    </method>"
847         "    <method name='Lock'/>"
848         "    <signal name='SessionAdded'>"
849         "      <arg name='session' type='o'/>"
850         "    </signal>"
851         "    <signal name='SessionRemoved'>"
852         "      <arg name='session' type='o'/>"
853         "    </signal>"
854         "  </interface>"
855         "</node>";
856     const gchar *session_interface =
857         "<node>"
858         "  <interface name='org.freedesktop.DisplayManager.Session'>"
859         "    <property name='Seat' type='o' access='read'/>"
860         "    <property name='UserName' type='s' access='read'/>"
861         "    <method name='Lock'/>"
862         "  </interface>"
863         "</node>";
864     GDBusNodeInfo *display_manager_info;
865     GList *link;
866     GError *error = NULL;
867
868     g_debug ("Acquired bus name %s", name);
869
870     bus = connection;
871
872     display_manager_info = g_dbus_node_info_new_for_xml (display_manager_interface, NULL);
873     g_assert (display_manager_info != NULL);
874     seat_info = g_dbus_node_info_new_for_xml (seat_interface, NULL);
875     g_assert (seat_info != NULL);
876     session_info = g_dbus_node_info_new_for_xml (session_interface, NULL);
877     g_assert (session_info != NULL);
878
879     reg_id = g_dbus_connection_register_object (connection,
880                                                 "/org/freedesktop/DisplayManager",
881                                                 display_manager_info->interfaces[0],
882                                                 &display_manager_vtable,
883                                                 NULL, NULL,
884                                                 &error);
885     if (reg_id == 0)
886         g_warning ("Failed to register display manager: %s", error->message);
887     g_clear_error (&error);
888     g_dbus_node_info_unref (display_manager_info);
889
890     seat_bus_entries = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, seat_bus_entry_free);
891     session_bus_entries = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, session_bus_entry_free);
892
893     g_signal_connect (display_manager, DISPLAY_MANAGER_SIGNAL_SEAT_ADDED, G_CALLBACK (seat_added_cb), NULL);
894     g_signal_connect (display_manager, DISPLAY_MANAGER_SIGNAL_SEAT_REMOVED, G_CALLBACK (seat_removed_cb), NULL);
895     for (link = display_manager_get_seats (display_manager); link; link = link->next)
896         seat_added_cb (display_manager, (Seat *) link->data);
897
898     display_manager_start (display_manager);
899
900     /* Start the XDMCP server */
901     if (config_get_boolean (config_get_instance (), "XDMCPServer", "enabled"))
902     {
903         gchar *key_name, *key = NULL, *listen_address, *hostname;
904
905         xdmcp_server = xdmcp_server_new ();
906         if (config_has_key (config_get_instance (), "XDMCPServer", "port"))
907         {
908             gint port;
909             port = config_get_integer (config_get_instance (), "XDMCPServer", "port");
910             if (port > 0)
911                 xdmcp_server_set_port (xdmcp_server, port);
912         }
913         listen_address = config_get_string (config_get_instance (), "XDMCPServer", "listen-address");
914         xdmcp_server_set_listen_address (xdmcp_server, listen_address);
915         g_free (listen_address);
916         hostname = config_get_string (config_get_instance (), "XDMCPServer", "hostname");
917         xdmcp_server_set_hostname (xdmcp_server, hostname);
918         g_free (hostname);
919         g_signal_connect (xdmcp_server, XDMCP_SERVER_SIGNAL_NEW_SESSION, G_CALLBACK (xdmcp_session_cb), NULL);
920
921         key_name = config_get_string (config_get_instance (), "XDMCPServer", "key");
922         if (key_name)
923         {
924             gchar *path;
925             GKeyFile *keys;
926             gboolean result;
927             GError *error = NULL;
928
929             path = g_build_filename (config_get_directory (config_get_instance ()), "keys.conf", NULL);
930
931             keys = g_key_file_new ();
932             result = g_key_file_load_from_file (keys, path, G_KEY_FILE_NONE, &error);
933             if (error)
934                 g_warning ("Unable to load keys from %s: %s", path, error->message);
935             g_clear_error (&error);
936
937             if (result)
938             {
939                 if (g_key_file_has_key (keys, "keyring", key_name, NULL))
940                     key = g_key_file_get_string (keys, "keyring", key_name, NULL);
941                 else
942                     g_warning ("Key %s not defined", key_name);
943             }
944             g_free (path);
945             g_key_file_free (keys);
946         }
947         if (key)
948             xdmcp_server_set_key (xdmcp_server, key);
949         g_free (key_name);
950         g_free (key);
951       
952         if (key_name && !key)
953         {
954             exit_code = EXIT_FAILURE;
955             display_manager_stop (display_manager);
956             return;
957         }
958         else
959         {
960             g_debug ("Starting XDMCP server on UDP/IP port %d", xdmcp_server_get_port (xdmcp_server));
961             xdmcp_server_start (xdmcp_server);
962         }
963     }
964
965     /* Start the VNC server */
966     if (config_get_boolean (config_get_instance (), "VNCServer", "enabled"))
967     {
968         gchar *path;
969
970         path = g_find_program_in_path ("Xvnc");
971         if (path)
972         {
973             gchar *listen_address;
974
975             vnc_server = vnc_server_new ();
976             if (config_has_key (config_get_instance (), "VNCServer", "port"))
977             {
978                 gint port;
979                 port = config_get_integer (config_get_instance (), "VNCServer", "port");
980                 if (port > 0)
981                     vnc_server_set_port (vnc_server, port);
982             }
983             listen_address = config_get_string (config_get_instance (), "VNCServer", "listen-address");
984             vnc_server_set_listen_address (vnc_server, listen_address);
985             g_free (listen_address);
986             g_signal_connect (vnc_server, VNC_SERVER_SIGNAL_NEW_CONNECTION, G_CALLBACK (vnc_connection_cb), NULL);
987
988             g_debug ("Starting VNC server on TCP/IP port %d", vnc_server_get_port (vnc_server));
989             vnc_server_start (vnc_server);
990
991             g_free (path);
992         }
993         else
994             g_warning ("Can't start VNC server, Xvnc is not in the path");
995     }
996 }
997
998 static void
999 name_lost_cb (GDBusConnection *connection,
1000               const gchar *name,
1001               gpointer user_data)
1002 {
1003     if (connection)
1004         g_printerr ("Failed to use bus name " LIGHTDM_BUS_NAME ", do you have appropriate permissions?\n");
1005     else
1006         g_printerr ("Failed to get D-Bus connection\n");
1007
1008     exit (EXIT_FAILURE);
1009 }
1010
1011 static gboolean
1012 add_login1_seat (Login1Seat *login1_seat)
1013 {
1014     const gchar *seat_name = login1_seat_get_id (login1_seat);
1015     gchar **types = NULL, **type;
1016     GList *config_sections = NULL, *link;
1017     Seat *seat = NULL;
1018     gboolean is_seat0, started = FALSE;
1019
1020     g_debug ("New seat added from logind: %s", seat_name);
1021     is_seat0 = strcmp (seat_name, "seat0") == 0;
1022
1023     config_sections = get_config_sections (seat_name);
1024     for (link = g_list_last (config_sections); link; link = link->prev)
1025     {
1026         gchar *config_section = link->data;
1027         types = config_get_string_list (config_get_instance (), config_section, "type");
1028         if (types)
1029             break;
1030     }
1031     g_list_free_full (config_sections, g_free);
1032
1033     for (type = types; !seat && type && *type; type++)
1034         seat = create_seat (*type, seat_name);
1035     g_strfreev (types);
1036
1037     if (seat)
1038     {
1039         set_seat_properties (seat, seat_name);
1040
1041         if (!login1_seat_get_can_multi_session (login1_seat))
1042         {
1043             g_debug ("Seat %s has property CanMultiSession=no", seat_name);
1044             /* XXX: uncomment this line after bug #1371250 is closed.
1045             seat_set_property (seat, "allow-user-switching", "false"); */
1046         }
1047
1048         if (is_seat0)
1049             seat_set_property (seat, "exit-on-failure", "true");
1050     }
1051     else
1052     {
1053         g_debug ("Unable to create seat: %s", seat_name);
1054         return FALSE;
1055     }
1056
1057     started = display_manager_add_seat (display_manager, seat);
1058     if (!started)
1059         g_debug ("Failed to start seat: %s", seat_name);
1060     g_object_unref (seat);
1061
1062     return started;
1063 }
1064
1065 static void
1066 remove_login1_seat (Login1Seat *login1_seat)
1067 {
1068     Seat *seat;
1069
1070     seat = display_manager_get_seat (display_manager, login1_seat_get_id (login1_seat));
1071     if (seat)
1072         seat_stop (seat);
1073 }
1074
1075 static void
1076 seat_stopped_cb (Seat *seat, Login1Seat *login1_seat)
1077 {
1078     update_login1_seat (login1_seat);
1079     g_signal_handlers_disconnect_matched (seat, G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, login1_seat);
1080 }
1081
1082 static gboolean
1083 update_login1_seat (Login1Seat *login1_seat)
1084 {
1085     if (!config_get_boolean (config_get_instance (), "LightDM", "logind-check-graphical") ||
1086         login1_seat_get_can_graphical (login1_seat))
1087     {
1088         Seat *seat;
1089
1090         /* Wait for existing seat to stop or ignore if we already have a valid seat */
1091         seat = display_manager_get_seat (display_manager, login1_seat_get_id (login1_seat));
1092         if (seat)
1093         {
1094             if (seat_get_is_stopping (seat))
1095                 g_signal_connect (seat, SEAT_SIGNAL_STOPPED, G_CALLBACK (seat_stopped_cb), login1_seat);
1096             return TRUE;
1097         }
1098
1099         return add_login1_seat (login1_seat);
1100     }
1101     else
1102     {
1103         remove_login1_seat (login1_seat);
1104         return TRUE;
1105     }
1106 }
1107
1108 static void
1109 login1_can_graphical_changed_cb (Login1Seat *login1_seat)
1110 {
1111     g_debug ("Seat %s changes graphical state to %s", login1_seat_get_id (login1_seat), login1_seat_get_can_graphical (login1_seat) ? "true" : "false");
1112     update_login1_seat (login1_seat);
1113 }
1114
1115 static void
1116 login1_active_session_changed_cb (Login1Seat *login1_seat, const gchar *login1_session_id)
1117 {
1118     g_debug ("Seat %s changes active session to %s", login1_seat_get_id (login1_seat), login1_session_id);
1119
1120     Seat *seat;
1121     seat = display_manager_get_seat (display_manager, login1_seat_get_id (login1_seat));
1122
1123     if (seat)
1124     {
1125         Session *active_session;
1126
1127         active_session = seat_get_expected_active_session (seat);
1128         if (active_session != NULL &&
1129             g_strcmp0 (login1_session_id, session_get_login1_session_id (active_session)) == 0)
1130         {
1131             // Session is already active
1132             g_debug ("Session %s is already active", login1_session_id);
1133             return;
1134         }
1135
1136         active_session = seat_find_session_by_login1_id (seat, login1_session_id);
1137         if (active_session != NULL)
1138         {
1139             g_debug ("Activating session %s", login1_session_id);
1140             seat_set_externally_activated_session (seat, active_session);
1141             return;
1142
1143         }
1144     }
1145 }
1146
1147 static gboolean
1148 login1_add_seat (Login1Seat *login1_seat)
1149 {
1150     if (config_get_boolean (config_get_instance (), "LightDM", "logind-check-graphical"))
1151         g_signal_connect (login1_seat, "can-graphical-changed", G_CALLBACK (login1_can_graphical_changed_cb), NULL);
1152
1153     g_signal_connect (login1_seat, LOGIN1_SIGNAL_ACTIVE_SESION_CHANGED, G_CALLBACK (login1_active_session_changed_cb), NULL);
1154
1155     return update_login1_seat (login1_seat);
1156 }
1157
1158 static void
1159 login1_service_seat_added_cb (Login1Service *service, Login1Seat *login1_seat)
1160 {
1161     if (login1_seat_get_can_graphical (login1_seat))
1162         g_debug ("Seat %s added from logind", login1_seat_get_id (login1_seat));
1163     else
1164         g_debug ("Seat %s added from logind without graphical output", login1_seat_get_id (login1_seat));
1165
1166     login1_add_seat (login1_seat);
1167 }
1168
1169 static void
1170 login1_service_seat_removed_cb (Login1Service *service, Login1Seat *login1_seat)
1171 {
1172     g_debug ("Seat %s removed from logind", login1_seat_get_id (login1_seat));
1173     g_signal_handlers_disconnect_matched (login1_seat, G_SIGNAL_MATCH_FUNC, 0, 0, NULL, login1_can_graphical_changed_cb, NULL);
1174     g_signal_handlers_disconnect_matched (login1_seat, G_SIGNAL_MATCH_FUNC, 0, 0, NULL, login1_active_session_changed_cb, NULL);
1175     remove_login1_seat (login1_seat);
1176 }
1177
1178 int
1179 main (int argc, char **argv)
1180 {
1181     FILE *pid_file;
1182     GOptionContext *option_context;
1183     gboolean result;
1184     gchar *dir;
1185     gboolean test_mode = FALSE;
1186     gchar *pid_path = "/var/run/lightdm.pid";
1187     gchar *log_dir = NULL;
1188     gchar *run_dir = NULL;
1189     gchar *cache_dir = NULL;
1190     gchar *default_log_dir = g_strdup (LOG_DIR);
1191     gchar *default_run_dir = g_strdup (RUN_DIR);
1192     gchar *default_cache_dir = g_strdup (CACHE_DIR);
1193     gboolean show_config = FALSE, show_version = FALSE;
1194     GList *link, *messages = NULL;
1195     GOptionEntry options[] =
1196     {
1197         { "config", 'c', 0, G_OPTION_ARG_STRING, &config_path,
1198           /* Help string for command line --config flag */
1199           N_("Use configuration file"), "FILE" },
1200         { "debug", 'd', 0, G_OPTION_ARG_NONE, &debug,
1201           /* Help string for command line --debug flag */
1202           N_("Print debugging messages"), NULL },
1203         { "test-mode", 0, 0, G_OPTION_ARG_NONE, &test_mode,
1204           /* Help string for command line --test-mode flag */
1205           N_("Run as unprivileged user, skipping things that require root access"), NULL },
1206         { "pid-file", 0, 0, G_OPTION_ARG_STRING, &pid_path,
1207           /* Help string for command line --pid-file flag */
1208           N_("File to write PID into"), "FILE" },
1209         { "log-dir", 0, 0, G_OPTION_ARG_STRING, &log_dir,
1210           /* Help string for command line --log-dir flag */
1211           N_("Directory to write logs to"), "DIRECTORY" },
1212         { "run-dir", 0, 0, G_OPTION_ARG_STRING, &run_dir,
1213           /* Help string for command line --run-dir flag */
1214           N_("Directory to store running state"), "DIRECTORY" },
1215         { "cache-dir", 0, 0, G_OPTION_ARG_STRING, &cache_dir,
1216           /* Help string for command line --cache-dir flag */
1217           N_("Directory to cache information"), "DIRECTORY" },
1218         { "show-config", 0, 0, G_OPTION_ARG_NONE, &show_config,
1219           /* Help string for command line --show-config flag */
1220           N_("Show combined configuration"), NULL },
1221         { "version", 'v', 0, G_OPTION_ARG_NONE, &show_version,
1222           /* Help string for command line --version flag */
1223           N_("Show release version"), NULL },
1224         { NULL }
1225     };
1226     GError *error = NULL;
1227
1228     /* Disable the SIGPIPE handler - this is a stupid Unix hangover behaviour.
1229      * We will handle piples / sockets being closed instead of having the whole daemon be killed...
1230      * http://stackoverflow.com/questions/8369506/why-does-sigpipe-exist
1231      */
1232     signal (SIGPIPE, SIG_IGN);
1233
1234     /* When lightdm starts sessions it needs to run itself in a new mode */
1235     if (argc >= 2 && strcmp (argv[1], "--session-child") == 0)
1236         return session_child_run (argc, argv);
1237
1238 #if !defined(GLIB_VERSION_2_36)
1239     g_type_init ();
1240 #endif
1241     loop = g_main_loop_new (NULL, FALSE);
1242
1243     messages = g_list_append (messages, g_strdup_printf ("Starting Light Display Manager %s, UID=%i PID=%i", VERSION, getuid (), getpid ()));
1244
1245     g_signal_connect (process_get_current (), PROCESS_SIGNAL_GOT_SIGNAL, G_CALLBACK (signal_cb), NULL);
1246
1247     option_context = g_option_context_new (/* Arguments and description for --help test */
1248                                            _("- Display Manager"));
1249     g_option_context_add_main_entries (option_context, options, GETTEXT_PACKAGE);
1250     result = g_option_context_parse (option_context, &argc, &argv, &error);
1251     if (error)
1252         g_printerr ("%s\n", error->message);
1253     g_clear_error (&error);
1254     g_option_context_free (option_context);
1255     if (!result)
1256     {
1257         g_printerr (/* Text printed out when an unknown command-line argument provided */
1258                     _("Run '%s --help' to see a full list of available command line options."), argv[0]);
1259         g_printerr ("\n");
1260         return EXIT_FAILURE;
1261     }
1262
1263     /* Show combined configuration if user requested it */
1264     if (show_config)
1265     {
1266         GList *sources, *link;
1267         gchar **groups, *last_source, *empty_source;
1268         GHashTable *source_ids;
1269         int i;
1270
1271         if (!config_load_from_standard_locations (config_get_instance (), config_path, NULL))
1272             return EXIT_FAILURE;
1273
1274         /* Number sources */
1275         sources = config_get_sources (config_get_instance ());
1276         source_ids = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
1277         last_source = "";
1278         for (i = 0, link = sources; link; i++, link = link->next)
1279         {
1280             gchar *path, *id;
1281
1282             path = link->data;
1283             if (i < 26)
1284                 id = g_strdup_printf ("%c", 'A' + i);
1285             else
1286                 id = g_strdup_printf ("%d", i);
1287             g_hash_table_insert (source_ids, g_strdup (path), id);
1288             last_source = id;
1289         }
1290         empty_source = g_strdup (last_source);
1291         for (i = 0; empty_source[i] != '\0'; i++)
1292             empty_source[i] = ' ';
1293
1294         /* Print out keys */
1295         groups = config_get_groups (config_get_instance ());
1296         for (i = 0; groups[i]; i++)
1297         {
1298             gchar **keys;
1299             int j;
1300
1301             if (i != 0)
1302                 g_printerr ("\n");
1303             g_printerr ("%s  [%s]\n", empty_source, groups[i]);
1304
1305             keys = config_get_keys (config_get_instance (), groups[i]);
1306             for (j = 0; keys && keys[j]; j++)
1307             {
1308                 const gchar *source, *id;
1309                 gchar *value;
1310
1311                 source = config_get_source (config_get_instance (), groups[i], keys[j]);
1312                 id = source ? g_hash_table_lookup (source_ids, source) : empty_source;
1313                 value = config_get_string (config_get_instance (), groups[i], keys[j]);
1314                 g_printerr ("%s  %s=%s\n", id, keys[j], value);
1315                 g_free (value);
1316             }
1317
1318             g_strfreev (keys);
1319         }
1320         g_strfreev (groups);
1321
1322         /* Show mapping from source number to path */
1323         g_printerr ("\n");
1324         g_printerr ("Sources:\n");
1325         for (link = sources; link; link = link->next)
1326         {
1327             const gchar *path = link->data;
1328             const gchar *source;
1329
1330             source = g_hash_table_lookup (source_ids, path);
1331             g_printerr ("%s  %s\n", source, path);
1332         }
1333
1334         g_hash_table_destroy (source_ids);
1335
1336         return EXIT_SUCCESS;
1337     }
1338
1339     if (show_version)
1340     {
1341         /* NOTE: Is not translated so can be easily parsed */
1342         g_printerr ("lightdm %s\n", VERSION);
1343         return EXIT_SUCCESS;
1344     }
1345
1346     if (!test_mode && getuid () != 0)
1347     {
1348         g_printerr ("Only root can run Light Display Manager.  To run as a regular user for testing run with the --test-mode flag.\n");
1349         return EXIT_FAILURE;
1350     }
1351
1352     /* If running inside an X server use Xephyr for display */
1353     if (getenv ("DISPLAY") && getuid () != 0)
1354     {
1355         gchar *x_server_path;
1356
1357         x_server_path = g_find_program_in_path ("Xephyr");
1358         if (!x_server_path)
1359         {
1360             g_printerr ("Running inside an X server requires Xephyr to be installed but it cannot be found.  Please install it or update your PATH environment variable.\n");
1361             return EXIT_FAILURE;
1362         }
1363         g_free (x_server_path);
1364     }
1365
1366     /* Make sure the system binary directory (where the greeters are installed) is in the path */
1367     if (test_mode)
1368     {
1369         const gchar *path = g_getenv ("PATH");
1370         gchar *new_path;
1371
1372         if (path)
1373             new_path = g_strdup_printf ("%s:%s", path, SBIN_DIR);
1374         else
1375             new_path = g_strdup (SBIN_DIR);
1376         g_setenv ("PATH", new_path, TRUE);
1377         g_free (new_path);
1378     }
1379
1380     /* Write PID file */
1381     pid_file = fopen (pid_path, "w");
1382     if (pid_file)
1383     {
1384         fprintf (pid_file, "%d\n", getpid ());
1385         fclose (pid_file);
1386     }
1387
1388     /* If not running as root write output to directories we control */
1389     if (getuid () != 0)
1390     {
1391         g_free (default_log_dir);
1392         default_log_dir = g_build_filename (g_get_user_cache_dir (), "lightdm", "log", NULL);
1393         g_free (default_run_dir);
1394         default_run_dir = g_build_filename (g_get_user_cache_dir (), "lightdm", "run", NULL);
1395         g_free (default_cache_dir);
1396         default_cache_dir = g_build_filename (g_get_user_cache_dir (), "lightdm", "cache", NULL);
1397     }
1398
1399     /* Load config file(s) */
1400     if (!config_load_from_standard_locations (config_get_instance (), config_path, &messages))
1401         exit (EXIT_FAILURE);
1402     g_free (config_path);
1403
1404     /* Set default values */
1405     if (!config_has_key (config_get_instance (), "LightDM", "start-default-seat"))
1406         config_set_boolean (config_get_instance (), "LightDM", "start-default-seat", TRUE);
1407     if (!config_has_key (config_get_instance (), "LightDM", "minimum-vt"))
1408         config_set_integer (config_get_instance (), "LightDM", "minimum-vt", 7);
1409     if (!config_has_key (config_get_instance (), "LightDM", "guest-account-script"))
1410         config_set_string (config_get_instance (), "LightDM", "guest-account-script", "guest-account");
1411     if (!config_has_key (config_get_instance (), "LightDM", "greeter-user"))
1412         config_set_string (config_get_instance (), "LightDM", "greeter-user", GREETER_USER);
1413     if (!config_has_key (config_get_instance (), "LightDM", "lock-memory"))
1414         config_set_boolean (config_get_instance (), "LightDM", "lock-memory", TRUE);
1415     if (!config_has_key (config_get_instance (), "LightDM", "backup-logs"))
1416         config_set_boolean (config_get_instance (), "LightDM", "backup-logs", TRUE);
1417     if (!config_has_key (config_get_instance (), "Seat:*", "type"))
1418         config_set_string (config_get_instance (), "Seat:*", "type", "local");
1419     if (!config_has_key (config_get_instance (), "Seat:*", "pam-service"))
1420         config_set_string (config_get_instance (), "Seat:*", "pam-service", "lightdm");
1421     if (!config_has_key (config_get_instance (), "Seat:*", "pam-autologin-service"))
1422         config_set_string (config_get_instance (), "Seat:*", "pam-autologin-service", "lightdm-autologin");
1423     if (!config_has_key (config_get_instance (), "Seat:*", "pam-greeter-service"))
1424         config_set_string (config_get_instance (), "Seat:*", "pam-greeter-service", "lightdm-greeter");
1425     if (!config_has_key (config_get_instance (), "Seat:*", "xserver-command"))
1426         config_set_string (config_get_instance (), "Seat:*", "xserver-command", "X");
1427     if (!config_has_key (config_get_instance (), "Seat:*", "xmir-command"))
1428         config_set_string (config_get_instance (), "Seat:*", "xmir-command", "Xmir");
1429     if (!config_has_key (config_get_instance (), "Seat:*", "xserver-share"))
1430         config_set_boolean (config_get_instance (), "Seat:*", "xserver-share", TRUE);
1431     if (!config_has_key (config_get_instance (), "Seat:*", "unity-compositor-command"))
1432         config_set_string (config_get_instance (), "Seat:*", "unity-compositor-command", "unity-system-compositor");
1433     if (!config_has_key (config_get_instance (), "Seat:*", "start-session"))
1434         config_set_boolean (config_get_instance (), "Seat:*", "start-session", TRUE);
1435     if (!config_has_key (config_get_instance (), "Seat:*", "allow-user-switching"))
1436         config_set_boolean (config_get_instance (), "Seat:*", "allow-user-switching", TRUE);
1437     if (!config_has_key (config_get_instance (), "Seat:*", "allow-guest"))
1438         config_set_boolean (config_get_instance (), "Seat:*", "allow-guest", TRUE);
1439     if (!config_has_key (config_get_instance (), "Seat:*", "greeter-allow-guest"))
1440         config_set_boolean (config_get_instance (), "Seat:*", "greeter-allow-guest", TRUE);
1441     if (!config_has_key (config_get_instance (), "Seat:*", "greeter-show-remote-login"))
1442         config_set_boolean (config_get_instance (), "Seat:*", "greeter-show-remote-login", TRUE);
1443     if (!config_has_key (config_get_instance (), "Seat:*", "greeter-session"))
1444         config_set_string (config_get_instance (), "Seat:*", "greeter-session", DEFAULT_GREETER_SESSION);
1445     if (!config_has_key (config_get_instance (), "Seat:*", "user-session"))
1446         config_set_string (config_get_instance (), "Seat:*", "user-session", DEFAULT_USER_SESSION);
1447     if (!config_has_key (config_get_instance (), "Seat:*", "session-wrapper"))
1448         config_set_string (config_get_instance (), "Seat:*", "session-wrapper", "lightdm-session");
1449     if (!config_has_key (config_get_instance (), "LightDM", "log-directory"))
1450         config_set_string (config_get_instance (), "LightDM", "log-directory", default_log_dir);
1451     g_free (default_log_dir);
1452     if (!config_has_key (config_get_instance (), "LightDM", "run-directory"))
1453         config_set_string (config_get_instance (), "LightDM", "run-directory", default_run_dir);
1454     g_free (default_run_dir);
1455     if (!config_has_key (config_get_instance (), "LightDM", "cache-directory"))
1456         config_set_string (config_get_instance (), "LightDM", "cache-directory", default_cache_dir);
1457     g_free (default_cache_dir);
1458     if (!config_has_key (config_get_instance (), "LightDM", "sessions-directory"))
1459         config_set_string (config_get_instance (), "LightDM", "sessions-directory", SESSIONS_DIR);
1460     if (!config_has_key (config_get_instance (), "LightDM", "remote-sessions-directory"))
1461         config_set_string (config_get_instance (), "LightDM", "remote-sessions-directory", REMOTE_SESSIONS_DIR);
1462     if (!config_has_key (config_get_instance (), "LightDM", "greeters-directory"))
1463         config_set_string (config_get_instance (), "LightDM", "greeters-directory", GREETERS_DIR);
1464     if (!config_has_key (config_get_instance (), "XDMCPServer", "hostname"))
1465         config_set_string (config_get_instance (), "XDMCPServer", "hostname", g_get_host_name ());
1466
1467     /* Override defaults */
1468     if (log_dir)
1469         config_set_string (config_get_instance (), "LightDM", "log-directory", log_dir);
1470     g_free (log_dir);
1471     if (run_dir)
1472         config_set_string (config_get_instance (), "LightDM", "run-directory", run_dir);
1473     g_free (run_dir);
1474     if (cache_dir)
1475         config_set_string (config_get_instance (), "LightDM", "cache-directory", cache_dir);
1476     g_free (cache_dir);
1477
1478     /* Create run and cache directories */
1479     dir = config_get_string (config_get_instance (), "LightDM", "log-directory");
1480     if (g_mkdir_with_parents (dir, S_IRWXU | S_IXGRP | S_IXOTH) < 0)
1481         g_warning ("Failed to make log directory %s: %s", dir, strerror (errno));
1482     g_free (dir);
1483     dir = config_get_string (config_get_instance (), "LightDM", "run-directory");
1484     if (g_mkdir_with_parents (dir, S_IRWXU | S_IXGRP | S_IXOTH) < 0)
1485         g_warning ("Failed to make run directory %s: %s", dir, strerror (errno));
1486     g_free (dir);
1487     dir = config_get_string (config_get_instance (), "LightDM", "cache-directory");
1488     if (g_mkdir_with_parents (dir, S_IRWXU | S_IXGRP | S_IXOTH) < 0)
1489         g_warning ("Failed to make cache directory %s: %s", dir, strerror (errno));
1490     g_free (dir);
1491
1492     log_init ();
1493
1494     /* Show queued messages once logging is complete */
1495     for (link = messages; link; link = link->next)
1496         g_debug ("%s", (gchar *)link->data);
1497     g_list_free_full (messages, g_free);
1498
1499     g_debug ("Using D-Bus name %s", LIGHTDM_BUS_NAME);
1500     bus_id = g_bus_own_name (getuid () == 0 ? G_BUS_TYPE_SYSTEM : G_BUS_TYPE_SESSION,
1501                              LIGHTDM_BUS_NAME,
1502                              G_BUS_NAME_OWNER_FLAGS_NONE,
1503                              bus_acquired_cb,
1504                              NULL,
1505                              name_lost_cb,
1506                              NULL,
1507                              NULL);
1508
1509     if (getuid () != 0)
1510         g_debug ("Running in user mode");
1511     if (getenv ("DISPLAY"))
1512         g_debug ("Using Xephyr for X servers");
1513
1514     display_manager = display_manager_new ();
1515     g_signal_connect (display_manager, DISPLAY_MANAGER_SIGNAL_STOPPED, G_CALLBACK (display_manager_stopped_cb), NULL);
1516     g_signal_connect (display_manager, DISPLAY_MANAGER_SIGNAL_SEAT_REMOVED, G_CALLBACK (display_manager_seat_removed_cb), NULL);
1517
1518     shared_data_manager_start (shared_data_manager_get_instance ());
1519
1520     /* Connect to logind */
1521     if (login1_service_connect (login1_service_get_instance ()))
1522     {
1523         /* Load dynamic seats from logind */
1524         g_debug ("Monitoring logind for seats");
1525
1526         if (config_get_boolean (config_get_instance (), "LightDM", "start-default-seat"))
1527         {
1528             g_signal_connect (login1_service_get_instance (), LOGIN1_SERVICE_SIGNAL_SEAT_ADDED, G_CALLBACK (login1_service_seat_added_cb), NULL);
1529             g_signal_connect (login1_service_get_instance (), LOGIN1_SERVICE_SIGNAL_SEAT_REMOVED, G_CALLBACK (login1_service_seat_removed_cb), NULL);
1530
1531             for (link = login1_service_get_seats (login1_service_get_instance ()); link; link = link->next)
1532             {
1533                 Login1Seat *login1_seat = link->data;
1534                 if (!login1_add_seat (login1_seat))
1535                     return EXIT_FAILURE;
1536             }
1537         }
1538     }
1539     else
1540     {
1541         if (config_get_boolean (config_get_instance (), "LightDM", "start-default-seat"))
1542         {
1543             gchar **types;
1544             gchar **type;
1545             Seat *seat = NULL;
1546
1547             g_debug ("Adding default seat");
1548
1549             types = config_get_string_list (config_get_instance (), "Seat:*", "type");
1550             for (type = types; type && *type; type++)
1551             {
1552                 seat = create_seat (*type, "seat0");
1553                 if (seat)
1554                     break;
1555             }
1556             g_strfreev (types);
1557             if (seat)
1558             {
1559                 set_seat_properties (seat, NULL);
1560                 seat_set_property (seat, "exit-on-failure", "true");
1561                 if (!display_manager_add_seat (display_manager, seat))
1562                     return EXIT_FAILURE;
1563                 g_object_unref (seat);
1564             }
1565             else
1566             {
1567                 g_warning ("Failed to create default seat");
1568                 return EXIT_FAILURE;
1569             }
1570         }
1571     }
1572
1573     g_main_loop_run (loop);
1574
1575     /* Clean up shared data manager */
1576     shared_data_manager_cleanup ();
1577
1578     /* Clean up user list */
1579     common_user_list_cleanup ();
1580
1581     /* Clean up display manager */
1582     g_clear_object (&display_manager);
1583
1584     /* Remove D-Bus interface */
1585     g_dbus_connection_unregister_object (bus, reg_id);
1586     g_bus_unown_name (bus_id);
1587     if (seat_bus_entries)
1588         g_hash_table_unref (seat_bus_entries);
1589     if (session_bus_entries)
1590         g_hash_table_unref (session_bus_entries);
1591
1592     g_debug ("Exiting with return value %d", exit_code);
1593     return exit_code;
1594 }