]> rtime.felk.cvut.cz Git - sojka/lightdm.git/blob - src/lightdm.c
src/lightdm.c: g_thread_init() deprecated, so removed.
[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
23 #include "configuration.h"
24 #include "display-manager.h"
25 #include "xdmcp-server.h"
26 #include "vnc-server.h"
27 #include "seat-xdmcp-session.h"
28 #include "seat-xvnc.h"
29 #include "xserver.h"
30 #include "pam-session.h"
31 #include "process.h"
32
33 static gchar *config_path = NULL;
34 static GMainLoop *loop = NULL;
35 static GTimer *log_timer;
36 static int log_fd = -1;
37 static gboolean debug = FALSE;
38
39 static DisplayManager *display_manager = NULL;
40 static XDMCPServer *xdmcp_server = NULL;
41 static VNCServer *vnc_server = NULL;
42 static guint bus_id = 0;
43 static GDBusConnection *bus = NULL;
44 static guint bus_id;
45 static GDBusNodeInfo *seat_info;
46 static GHashTable *seat_bus_entries = NULL;
47 static guint seat_index = 0;
48 static GDBusNodeInfo *session_info;
49 static GHashTable *session_bus_entries = NULL;
50 static guint session_index = 0;
51 static gint exit_code = EXIT_SUCCESS;
52
53 typedef struct
54 {
55     gchar *path;
56     gchar *parent_path;
57     gchar *removed_signal;
58     guint bus_id;
59 } BusEntry;
60
61 #define LIGHTDM_BUS_NAME "org.freedesktop.DisplayManager"
62
63 static void
64 log_cb (const gchar *log_domain, GLogLevelFlags log_level, const gchar *message, gpointer data)
65 {
66     const gchar *prefix;
67     gchar *text;
68
69     switch (log_level & G_LOG_LEVEL_MASK)
70     {
71     case G_LOG_LEVEL_ERROR:
72         prefix = "ERROR:";
73         break;
74     case G_LOG_LEVEL_CRITICAL:
75         prefix = "CRITICAL:";
76         break;
77     case G_LOG_LEVEL_WARNING:
78         prefix = "WARNING:";
79         break;
80     case G_LOG_LEVEL_MESSAGE:
81         prefix = "MESSAGE:";
82         break;
83     case G_LOG_LEVEL_INFO:
84         prefix = "INFO:";
85         break;
86     case G_LOG_LEVEL_DEBUG:
87         prefix = "DEBUG:";
88         break;
89     default:
90         prefix = "LOG:";
91         break;
92     }
93
94     text = g_strdup_printf ("[%+.2fs] %s %s\n", g_timer_elapsed (log_timer, NULL), prefix, message);
95
96     /* Log everything to a file */
97     if (log_fd >= 0)
98     {
99         ssize_t n_written;
100         n_written = write (log_fd, text, strlen (text));
101         if (n_written < 0)
102             ; /* Check result so compiler doesn't warn about it */
103     }
104
105     /* Log to stderr if requested */
106     if (debug)
107         g_printerr ("%s", text);
108     else
109         g_log_default_handler (log_domain, log_level, message, data);
110
111     g_free (text);
112 }
113
114 static void
115 log_init (void)
116 {
117     gchar *log_dir, *path;
118
119     log_timer = g_timer_new ();
120
121     /* Log to a file */
122     log_dir = config_get_string (config_get_instance (), "LightDM", "log-directory");
123     path = g_build_filename (log_dir, "lightdm.log", NULL);
124     g_free (log_dir);
125
126     log_fd = open (path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
127     g_log_set_default_handler (log_cb, NULL);
128
129     g_debug ("Logging to %s", path);
130     g_free (path);
131 }
132
133 static void
134 signal_cb (Process *process, int signum)
135 {
136     g_debug ("Caught %s signal, shutting down", g_strsignal (signum));
137     display_manager_stop (display_manager);
138     // FIXME: Stop XDMCP server
139 }
140
141 static gboolean
142 exit_cb (gpointer data)
143 {
144     /* Clean up display manager */
145     g_object_unref (display_manager);
146     display_manager = NULL;
147
148     /* Remove D-Bus interface */
149     g_bus_unown_name (bus_id);
150     if (seat_bus_entries)
151         g_hash_table_unref (seat_bus_entries);
152     if (session_bus_entries)
153         g_hash_table_unref (session_bus_entries);
154
155     g_debug ("Exiting with return value %d", exit_code);
156     exit (exit_code);
157 }
158
159 static void
160 display_manager_stopped_cb (DisplayManager *display_manager)
161 {
162     g_debug ("Stopping daemon");
163     g_idle_add (exit_cb, NULL);
164 }
165
166 static GVariant *
167 handle_display_manager_get_property (GDBusConnection       *connection,
168                                      const gchar           *sender,
169                                      const gchar           *object_path,
170                                      const gchar           *interface_name,
171                                      const gchar           *property_name,
172                                      GError               **error,
173                                      gpointer               user_data)
174 {
175     GVariant *result = NULL;
176
177     if (g_strcmp0 (property_name, "Seats") == 0)
178     {
179         GVariantBuilder *builder;
180         GHashTableIter iter;
181         gpointer value;
182
183         builder = g_variant_builder_new (G_VARIANT_TYPE ("ao"));
184         g_hash_table_iter_init (&iter, seat_bus_entries);
185         while (g_hash_table_iter_next (&iter, NULL, &value))
186         {
187             BusEntry *entry = value;
188             g_variant_builder_add_value (builder, g_variant_new_object_path (entry->path));
189         }
190         result = g_variant_builder_end (builder);
191         g_variant_builder_unref (builder);
192     }
193     else if (g_strcmp0 (property_name, "Sessions") == 0)
194     {
195         GVariantBuilder *builder;
196         GHashTableIter iter;
197         gpointer value;
198
199         builder = g_variant_builder_new (G_VARIANT_TYPE ("ao"));
200         g_hash_table_iter_init (&iter, session_bus_entries);
201         while (g_hash_table_iter_next (&iter, NULL, &value))
202         {
203             BusEntry *entry = value;
204             g_variant_builder_add_value (builder, g_variant_new_object_path (entry->path));
205         }
206         result = g_variant_builder_end (builder);
207         g_variant_builder_unref (builder);
208     }
209
210     return result;
211 }
212
213 static void
214 set_seat_properties (Seat *seat, const gchar *config_section)
215 {
216     gchar **keys;
217     gint i;
218
219     keys = config_get_keys (config_get_instance (), "SeatDefaults");
220     for (i = 0; keys[i]; i++)
221     {
222         gchar *value = config_get_string (config_get_instance (), "SeatDefaults", keys[i]);
223         seat_set_property (seat, keys[i], value);
224         g_free (value);
225     }
226     g_strfreev (keys);
227
228     if (config_section)
229     {
230         keys = config_get_keys (config_get_instance (), config_section);
231         for (i = 0; keys[i]; i++)
232         {
233             gchar *value = config_get_string (config_get_instance (), config_section, keys[i]);
234             seat_set_property (seat, keys[i], value);
235             g_free (value);
236         }
237         g_strfreev (keys);
238     }
239 }
240
241 static void
242 handle_display_manager_call (GDBusConnection       *connection,
243                              const gchar           *sender,
244                              const gchar           *object_path,
245                              const gchar           *interface_name,
246                              const gchar           *method_name,
247                              GVariant              *parameters,
248                              GDBusMethodInvocation *invocation,
249                              gpointer               user_data)
250 {
251     if (g_strcmp0 (method_name, "AddSeat") == 0)
252     {
253         gchar *type;
254         GVariantIter *property_iter;
255         gchar *name, *value;
256         Seat *seat;
257
258         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(sa(ss))")))
259             return;
260
261         g_variant_get (parameters, "(&sa(ss))", &type, &property_iter);
262
263         g_debug ("Adding seat of type %s", type);
264
265         seat = seat_new (type);
266         if (seat)
267         {
268             set_seat_properties (seat, NULL);
269             while (g_variant_iter_loop (property_iter, "(&s&s)", &name, &value))
270                 seat_set_property (seat, name, value);
271         }
272         g_variant_iter_free (property_iter);
273
274         if (!seat)
275         {
276             // FIXME: Need to make proper error
277             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Unable to create seat of type %s", type);
278             return;
279         }
280
281         if (display_manager_add_seat (display_manager, seat))
282         {
283             BusEntry *entry;
284
285             entry = g_hash_table_lookup (seat_bus_entries, seat);
286             g_dbus_method_invocation_return_value (invocation, g_variant_new ("(o)", entry->path));
287         }
288         else// FIXME: Need to make proper error
289             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Failed to start seat");
290         g_object_unref (seat);
291     }
292     else if (g_strcmp0 (method_name, "AddLocalXSeat") == 0)
293     {
294         gint display_number;
295         Seat *seat;
296
297         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(i)")))
298             return;
299
300         g_variant_get (parameters, "(i)", &display_number);
301
302         g_debug ("Adding local X seat :%d", display_number);
303
304         seat = seat_new ("xremote");
305         if (seat)
306         {
307             gchar *display_number_string;
308
309             set_seat_properties (seat, NULL);
310             display_number_string = g_strdup_printf ("%d", display_number);
311             seat_set_property (seat, "xserver-display-number", display_number_string);
312             g_free (display_number_string);
313         }
314
315         if (!seat)
316         {
317             // FIXME: Need to make proper error
318             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Unable to create local X seat");
319             return;
320         }
321
322         if (display_manager_add_seat (display_manager, seat))
323         {
324             BusEntry *entry;
325
326             entry = g_hash_table_lookup (seat_bus_entries, seat);
327             g_dbus_method_invocation_return_value (invocation, g_variant_new ("(o)", entry->path));
328         }
329         else// FIXME: Need to make proper error
330             g_dbus_method_invocation_return_error (invocation, G_DBUS_ERROR, G_DBUS_ERROR_FAILED, "Failed to start seat");
331         g_object_unref (seat);
332     }
333 }
334
335 static GVariant *
336 handle_seat_get_property (GDBusConnection       *connection,
337                           const gchar           *sender,
338                           const gchar           *object_path,
339                           const gchar           *interface_name,
340                           const gchar           *property_name,
341                           GError               **error,
342                           gpointer               user_data)
343 {
344     Seat *seat = user_data;
345     GVariant *result = NULL;
346
347     if (g_strcmp0 (property_name, "CanSwitch") == 0)
348         result = g_variant_new_boolean (seat_get_can_switch (seat));
349     if (g_strcmp0 (property_name, "HasGuestAccount") == 0)
350         result = g_variant_new_boolean (seat_get_allow_guest (seat));
351     else if (g_strcmp0 (property_name, "Sessions") == 0)
352     {
353         GVariantBuilder *builder;
354         GList *link;
355
356         builder = g_variant_builder_new (G_VARIANT_TYPE ("ao"));
357         for (link = seat_get_displays (seat); link; link = link->next)
358         {
359             Display *display = link->data;
360             BusEntry *entry;
361             entry = g_hash_table_lookup (session_bus_entries, display_get_session (display));
362             if (entry)
363                 g_variant_builder_add_value (builder, g_variant_new_object_path (entry->path));
364         }
365         result = g_variant_builder_end (builder);
366         g_variant_builder_unref (builder);
367     }
368   
369     return result;
370 }
371
372 static void
373 handle_seat_call (GDBusConnection       *connection,
374                   const gchar           *sender,
375                   const gchar           *object_path,
376                   const gchar           *interface_name,
377                   const gchar           *method_name,
378                   GVariant              *parameters,
379                   GDBusMethodInvocation *invocation,
380                   gpointer               user_data)
381 {
382     Seat *seat = user_data;
383   
384     if (g_strcmp0 (method_name, "SwitchToGreeter") == 0)
385     {
386         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("()")))
387             return;
388
389         seat_switch_to_greeter (seat);
390         g_dbus_method_invocation_return_value (invocation, NULL);
391     }
392     else if (g_strcmp0 (method_name, "SwitchToUser") == 0)
393     {
394         const gchar *username, *session_name;
395
396         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(ss)")))
397             return;
398
399         g_variant_get (parameters, "(&s&s)", &username, &session_name);
400         if (strcmp (session_name, "") == 0)
401             session_name = NULL;
402
403         seat_switch_to_user (seat, username, session_name);
404         g_dbus_method_invocation_return_value (invocation, NULL);
405     }
406     else if (g_strcmp0 (method_name, "SwitchToGuest") == 0)
407     {
408         const gchar *session_name;
409
410         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(s)")))
411             return;
412
413         g_variant_get (parameters, "(&s)", &session_name);
414         if (strcmp (session_name, "") == 0)
415             session_name = NULL;
416
417         seat_switch_to_guest (seat, session_name);
418         g_dbus_method_invocation_return_value (invocation, NULL);
419     }
420 }
421
422 static GVariant *
423 handle_session_get_property (GDBusConnection       *connection,
424                              const gchar           *sender,
425                              const gchar           *object_path,
426                              const gchar           *interface_name,
427                              const gchar           *property_name,
428                              GError               **error,
429                              gpointer               user_data)
430 {
431     Session *session = user_data;
432     BusEntry *entry;
433
434     entry = g_hash_table_lookup (session_bus_entries, session);
435     if (g_strcmp0 (property_name, "Seat") == 0)
436         return g_variant_new_object_path (entry ? entry->parent_path : "");
437     else if (g_strcmp0 (property_name, "UserName") == 0)
438         return g_variant_new_string (user_get_name (session_get_user (session)));
439
440     return NULL;
441 }
442
443 static void
444 handle_session_call (GDBusConnection       *connection,
445                      const gchar           *sender,
446                      const gchar           *object_path,
447                      const gchar           *interface_name,
448                      const gchar           *method_name,
449                      GVariant              *parameters,
450                      GDBusMethodInvocation *invocation,
451                      gpointer               user_data)
452 {
453 }
454
455 static BusEntry *
456 bus_entry_new (const gchar *path, const gchar *parent_path, const gchar *removed_signal)
457 {
458     BusEntry *entry;
459
460     entry = g_malloc0 (sizeof (BusEntry));
461     entry->path = g_strdup (path);
462     entry->parent_path = g_strdup (parent_path);
463     entry->removed_signal = g_strdup (removed_signal);
464
465     return entry;
466 }
467
468 static void
469 bus_entry_free (gpointer data)
470 {
471     BusEntry *entry = data;
472
473     g_dbus_connection_unregister_object (bus, entry->bus_id);
474
475     g_dbus_connection_emit_signal (bus,
476                                    NULL,
477                                    "/org/freedesktop/DisplayManager",
478                                    "org.freedesktop.DisplayManager",
479                                    entry->removed_signal,
480                                    g_variant_new ("(o)", entry->path),
481                                    NULL);
482
483     g_free (entry->path);
484     g_free (entry->parent_path);
485     g_free (entry->removed_signal);
486     g_free (entry);
487 }
488
489 static gboolean
490 start_session_cb (Display *display, Seat *seat)
491 {
492     Session *session;
493     BusEntry *seat_entry;
494     gchar *path;
495
496     session = display_get_session (display);
497
498     seat_entry = g_hash_table_lookup (seat_bus_entries, seat);
499     session_set_env (session, "XDG_SEAT_PATH", seat_entry->path);
500
501     path = g_strdup_printf ("/org/freedesktop/DisplayManager/Session%d", session_index);
502     session_index++;
503     session_set_env (session, "XDG_SESSION_PATH", path);
504     g_free (path);
505
506     return FALSE;
507 }
508
509 static void
510 session_stopped_cb (Session *session, Seat *seat)
511 {
512     g_signal_handlers_disconnect_matched (session, G_SIGNAL_MATCH_DATA, 0, 0, NULL, NULL, seat);
513     g_hash_table_remove (session_bus_entries, session);
514 }
515
516 static gboolean
517 session_started_cb (Display *display, Seat *seat)
518 {
519     static const GDBusInterfaceVTable session_vtable =
520     {
521         handle_session_call,
522         handle_session_get_property
523     };
524     Session *session;
525     BusEntry *seat_entry, *entry;
526
527     session = display_get_session (display);
528
529     g_signal_connect (session, "stopped", G_CALLBACK (session_stopped_cb), seat);
530
531     seat_entry = g_hash_table_lookup (seat_bus_entries, seat);
532     entry = bus_entry_new (session_get_env (session, "XDG_SESSION_PATH"), seat_entry ? seat_entry->path : NULL, "SessionRemoved");
533     g_hash_table_insert (session_bus_entries, g_object_ref (session), entry);
534
535     g_debug ("Registering session with bus path %s", entry->path);
536
537     entry->bus_id = g_dbus_connection_register_object (bus,
538                                                        entry->path,
539                                                        session_info->interfaces[0],
540                                                        &session_vtable,
541                                                        g_object_ref (session), g_object_unref,
542                                                        NULL);
543     g_dbus_connection_emit_signal (bus,
544                                    NULL,
545                                    "/org/freedesktop/DisplayManager",
546                                    "org.freedesktop.DisplayManager",
547                                    "SessionAdded",
548                                    g_variant_new ("(o)", entry->path),
549                                    NULL);
550
551     return FALSE;
552 }
553
554 static void
555 display_added_cb (Seat *seat, Display *display)
556 {
557     g_signal_connect (display, "start-session", G_CALLBACK (start_session_cb), seat);
558     g_signal_connect_after (display, "start-session", G_CALLBACK (session_started_cb), seat);
559 }
560
561 static void
562 seat_added_cb (DisplayManager *display_manager, Seat *seat)
563 {
564     static const GDBusInterfaceVTable seat_vtable =
565     {
566         handle_seat_call,
567         handle_seat_get_property
568     };
569     GList *link;
570     gchar *path;
571     BusEntry *entry;
572
573     g_signal_connect (seat, "display-added", G_CALLBACK (display_added_cb), NULL);
574     for (link = seat_get_displays (seat); link; link = link->next)
575         display_added_cb (seat, (Display *) link->data);
576
577     path = g_strdup_printf ("/org/freedesktop/DisplayManager/Seat%d", seat_index);
578     seat_index++;
579
580     entry = bus_entry_new (path, NULL, "SeatRemoved");
581     g_free (path);
582     g_hash_table_insert (seat_bus_entries, g_object_ref (seat), entry);
583
584     g_debug ("Registering seat with bus path %s", entry->path);
585
586     entry->bus_id = g_dbus_connection_register_object (bus,
587                                                        entry->path,
588                                                        seat_info->interfaces[0],
589                                                        &seat_vtable,
590                                                        g_object_ref (seat), g_object_unref,
591                                                        NULL);
592     g_dbus_connection_emit_signal (bus,
593                                    NULL,
594                                    "/org/freedesktop/DisplayManager",
595                                    "org.freedesktop.DisplayManager",
596                                    "SeatAdded",
597                                    g_variant_new ("(o)", entry->path),
598                                    NULL);
599 }
600
601 static void
602 seat_removed_cb (DisplayManager *display_manager, Seat *seat)
603 {
604     gboolean exit_on_failure;
605
606     exit_on_failure = seat_get_boolean_property (seat, "exit-on-failure");
607     g_hash_table_remove (seat_bus_entries, seat);
608
609     if (exit_on_failure)
610     {
611         g_debug ("Required seat has stopped");
612         exit_code = EXIT_FAILURE;
613         display_manager_stop (display_manager);
614     }
615 }
616
617 static void
618 bus_acquired_cb (GDBusConnection *connection,
619                  const gchar     *name,
620                  gpointer         user_data)
621 {
622     const gchar *display_manager_interface =
623         "<node>"
624         "  <interface name='org.freedesktop.DisplayManager'>"
625         "    <property name='Seats' type='ao' access='read'/>"
626         "    <property name='Sessions' type='ao' access='read'/>"
627         "    <method name='AddSeat'>"
628         "      <arg name='type' direction='in' type='s'/>"
629         "      <arg name='properties' direction='in' type='a(ss)'/>"
630         "      <arg name='seat' direction='out' type='o'/>"
631         "    </method>"
632         "    <method name='AddLocalXSeat'>"
633         "      <arg name='display-number' direction='in' type='i'/>"
634         "      <arg name='seat' direction='out' type='o'/>"
635         "    </method>"
636         "    <signal name='SeatAdded'>"
637         "      <arg name='seat' type='o'/>"
638         "    </signal>"
639         "    <signal name='SeatRemoved'>"
640         "      <arg name='seat' type='o'/>"
641         "    </signal>"
642         "    <signal name='SessionAdded'>"
643         "      <arg name='session' type='o'/>"
644         "    </signal>"
645         "    <signal name='SessionRemoved'>"
646         "      <arg name='session' type='o'/>"
647         "    </signal>"
648         "  </interface>"
649         "</node>";
650     static const GDBusInterfaceVTable display_manager_vtable =
651     {
652         handle_display_manager_call,
653         handle_display_manager_get_property
654     };
655     const gchar *seat_interface =
656         "<node>"
657         "  <interface name='org.freedesktop.DisplayManager.Seat'>"
658         "    <property name='CanSwitch' type='b' access='read'/>"
659         "    <property name='HasGuestAccount' type='b' access='read'/>"
660         "    <property name='Sessions' type='ao' access='read'/>"
661         "    <method name='SwitchToGreeter'/>"
662         "    <method name='SwitchToUser'>"
663         "      <arg name='username' direction='in' type='s'/>"
664         "      <arg name='session-name' direction='in' type='s'/>"
665         "    </method>"
666         "    <method name='SwitchToGuest'>"
667         "      <arg name='session-name' direction='in' type='s'/>"
668         "    </method>"
669         "  </interface>"
670         "</node>";
671     const gchar *session_interface =
672         "<node>"
673         "  <interface name='org.freedesktop.DisplayManager.Session'>"
674         "    <property name='Seat' type='o' access='read'/>"
675         "    <property name='UserName' type='s' access='read'/>"
676         "  </interface>"
677         "</node>";
678     GDBusNodeInfo *display_manager_info;
679     GList *link;
680
681     g_debug ("Acquired bus name %s", name);
682
683     bus = connection;
684
685     display_manager_info = g_dbus_node_info_new_for_xml (display_manager_interface, NULL);
686     g_assert (display_manager_info != NULL);
687     seat_info = g_dbus_node_info_new_for_xml (seat_interface, NULL);
688     g_assert (seat_info != NULL);
689     session_info = g_dbus_node_info_new_for_xml (session_interface, NULL);
690     g_assert (session_info != NULL);
691
692     bus_id = g_dbus_connection_register_object (connection,
693                                                 "/org/freedesktop/DisplayManager",
694                                                 display_manager_info->interfaces[0],
695                                                 &display_manager_vtable,
696                                                 NULL, NULL,
697                                                 NULL);
698     g_dbus_node_info_unref  (display_manager_info);
699
700     seat_bus_entries = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, bus_entry_free);
701     session_bus_entries = g_hash_table_new_full (g_direct_hash, g_direct_equal, g_object_unref, bus_entry_free);
702
703     g_signal_connect (display_manager, "seat-added", G_CALLBACK (seat_added_cb), NULL);
704     g_signal_connect (display_manager, "seat-removed", G_CALLBACK (seat_removed_cb), NULL);
705     for (link = display_manager_get_seats (display_manager); link; link = link->next)
706         seat_added_cb (display_manager, (Seat *) link->data);
707 }
708
709 static void
710 name_lost_cb (GDBusConnection *connection,
711               const gchar *name,
712               gpointer user_data)
713 {
714     if (connection)
715         g_printerr ("Failed to use bus name " LIGHTDM_BUS_NAME ", do you have appropriate permissions?\n");
716     else
717         g_printerr ("Failed to get D-Bus connection\n");
718
719     exit (EXIT_FAILURE);
720 }
721
722 static gchar *
723 path_make_absolute (gchar *path)
724 {
725     gchar *cwd, *abs_path;
726   
727     if (!path)
728         return NULL;
729
730     if (g_path_is_absolute (path))
731         return path;
732
733     cwd = g_get_current_dir ();
734     abs_path = g_build_filename (cwd, path, NULL);
735     g_free (path);
736
737     return abs_path;
738 }
739
740 static gboolean
741 xdmcp_session_cb (XDMCPServer *server, XDMCPSession *session)
742 {
743     SeatXDMCPSession *seat;
744     gboolean result;
745
746     seat = seat_xdmcp_session_new (session);
747     set_seat_properties (SEAT (seat), NULL);
748     result = display_manager_add_seat (display_manager, SEAT (seat));
749     g_object_unref (seat);
750
751     return result;
752 }
753
754 static void
755 vnc_connection_cb (VNCServer *server, GSocket *connection)
756 {
757     SeatXVNC *seat;
758
759     seat = seat_xvnc_new (connection);
760     set_seat_properties (SEAT (seat), NULL);
761     display_manager_add_seat (display_manager, SEAT (seat));
762     g_object_unref (seat);
763 }
764
765 int
766 main (int argc, char **argv)
767 {
768     FILE *pid_file;
769     GOptionContext *option_context;
770     gboolean result;
771     gchar **groups, **i, *dir;
772     gint n_seats = 0;
773     gboolean explicit_config = FALSE;
774     gboolean test_mode = FALSE;
775     gchar *pid_path = "/var/run/lightdm.pid";
776     gchar *xsessions_dir = NULL;
777     gchar *xgreeters_dir = NULL;
778     gchar *config_dir;
779     gchar *log_dir = NULL;
780     gchar *run_dir = NULL;
781     gchar *cache_dir = NULL;
782     gchar *default_log_dir = g_strdup (LOG_DIR);
783     gchar *default_run_dir = g_strdup (RUN_DIR);
784     gchar *default_cache_dir = g_strdup (CACHE_DIR);
785     gboolean show_version = FALSE;
786     GOptionEntry options[] = 
787     {
788         { "config", 'c', 0, G_OPTION_ARG_STRING, &config_path,
789           /* Help string for command line --config flag */
790           N_("Use configuration file"), "FILE" },
791         { "debug", 'd', 0, G_OPTION_ARG_NONE, &debug,
792           /* Help string for command line --debug flag */
793           N_("Print debugging messages"), NULL },
794         { "test-mode", 0, 0, G_OPTION_ARG_NONE, &test_mode,
795           /* Help string for command line --test-mode flag */
796           N_("Run as unprivileged user, skipping things that require root access"), NULL },
797         { "pid-file", 0, 0, G_OPTION_ARG_STRING, &pid_path,
798           /* Help string for command line --pid-file flag */
799           N_("File to write PID into"), "FILE" },
800         { "xsessions-dir", 0, 0, G_OPTION_ARG_STRING, &xsessions_dir,
801           /* Help string for command line --xsessions-dir flag */
802           N_("Directory to load X sessions from"), "DIRECTORY" },
803         { "xgreeters-dir", 0, 0, G_OPTION_ARG_STRING, &xgreeters_dir,
804           /* Help string for command line --xgreeters-dir flag */
805           N_("Directory to load X greeters from"), "DIRECTORY" },
806         { "log-dir", 0, 0, G_OPTION_ARG_STRING, &log_dir,
807           /* Help string for command line --log-dir flag */
808           N_("Directory to write logs to"), "DIRECTORY" },
809         { "run-dir", 0, 0, G_OPTION_ARG_STRING, &run_dir,
810           /* Help string for command line --run-dir flag */
811           N_("Directory to store running state"), "DIRECTORY" },
812         { "cache-dir", 0, 0, G_OPTION_ARG_STRING, &cache_dir,
813           /* Help string for command line --cache-dir flag */
814           N_("Directory to cache information"), "DIRECTORY" },
815         { "version", 'v', 0, G_OPTION_ARG_NONE, &show_version,
816           /* Help string for command line --version flag */
817           N_("Show release version"), NULL },
818         { NULL }
819     };
820     GError *error = NULL;
821
822     g_type_init ();
823     loop = g_main_loop_new (NULL, FALSE);
824
825     g_signal_connect (process_get_current (), "got-signal", G_CALLBACK (signal_cb), NULL);
826
827     option_context = g_option_context_new (/* Arguments and description for --help test */
828                                            _("- Display Manager"));
829     g_option_context_add_main_entries (option_context, options, GETTEXT_PACKAGE);
830     result = g_option_context_parse (option_context, &argc, &argv, &error);
831     if (error)
832         g_printerr ("%s\n", error->message);
833     g_clear_error (&error);
834     g_option_context_free (option_context);
835     if (!result)
836     {
837         g_printerr (/* Text printed out when an unknown command-line argument provided */
838                     _("Run '%s --help' to see a full list of available command line options."), argv[0]);
839         g_printerr ("\n");
840         return EXIT_FAILURE;
841     }
842
843     if (show_version)
844     {
845         /* NOTE: Is not translated so can be easily parsed */
846         g_printerr ("lightdm %s\n", VERSION);
847         return EXIT_SUCCESS;
848     }
849
850     if (config_path)
851     {
852         config_dir = g_path_get_basename (config_path);
853         config_dir = path_make_absolute (config_dir);
854         explicit_config = TRUE;
855     }
856     else
857     {
858         config_dir = g_strdup (CONFIG_DIR);
859         config_path = g_build_filename (config_dir, "lightdm.conf", NULL);
860     }
861     config_set_string (config_get_instance (), "LightDM", "config-directory", config_dir);
862     g_free (config_dir);
863
864     if (!test_mode && getuid () != 0)
865     {
866         g_printerr ("Only root can run Light Display Manager.  To run as a regular user for testing run with the --test-mode flag.\n");
867         return EXIT_FAILURE;
868     }
869
870     /* If running inside an X server use Xephyr for display */
871     if (getenv ("DISPLAY") && getuid () != 0)
872     {
873         gchar *xserver_path;
874
875         xserver_path = g_find_program_in_path ("Xephyr");
876         if (!xserver_path)
877         {
878             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");
879             return EXIT_FAILURE;
880         }
881         g_free (xserver_path);
882     }
883
884     /* Make sure the system binary directory (where the greeters are installed) is in the path */
885     if (test_mode)
886     {
887         const gchar *path = g_getenv ("PATH");
888         gchar *new_path;
889
890         if (path)
891             new_path = g_strdup_printf ("%s:%s", path, SBIN_DIR);
892         else
893             new_path = g_strdup (SBIN_DIR);
894         g_setenv ("PATH", new_path, TRUE);
895         g_free (new_path);
896     }
897
898     /* Write PID file */
899     pid_file = fopen (pid_path, "w");
900     if (pid_file)
901     {
902         fprintf (pid_file, "%d\n", getpid ());
903         fclose (pid_file);
904     }
905
906     /* Always use absolute directories as child processes may run from different locations */
907     xsessions_dir = path_make_absolute (xsessions_dir);
908     xgreeters_dir = path_make_absolute (xgreeters_dir);
909
910     /* If not running as root write output to directories we control */
911     if (getuid () != 0)
912     {
913         g_free (default_log_dir);
914         default_log_dir = g_build_filename (g_get_user_cache_dir (), "lightdm", "log", NULL);
915         g_free (default_run_dir);
916         default_run_dir = g_build_filename (g_get_user_cache_dir (), "lightdm", "run", NULL);
917         g_free (default_cache_dir);
918         default_cache_dir = g_build_filename (g_get_user_cache_dir (), "lightdm", "cache", NULL);
919     }
920
921     /* Load config file */
922     if (!config_load_from_file (config_get_instance (), config_path, &error))
923     {
924         gboolean is_empty;
925
926         is_empty = error && g_error_matches (error, G_FILE_ERROR, G_FILE_ERROR_NOENT);
927       
928         if (explicit_config || !is_empty)      
929         {
930             if (error)
931                 g_printerr ("Failed to load configuration from %s: %s\n", config_path, error->message);
932             exit (EXIT_FAILURE);
933         }
934     }
935     g_clear_error (&error);
936
937     /* Set default values */
938     if (!config_has_key (config_get_instance (), "LightDM", "start-default-seat"))
939         config_set_boolean (config_get_instance (), "LightDM", "start-default-seat", TRUE);
940     if (!config_has_key (config_get_instance (), "LightDM", "minimum-vt"))
941         config_set_integer (config_get_instance (), "LightDM", "minimum-vt", 7);
942     if (!config_has_key (config_get_instance (), "LightDM", "guest-account-script"))
943         config_set_string (config_get_instance (), "LightDM", "guest-account-script", "guest-account");
944     if (!config_has_key (config_get_instance (), "LightDM", "greeter-user"))
945         config_set_string (config_get_instance (), "LightDM", "greeter-user", GREETER_USER);
946     if (!config_has_key (config_get_instance (), "SeatDefaults", "type"))
947         config_set_string (config_get_instance (), "SeatDefaults", "type", "xlocal");
948     if (!config_has_key (config_get_instance (), "SeatDefaults", "xserver-command"))
949         config_set_string (config_get_instance (), "SeatDefaults", "xserver-command", "X");
950     if (!config_has_key (config_get_instance (), "SeatDefaults", "start-session"))
951         config_set_boolean (config_get_instance (), "SeatDefaults", "start-session", TRUE);
952     if (!config_has_key (config_get_instance (), "SeatDefaults", "allow-guest"))
953         config_set_boolean (config_get_instance (), "SeatDefaults", "allow-guest", TRUE);
954     if (!config_has_key (config_get_instance (), "SeatDefaults", "greeter-session"))
955         config_set_string (config_get_instance (), "SeatDefaults", "greeter-session", GREETER_SESSION);
956     if (!config_has_key (config_get_instance (), "SeatDefaults", "user-session"))
957         config_set_string (config_get_instance (), "SeatDefaults", "user-session", USER_SESSION);
958     if (!config_has_key (config_get_instance (), "SeatDefaults", "session-wrapper"))
959         config_set_string (config_get_instance (), "SeatDefaults", "session-wrapper", "lightdm-session");
960     if (!config_has_key (config_get_instance (), "LightDM", "log-directory"))
961         config_set_string (config_get_instance (), "LightDM", "log-directory", default_log_dir);
962     g_free (default_log_dir);
963     if (!config_has_key (config_get_instance (), "LightDM", "run-directory"))
964         config_set_string (config_get_instance (), "LightDM", "run-directory", default_run_dir);
965     g_free (default_run_dir);
966     if (!config_has_key (config_get_instance (), "LightDM", "cache-directory"))
967         config_set_string (config_get_instance (), "LightDM", "cache-directory", default_cache_dir);
968     g_free (default_cache_dir);
969     if (!config_has_key (config_get_instance (), "LightDM", "xsessions-directory"))
970         config_set_string (config_get_instance (), "LightDM", "xsessions-directory", XSESSIONS_DIR);
971     if (!config_has_key (config_get_instance (), "LightDM", "xgreeters-directory"))
972         config_set_string (config_get_instance (), "LightDM", "xgreeters-directory", XGREETERS_DIR);
973
974     /* Override defaults */
975     if (log_dir)
976         config_set_string (config_get_instance (), "LightDM", "log-directory", log_dir);
977     g_free (log_dir);
978     if (run_dir)
979         config_set_string (config_get_instance (), "LightDM", "run-directory", run_dir);
980     g_free (run_dir);
981     if (cache_dir)
982         config_set_string (config_get_instance (), "LightDM", "cache-directory", cache_dir);
983     g_free (cache_dir);
984     if (xsessions_dir)
985         config_set_string (config_get_instance (), "LightDM", "xsessions-directory", xsessions_dir);
986     g_free (xsessions_dir);
987     if (xgreeters_dir)
988         config_set_string (config_get_instance (), "LightDM", "xgreeters-directory", xgreeters_dir);
989     g_free (xgreeters_dir);
990
991     /* Create run and cache directories */
992     dir = config_get_string (config_get_instance (), "LightDM", "log-directory");
993     g_mkdir_with_parents (dir, S_IRWXU | S_IXGRP | S_IXOTH);
994     g_free (dir);
995     dir = config_get_string (config_get_instance (), "LightDM", "run-directory");
996     g_mkdir_with_parents (dir, S_IRWXU | S_IXGRP | S_IXOTH);
997     g_free (dir);
998     dir = config_get_string (config_get_instance (), "LightDM", "cache-directory");
999     g_mkdir_with_parents (dir, S_IRWXU | S_IXGRP | S_IXOTH);
1000     g_free (dir);
1001
1002     log_init ();
1003
1004     g_debug ("Starting Light Display Manager %s, UID=%i PID=%i", VERSION, getuid (), getpid ());
1005
1006     g_debug ("Loaded configuration from %s", config_path);
1007     g_free (config_path);
1008
1009     g_debug ("Using D-Bus name %s", LIGHTDM_BUS_NAME);
1010     bus_id = g_bus_own_name (getuid () == 0 ? G_BUS_TYPE_SYSTEM : G_BUS_TYPE_SESSION,
1011                              LIGHTDM_BUS_NAME,
1012                              G_BUS_NAME_OWNER_FLAGS_NONE,
1013                              bus_acquired_cb,
1014                              NULL,
1015                              name_lost_cb,
1016                              NULL,
1017                              NULL);
1018
1019     if (getuid () != 0)
1020         g_debug ("Running in user mode");
1021     if (getenv ("DISPLAY"))
1022         g_debug ("Using Xephyr for X servers");
1023
1024     display_manager = display_manager_new ();
1025     g_signal_connect (display_manager, "stopped", G_CALLBACK (display_manager_stopped_cb), NULL);
1026
1027     /* Load the static display entries */
1028     groups = config_get_groups (config_get_instance ());
1029     for (i = groups; *i; i++)
1030     {
1031         gchar *config_section = *i;
1032         gchar *type;
1033         Seat *seat;
1034
1035         if (!g_str_has_prefix (config_section, "Seat:"))
1036             continue;
1037
1038         g_debug ("Loading seat %s", config_section);
1039         type = config_get_string (config_get_instance (), config_section, "type");
1040         if (!type)
1041             type = config_get_string (config_get_instance (), "SeatDefaults", "type");
1042         seat = seat_new (type);
1043         g_free (type);
1044         if (seat)
1045         {
1046             set_seat_properties (seat, config_section);
1047             display_manager_add_seat (display_manager, seat);
1048             g_object_unref (seat);
1049             n_seats++;
1050         }
1051         else
1052             g_warning ("Failed to create seat %s", config_section);
1053     }
1054     g_strfreev (groups);
1055
1056     /* If no seats start a default one */
1057     if (n_seats == 0 && config_get_boolean (config_get_instance (), "LightDM", "start-default-seat"))
1058     {
1059         gchar *type;
1060         Seat *seat;
1061
1062         g_debug ("Adding default seat");
1063
1064         type = config_get_string (config_get_instance (), "SeatDefaults", "type");
1065         seat = seat_new (type);
1066         g_free (type);
1067         if (seat)
1068         {
1069             set_seat_properties (seat, NULL);
1070             seat_set_property (seat, "exit-on-failure", "true");
1071             display_manager_add_seat (display_manager, seat);
1072             g_object_unref (seat);
1073         }
1074         else
1075             g_warning ("Failed to create default seat");
1076     }
1077
1078     display_manager_start (display_manager);
1079
1080     /* Start the XDMCP server */
1081     if (config_get_boolean (config_get_instance (), "XDMCPServer", "enabled"))
1082     {
1083         gchar *key_name, *key = NULL;
1084
1085         xdmcp_server = xdmcp_server_new ();
1086         if (config_has_key (config_get_instance (), "XDMCPServer", "port"))
1087         {
1088             gint port;
1089             port = config_get_integer (config_get_instance (), "XDMCPServer", "port");
1090             if (port > 0)
1091                 xdmcp_server_set_port (xdmcp_server, port);
1092         }
1093         g_signal_connect (xdmcp_server, "new-session", G_CALLBACK (xdmcp_session_cb), NULL);
1094
1095         key_name = config_get_string (config_get_instance (), "XDMCPServer", "key");
1096         if (key_name)
1097         {
1098             gchar *dir, *path;
1099             GKeyFile *keys;
1100             gboolean result;
1101             GError *error = NULL;
1102
1103             dir = config_get_string (config_get_instance (), "LightDM", "config-directory");
1104             path = g_build_filename (dir, "keys.conf", NULL);
1105             g_free (dir);
1106
1107             keys = g_key_file_new ();
1108             result = g_key_file_load_from_file (keys, path, G_KEY_FILE_NONE, &error);
1109             if (error)
1110                 g_debug ("Error getting key %s", error->message);
1111             g_clear_error (&error);
1112
1113             if (result)
1114             {
1115                 if (g_key_file_has_key (keys, "keyring", key_name, NULL))
1116                     key = g_key_file_get_string (keys, "keyring", key_name, NULL);
1117                 else
1118                     g_debug ("Key %s not defined", key_name);
1119             }
1120             g_free (path);
1121             g_key_file_free (keys);
1122         }
1123         if (key)
1124             xdmcp_server_set_key (xdmcp_server, key);
1125         g_free (key_name);
1126         g_free (key);
1127
1128         g_debug ("Starting XDMCP server on UDP/IP port %d", xdmcp_server_get_port (xdmcp_server));
1129         xdmcp_server_start (xdmcp_server);
1130     }
1131
1132     /* Start the VNC server */
1133     if (config_get_boolean (config_get_instance (), "VNCServer", "enabled"))
1134     {
1135         gchar *path;
1136
1137         path = g_find_program_in_path ("Xvnc");
1138         if (path)
1139         {
1140             vnc_server = vnc_server_new ();
1141             if (config_has_key (config_get_instance (), "VNCServer", "port"))
1142             {
1143                 gint port;
1144                 port = config_get_integer (config_get_instance (), "VNCServer", "port");
1145                 if (port > 0)
1146                     vnc_server_set_port (vnc_server, port);
1147             }
1148             g_signal_connect (vnc_server, "new-connection", G_CALLBACK (vnc_connection_cb), NULL);
1149
1150             g_debug ("Starting VNC server on TCP/IP port %d", vnc_server_get_port (vnc_server));
1151             vnc_server_start (vnc_server);
1152
1153             g_free (path);
1154         }
1155         else
1156             g_warning ("Can't start VNC server, Xvn is not in the path");
1157     }
1158
1159     g_main_loop_run (loop);
1160
1161     return EXIT_SUCCESS;
1162 }