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