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