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