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