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