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