chiark / gitweb /
localed: add SetX11Keyboard() and SetVConsoleKeyboard() bus calls
[elogind.git] / src / localed.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2011 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <dbus/dbus.h>
23
24 #include <errno.h>
25 #include <string.h>
26 #include <unistd.h>
27
28 #include "util.h"
29 #include "strv.h"
30 #include "dbus-common.h"
31 #include "polkit.h"
32 #include "def.h"
33
34 #define INTERFACE                                                       \
35         " <interface name=\"org.freedesktop.locale1\">\n"               \
36         "  <property name=\"Locale\" type=\"as\" access=\"read\"/>\n"   \
37         "  <property name=\"VConsoleKeymap\" type=\"s\" access=\"read\"/>\n" \
38         "  <property name=\"VConsoleKeymapToggle\" type=\"s\" access=\"read\"/>\n" \
39         "  <property name=\"X11Layout\" type=\"s\" access=\"read\"/>\n" \
40         "  <property name=\"X11Model\" type=\"s\" access=\"read\"/>\n"  \
41         "  <property name=\"X11Variant\" type=\"s\" access=\"read\"/>\n" \
42         "  <property name=\"X11Options\" type=\"s\" access=\"read\"/>\n" \
43         "  <method name=\"SetLocale\">\n"                               \
44         "   <arg name=\"locale\" type=\"as\" direction=\"in\"/>\n"      \
45         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
46         "  </method>\n"                                                 \
47         "  <method name=\"SetVConsoleKeyboard\">\n"                      \
48         "   <arg name=\"keymap\" type=\"s\" direction=\"in\"/>\n"       \
49         "   <arg name=\"keymap_toggle\" type=\"s\" direction=\"in\"/>\n" \
50         "   <arg name=\"convert\" type=\"b\" direction=\"in\"/>\n"      \
51         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
52         "  </method>\n"                                                 \
53         "  <method name=\"SetX11Keyboard\">\n"                          \
54         "   <arg name=\"layout\" type=\"s\" direction=\"in\"/>\n"       \
55         "   <arg name=\"model\" type=\"s\" direction=\"in\"/>\n"        \
56         "   <arg name=\"variant\" type=\"s\" direction=\"in\"/>\n"      \
57         "   <arg name=\"options\" type=\"s\" direction=\"in\"/>\n"      \
58         "   <arg name=\"convert\" type=\"b\" direction=\"in\"/>\n"      \
59         "   <arg name=\"user_interaction\" type=\"b\" direction=\"in\"/>\n" \
60         "  </method>\n"                                                 \
61         " </interface>\n"
62
63 #define INTROSPECTION                                                   \
64         DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE                       \
65         "<node>\n"                                                      \
66         INTERFACE                                                       \
67         BUS_PROPERTIES_INTERFACE                                        \
68         BUS_INTROSPECTABLE_INTERFACE                                    \
69         BUS_PEER_INTERFACE                                              \
70         "</node>\n"
71
72 #define INTERFACES_LIST                         \
73         BUS_GENERIC_INTERFACES_LIST             \
74         "org.freedesktop.locale1\0"
75
76 const char locale_interface[] _introspect_("locale1") = INTERFACE;
77
78 enum {
79         /* We don't list LC_ALL here on purpose. People should be
80          * using LANG instead. */
81
82         PROP_LANG,
83         PROP_LANGUAGE,
84         PROP_LC_CTYPE,
85         PROP_LC_NUMERIC,
86         PROP_LC_TIME,
87         PROP_LC_COLLATE,
88         PROP_LC_MONETARY,
89         PROP_LC_MESSAGES,
90         PROP_LC_PAPER,
91         PROP_LC_NAME,
92         PROP_LC_ADDRESS,
93         PROP_LC_TELEPHONE,
94         PROP_LC_MEASUREMENT,
95         PROP_LC_IDENTIFICATION,
96         _PROP_MAX
97 };
98
99 static const char * const names[_PROP_MAX] = {
100         [PROP_LANG] = "LANG",
101         [PROP_LANGUAGE] = "LANGUAGE",
102         [PROP_LC_CTYPE] = "LC_CTYPE",
103         [PROP_LC_NUMERIC] = "LC_NUMERIC",
104         [PROP_LC_TIME] = "LC_TIME",
105         [PROP_LC_COLLATE] = "LC_COLLATE",
106         [PROP_LC_MONETARY] = "LC_MONETARY",
107         [PROP_LC_MESSAGES] = "LC_MESSAGES",
108         [PROP_LC_PAPER] = "LC_PAPER",
109         [PROP_LC_NAME] = "LC_NAME",
110         [PROP_LC_ADDRESS] = "LC_ADDRESS",
111         [PROP_LC_TELEPHONE] = "LC_TELEPHONE",
112         [PROP_LC_MEASUREMENT] = "LC_MEASUREMENT",
113         [PROP_LC_IDENTIFICATION] = "LC_IDENTIFICATION"
114 };
115
116 static char *data[_PROP_MAX] = {
117         NULL,
118         NULL,
119         NULL,
120         NULL,
121         NULL,
122         NULL,
123         NULL,
124         NULL,
125         NULL,
126         NULL,
127         NULL,
128         NULL,
129         NULL
130 };
131
132 static char *x11_layout = NULL, *x11_model = NULL, *x11_variant = NULL, *x11_options = NULL;
133 static char *vc_keymap = NULL, *vc_keymap_toggle = NULL;
134
135 static usec_t remain_until = 0;
136
137 static int free_and_set(char **s, const char *v) {
138         int r;
139         char *t;
140
141         assert(s);
142
143         r = strdup_or_null(isempty(v) ? NULL : v, &t);
144         if (r < 0)
145                 return r;
146
147         free(*s);
148         *s = t;
149
150         return 0;
151 }
152
153 static void free_data_locale(void) {
154         int p;
155
156         for (p = 0; p < _PROP_MAX; p++) {
157                 free(data[p]);
158                 data[p] = NULL;
159         }
160 }
161
162 static void free_data_x11(void) {
163         free(x11_layout);
164         free(x11_model);
165         free(x11_variant);
166         free(x11_options);
167
168         x11_layout = x11_model = x11_variant = x11_options = NULL;
169 }
170
171 static void free_data_vconsole(void) {
172         free(vc_keymap);
173         free(vc_keymap_toggle);
174
175         vc_keymap = vc_keymap_toggle = NULL;
176 }
177
178 static void simplify(void) {
179         int p;
180
181         for (p = 1; p < _PROP_MAX; p++)
182                 if (isempty(data[p]) || streq_ptr(data[PROP_LANG], data[p])) {
183                         free(data[p]);
184                         data[p] = NULL;
185                 }
186 }
187
188 static int read_data_locale(void) {
189         int r;
190
191         free_data_locale();
192
193         r = parse_env_file("/etc/locale.conf", NEWLINE,
194                            "LANG",              &data[PROP_LANG],
195                            "LANGUAGE",          &data[PROP_LANGUAGE],
196                            "LC_CTYPE",          &data[PROP_LC_CTYPE],
197                            "LC_NUMERIC",        &data[PROP_LC_NUMERIC],
198                            "LC_TIME",           &data[PROP_LC_TIME],
199                            "LC_COLLATE",        &data[PROP_LC_COLLATE],
200                            "LC_MONETARY",       &data[PROP_LC_MONETARY],
201                            "LC_MESSAGES",       &data[PROP_LC_MESSAGES],
202                            "LC_PAPER",          &data[PROP_LC_PAPER],
203                            "LC_NAME",           &data[PROP_LC_NAME],
204                            "LC_ADDRESS",        &data[PROP_LC_ADDRESS],
205                            "LC_TELEPHONE",      &data[PROP_LC_TELEPHONE],
206                            "LC_MEASUREMENT",    &data[PROP_LC_MEASUREMENT],
207                            "LC_IDENTIFICATION", &data[PROP_LC_IDENTIFICATION],
208                            NULL);
209
210         if (r == -ENOENT) {
211                 int p;
212
213                 /* Fill in what we got passed from systemd. */
214
215                 for (p = 0; p < _PROP_MAX; p++) {
216                         char *e, *d;
217
218                         assert(names[p]);
219
220                         e = getenv(names[p]);
221                         if (e) {
222                                 d = strdup(e);
223                                 if (!d)
224                                         return -ENOMEM;
225                         } else
226                                 d = NULL;
227
228                         free(data[p]);
229                         data[p] = d;
230                 }
231
232                 r = 0;
233         }
234
235         simplify();
236         return r;
237 }
238
239 static void free_data(void) {
240         free_data_locale();
241         free_data_vconsole();
242         free_data_x11();
243 }
244
245 static int read_data_vconsole(void) {
246         int r;
247
248         free_data_vconsole();
249
250         r = parse_env_file("/etc/vconsole.conf", NEWLINE,
251                            "KEYMAP",        &vc_keymap,
252                            "KEYMAP_TOGGLE", &vc_keymap_toggle,
253                            NULL);
254
255         if (r < 0 && r != -ENOENT)
256                 return r;
257
258         return 0;
259 }
260
261 static int read_data_x11(void) {
262         FILE *f;
263         char line[LINE_MAX];
264         bool in_section = false;
265
266         free_data_x11();
267
268         f = fopen("/etc/X11/xorg.conf.d/00-keyboard.conf", "re");
269         if (!f) {
270                 if (errno == ENOENT) {
271
272 #ifdef TARGET_FEDORA
273                         f = fopen("/etc/X11/xorg.conf.d/00-system-setup-keyboard.conf", "re");
274                         if (!f) {
275                                 if (errno == ENOENT)
276                                         return 0;
277                                 else
278                                         return -errno;
279                         }
280 #else
281                         return 0;
282 #endif
283
284                 } else
285                           return -errno;
286         }
287
288         while (fgets(line, sizeof(line), f)) {
289                 char *l;
290
291                 char_array_0(line);
292                 l = strstrip(line);
293
294                 if (l[0] == 0 || l[0] == '#')
295                         continue;
296
297                 if (in_section && first_word(l, "Option")) {
298                         char **a;
299
300                         a = strv_split_quoted(l);
301                         if (!a) {
302                                 fclose(f);
303                                 return -ENOMEM;
304                         }
305
306                         if (strv_length(a) == 3) {
307
308                                 if (streq(a[1], "XkbLayout")) {
309                                         free(x11_layout);
310                                         x11_layout = a[2];
311                                         a[2] = NULL;
312                                 } else if (streq(a[1], "XkbModel")) {
313                                         free(x11_model);
314                                         x11_model = a[2];
315                                         a[2] = NULL;
316                                 } else if (streq(a[1], "XkbVariant")) {
317                                         free(x11_variant);
318                                         x11_variant = a[2];
319                                         a[2] = NULL;
320                                 } else if (streq(a[1], "XkbOptions")) {
321                                         free(x11_options);
322                                         x11_options = a[2];
323                                         a[2] = NULL;
324                                 }
325                         }
326
327                         strv_free(a);
328
329                 } else if (!in_section && first_word(l, "Section")) {
330                         char **a;
331
332                         a = strv_split_quoted(l);
333                         if (!a) {
334                                 fclose(f);
335                                 return -ENOMEM;
336                         }
337
338                         if (strv_length(a) == 2 && streq(a[1], "InputClass"))
339                                 in_section = true;
340
341                         strv_free(a);
342                 } else if (in_section && first_word(l, "EndSection"))
343                         in_section = false;
344         }
345
346         fclose(f);
347
348         return 0;
349 }
350
351 static int read_data(void) {
352         int r, q, p;
353
354         r = read_data_locale();
355         q = read_data_vconsole();
356         p = read_data_x11();
357
358         return r < 0 ? r : q < 0 ? q : p;
359 }
360
361 static int write_data_locale(void) {
362         int r, p;
363         char **l = NULL;
364
365         r = load_env_file("/etc/locale.conf", &l);
366         if (r < 0 && r != -ENOENT)
367                 return r;
368
369         for (p = 0; p < _PROP_MAX; p++) {
370                 char *t, **u;
371
372                 assert(names[p]);
373
374                 if (isempty(data[p])) {
375                         l = strv_env_unset(l, names[p]);
376                         continue;
377                 }
378
379                 if (asprintf(&t, "%s=%s", names[p], data[p]) < 0) {
380                         strv_free(l);
381                         return -ENOMEM;
382                 }
383
384                 u = strv_env_set(l, t);
385                 free(t);
386                 strv_free(l);
387
388                 if (!u)
389                         return -ENOMEM;
390
391                 l = u;
392         }
393
394         if (strv_isempty(l)) {
395                 strv_free(l);
396
397                 if (unlink("/etc/locale.conf") < 0)
398                         return errno == ENOENT ? 0 : -errno;
399
400                 return 0;
401         }
402
403         r = write_env_file("/etc/locale.conf", l);
404         strv_free(l);
405
406         return r;
407 }
408
409 static void push_data(DBusConnection *bus) {
410         char **l_set = NULL, **l_unset = NULL, **t;
411         int c_set = 0, c_unset = 0, p;
412         DBusError error;
413         DBusMessage *m = NULL, *reply = NULL;
414         DBusMessageIter iter, sub;
415
416         dbus_error_init(&error);
417
418         assert(bus);
419
420         l_set = new0(char*, _PROP_MAX);
421         l_unset = new0(char*, _PROP_MAX);
422         if (!l_set || !l_unset) {
423                 log_error("Out of memory");
424                 goto finish;
425         }
426
427         for (p = 0; p < _PROP_MAX; p++) {
428                 assert(names[p]);
429
430                 if (isempty(data[p]))
431                         l_unset[c_set++] = (char*) names[p];
432                 else {
433                         char *s;
434
435                         if (asprintf(&s, "%s=%s", names[p], data[p]) < 0) {
436                                 log_error("Out of memory");
437                                 goto finish;
438                         }
439
440                         l_set[c_unset++] = s;
441                 }
442         }
443
444         assert(c_set + c_unset == _PROP_MAX);
445         m = dbus_message_new_method_call("org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "UnsetAndSetEnvironment");
446         if (!m) {
447                 log_error("Could not allocate message.");
448                 goto finish;
449         }
450
451         dbus_message_iter_init_append(m, &iter);
452
453         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
454                 log_error("Out of memory.");
455                 goto finish;
456         }
457
458         STRV_FOREACH(t, l_unset)
459                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, t)) {
460                         log_error("Out of memory.");
461                         goto finish;
462                 }
463
464         if (!dbus_message_iter_close_container(&iter, &sub) ||
465             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub)) {
466                 log_error("Out of memory.");
467                 goto finish;
468         }
469
470         STRV_FOREACH(t, l_set)
471                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, t)) {
472                         log_error("Out of memory.");
473                         goto finish;
474                 }
475
476         if (!dbus_message_iter_close_container(&iter, &sub)) {
477                 log_error("Out of memory.");
478                 goto finish;
479         }
480
481         reply = dbus_connection_send_with_reply_and_block(bus, m, -1, &error);
482         if (!reply) {
483                 log_error("Failed to set locale information: %s", bus_error_message(&error));
484                 goto finish;
485         }
486
487 finish:
488         if (m)
489                 dbus_message_unref(m);
490
491         if (reply)
492                 dbus_message_unref(reply);
493
494         dbus_error_free(&error);
495
496         strv_free(l_set);
497         free(l_unset);
498 }
499
500 static int write_data_vconsole(void) {
501         int r;
502         char **l = NULL;
503
504         r = load_env_file("/etc/vconsole.conf", &l);
505         if (r < 0 && r != -ENOENT)
506                 return r;
507
508         if (isempty(vc_keymap))
509                 l = strv_env_unset(l, "KEYMAP");
510         else {
511                 char *s, **u;
512
513                 s = strappend("KEYMAP=", vc_keymap);
514                 if (!s) {
515                         strv_free(l);
516                         return -ENOMEM;
517                 }
518
519                 u = strv_env_set(l, s);
520                 free(s);
521                 strv_free(l);
522
523                 if (!u)
524                         return -ENOMEM;
525
526                 l = u;
527         }
528
529         if (isempty(vc_keymap_toggle))
530                 l = strv_env_unset(l, "KEYMAP_TOGGLE");
531         else  {
532                 char *s, **u;
533
534                 s = strappend("KEYMAP_TOGGLE=", vc_keymap_toggle);
535                 if (!s) {
536                         strv_free(l);
537                         return -ENOMEM;
538                 }
539
540                 u = strv_env_set(l, s);
541                 free(s);
542                 strv_free(l);
543
544                 if (!u)
545                         return -ENOMEM;
546
547                 l = u;
548         }
549
550         if (strv_isempty(l)) {
551                 strv_free(l);
552
553                 if (unlink("/etc/vconsole.conf") < 0)
554                         return errno == ENOENT ? 0 : -errno;
555
556                 return 0;
557         }
558
559         r = write_env_file("/etc/vconsole.conf", l);
560         strv_free(l);
561
562         return r;
563 }
564
565 static int write_data_x11(void) {
566         FILE *f;
567         char *temp_path;
568         int r;
569
570         if (isempty(x11_layout) &&
571             isempty(x11_model) &&
572             isempty(x11_variant) &&
573             isempty(x11_options)) {
574
575 #ifdef TARGET_FEDORA
576                 unlink("/etc/X11/xorg.conf.d/00-system-setup-keyboard.conf");
577 #endif
578
579                 if (unlink("/etc/X11/xorg.conf.d/00-keyboard.conf") < 0)
580                         return errno == ENOENT ? 0 : -errno;
581
582                 return 0;
583         }
584
585         mkdir_parents("/etc/X11/xorg.conf.d", 0755);
586
587         r = fopen_temporary("/etc/X11/xorg.conf.d/00-keyboard.conf", &f, &temp_path);
588         if (r < 0)
589                 return r;
590
591         fchmod(fileno(f), 0644);
592
593         fputs("# Read and parsed by systemd-localed. It's probably wise not to edit this file\n"
594               "# manually too freely.\n"
595               "Section \"InputClass\"\n"
596               "        Identifier \"system-keyboard\"\n"
597               "        MatchIsKeyboard \"on\"\n", f);
598
599         if (!isempty(x11_layout))
600                 fprintf(f, "        Option \"XkbLayout\" \"%s\"\n", x11_layout);
601
602         if (!isempty(x11_model))
603                 fprintf(f, "        Option \"XkbModel\" \"%s\"\n", x11_model);
604
605         if (!isempty(x11_variant))
606                 fprintf(f, "        Option \"XkbVariant\" \"%s\"\n", x11_variant);
607
608         if (!isempty(x11_options))
609                 fprintf(f, "        Option \"XkbOptions\" \"%s\"\n", x11_options);
610
611         fputs("EndSection\n", f);
612         fflush(f);
613
614         if (ferror(f) || rename(temp_path, "/etc/X11/xorg.conf.d/00-keyboard.conf") < 0) {
615                 r = -errno;
616                 unlink("/etc/X11/xorg.conf.d/00-keyboard.conf");
617                 unlink(temp_path);
618         } else {
619
620 #ifdef TARGET_FEDORA
621                 unlink("/etc/X11/xorg.conf.d/00-system-setup-keyboard.conf");
622 #endif
623
624                 r = 0;
625         }
626
627         fclose(f);
628         free(temp_path);
629
630         return r;
631 }
632
633 static int load_vconsole_keymap(DBusConnection *bus, DBusError *error) {
634         DBusMessage *m = NULL, *reply = NULL;
635         const char *name = "systemd-vconsole-setup.service", *mode = "replace";
636         int r;
637         DBusError _error;
638
639         assert(bus);
640
641         if (!error) {
642                 dbus_error_init(&_error);
643                 error = &_error;
644         }
645
646         m = dbus_message_new_method_call(
647                         "org.freedesktop.systemd1",
648                         "/org/freedesktop/systemd1",
649                         "org.freedesktop.systemd1.Manager",
650                         "RestartUnit");
651         if (!m) {
652                 log_error("Could not allocate message.");
653                 r = -ENOMEM;
654                 goto finish;
655         }
656
657         if (!dbus_message_append_args(m,
658                                       DBUS_TYPE_STRING, &name,
659                                       DBUS_TYPE_STRING, &mode,
660                                       DBUS_TYPE_INVALID)) {
661                 log_error("Could not append arguments to message.");
662                 r = -ENOMEM;
663                 goto finish;
664         }
665
666         reply = dbus_connection_send_with_reply_and_block(bus, m, -1, error);
667         if (!reply) {
668                 log_error("Failed to issue method call: %s", bus_error_message(error));
669                 r = -EIO;
670                 goto finish;
671         }
672
673         r = 0;
674
675 finish:
676         if (m)
677                 dbus_message_unref(m);
678
679         if (reply)
680                 dbus_message_unref(reply);
681
682         if (error == &_error)
683                 dbus_error_free(error);
684
685         return r;
686 }
687
688 static char *strnulldash(const char *s) {
689         return s == NULL || *s == 0 || (s[0] == '-' && s[1] == 0) ? NULL : (char*) s;
690 }
691
692 static int read_next_mapping(FILE *f, unsigned *n, char ***a) {
693         assert(f);
694         assert(n);
695         assert(a);
696
697         for (;;) {
698                 char line[LINE_MAX];
699                 char *l, **b;
700
701                 errno = 0;
702                 if (!fgets(line, sizeof(line), f)) {
703
704                         if (ferror(f))
705                                 return errno ? -errno : -EIO;
706
707                         return 0;
708                 }
709
710                 (*n) ++;
711
712                 l = strstrip(line);
713                 if (l[0] == 0 || l[0] == '#')
714                         continue;
715
716                 b = strv_split_quoted(l);
717                 if (!b)
718                         return -ENOMEM;
719
720                 if (strv_length(b) < 5) {
721                         log_error("Invalid line "SYSTEMD_KBD_MODEL_MAP":%u, ignoring.", *n);
722                         strv_free(b);
723                         continue;
724
725                 }
726
727                 *a = b;
728                 return 1;
729         }
730 }
731
732 static int convert_vconsole_to_x11(DBusConnection *connection) {
733         bool modified = false;
734
735         assert(connection);
736
737         if (isempty(vc_keymap)) {
738
739                 modified =
740                         !isempty(x11_layout) ||
741                         !isempty(x11_model) ||
742                         !isempty(x11_variant) ||
743                         !isempty(x11_options);
744
745                 free_data_x11();
746         } else {
747                 FILE *f;
748                 unsigned n = 0;
749
750                 f = fopen(SYSTEMD_KBD_MODEL_MAP, "re");
751                 if (!f)
752                         return -errno;
753
754                 for (;;) {
755                         char **a;
756                         int r;
757
758                         r = read_next_mapping(f, &n, &a);
759                         if (r < 0) {
760                                 fclose(f);
761                                 return r;
762                         }
763
764                         if (r == 0)
765                                 break;
766
767                         if (!streq(vc_keymap, a[0])) {
768                                 strv_free(a);
769                                 continue;
770                         }
771
772                         if (!streq_ptr(x11_layout, strnulldash(a[1])) ||
773                             !streq_ptr(x11_model, strnulldash(a[2])) ||
774                             !streq_ptr(x11_variant, strnulldash(a[3])) ||
775                             !streq_ptr(x11_options, strnulldash(a[4]))) {
776
777                                 if (free_and_set(&x11_layout, strnulldash(a[1])) < 0 ||
778                                     free_and_set(&x11_model, strnulldash(a[2])) < 0 ||
779                                     free_and_set(&x11_variant, strnulldash(a[3])) < 0 ||
780                                     free_and_set(&x11_options, strnulldash(a[4])) < 0) {
781                                         strv_free(a);
782                                         fclose(f);
783                                         return -ENOMEM;
784                                 }
785
786                                 modified = true;
787                         }
788
789                         strv_free(a);
790                         break;
791                 }
792
793                 fclose(f);
794         }
795
796         if (modified) {
797                 dbus_bool_t b;
798                 DBusMessage *changed;
799                 int r;
800
801                 r = write_data_x11();
802                 if (r < 0)
803                         log_error("Failed to set X11 keyboard layout: %s", strerror(-r));
804
805                 changed = bus_properties_changed_new(
806                                 "/org/freedesktop/locale1",
807                                 "org.freedesktop.locale1",
808                                 "X11Layout\0"
809                                 "X11Model\0"
810                                 "X11Variant\0"
811                                 "X11Options\0");
812
813                 if (!changed)
814                         return -ENOMEM;
815
816                 b = dbus_connection_send(connection, changed, NULL);
817                 dbus_message_unref(changed);
818
819                 if (!b)
820                         return -ENOMEM;
821         }
822
823         return 0;
824 }
825
826 static int convert_x11_to_vconsole(DBusConnection *connection) {
827         bool modified = false;
828
829         assert(connection);
830
831         if (isempty(x11_layout)) {
832
833                 modified =
834                         !isempty(vc_keymap) ||
835                         !isempty(vc_keymap_toggle);
836
837                 free_data_x11();
838         } else {
839                 FILE *f;
840                 unsigned n = 0;
841                 unsigned best_matching = 0;
842                 char *new_keymap = NULL;
843
844                 f = fopen(SYSTEMD_KBD_MODEL_MAP, "re");
845                 if (!f)
846                         return -errno;
847
848                 for (;;) {
849                         char **a;
850                         unsigned matching = 0;
851                         int r;
852
853                         r = read_next_mapping(f, &n, &a);
854                         if (r < 0) {
855                                 fclose(f);
856                                 return r;
857                         }
858
859                         if (r == 0)
860                                 break;
861
862                         /* Determine how well matching this entry is */
863                         if (streq_ptr(x11_layout, a[1])) {
864                                 matching ++;
865
866                                 if (streq_ptr(x11_model, a[2])) {
867                                         matching++;
868
869                                         if (streq_ptr(x11_variant, a[3])) {
870                                                 matching++;
871
872                                                 if (streq_ptr(x11_options, a[4]))
873                                                         matching++;
874                                         }
875                                 }
876                         }
877
878                         /* The best matching entry so far, then let's
879                          * save that */
880                         if (matching > best_matching) {
881                                 best_matching = matching;
882
883                                 free(new_keymap);
884                                 new_keymap = strdup(a[0]);
885
886                                 if (!new_keymap) {
887                                         strv_free(a);
888                                         fclose(f);
889                                         return -ENOMEM;
890                                 }
891                         }
892
893                         strv_free(a);
894                 }
895
896                 fclose(f);
897
898                 if (!streq_ptr(vc_keymap, new_keymap)) {
899                         free(vc_keymap);
900                         vc_keymap = new_keymap;
901
902                         free(vc_keymap_toggle);
903                         vc_keymap_toggle = NULL;
904
905                         modified = true;
906                 } else
907                         free(new_keymap);
908         }
909
910         if (modified) {
911                 dbus_bool_t b;
912                 DBusMessage *changed;
913                 int r;
914
915                 r = write_data_vconsole();
916                 if (r < 0)
917                         log_error("Failed to set virtual console keymap: %s", strerror(-r));
918
919                 changed = bus_properties_changed_new(
920                                 "/org/freedesktop/locale1",
921                                 "org.freedesktop.locale1",
922                                 "VConsoleKeymap\0"
923                                 "VConsoleKeymapToggle\0");
924
925                 if (!changed)
926                         return -ENOMEM;
927
928                 b = dbus_connection_send(connection, changed, NULL);
929                 dbus_message_unref(changed);
930
931                 if (!b)
932                         return -ENOMEM;
933
934                 return load_vconsole_keymap(connection, NULL);
935         }
936
937         return 0;
938 }
939
940 static int append_locale(DBusMessageIter *i, const char *property, void *userdata) {
941         int r, c = 0, p;
942         char **l;
943
944         l = new0(char*, _PROP_MAX+1);
945         if (!l)
946                 return -ENOMEM;
947
948         for (p = 0; p < _PROP_MAX; p++) {
949                 char *t;
950
951                 if (isempty(data[p]))
952                         continue;
953
954                 if (asprintf(&t, "%s=%s", names[p], data[p]) < 0) {
955                         strv_free(l);
956                         return -ENOMEM;
957                 }
958
959                 l[c++] = t;
960         }
961
962         r = bus_property_append_strv(i, property, (void*) l);
963         strv_free(l);
964
965         return r;
966 }
967
968 static DBusHandlerResult locale_message_handler(
969                 DBusConnection *connection,
970                 DBusMessage *message,
971                 void *userdata) {
972
973         const BusProperty properties[] = {
974                 { "org.freedesktop.locale1", "Locale",               append_locale,              "as", NULL                   },
975                 { "org.freedesktop.locale1", "X11Layout",            bus_property_append_string, "s",  x11_layout             },
976                 { "org.freedesktop.locale1", "X11Model",             bus_property_append_string, "s",  x11_model              },
977                 { "org.freedesktop.locale1", "X11Variant",           bus_property_append_string, "s",  x11_variant            },
978                 { "org.freedesktop.locale1", "X11Options",           bus_property_append_string, "s",  x11_options            },
979                 { "org.freedesktop.locale1", "VConsoleKeymap",       bus_property_append_string, "s",  vc_keymap              },
980                 { "org.freedesktop.locale1", "VConsoleKeymapToggle", bus_property_append_string, "s",  vc_keymap_toggle       },
981                 { NULL, NULL, NULL, NULL, NULL }
982         };
983
984         DBusMessage *reply = NULL, *changed = NULL;
985         DBusError error;
986         int r;
987
988         assert(connection);
989         assert(message);
990
991         dbus_error_init(&error);
992
993         if (dbus_message_is_method_call(message, "org.freedesktop.locale1", "SetLocale")) {
994                 char **l = NULL, **i;
995                 dbus_bool_t interactive;
996                 DBusMessageIter iter;
997                 bool modified = false;
998                 bool passed[_PROP_MAX];
999                 int p;
1000
1001                 if (!dbus_message_iter_init(message, &iter))
1002                         return bus_send_error_reply(connection, message, NULL, -EINVAL);
1003
1004                 r = bus_parse_strv_iter(&iter, &l);
1005                 if (r < 0) {
1006                         if (r == -ENOMEM)
1007                                 goto oom;
1008
1009                         return bus_send_error_reply(connection, message, NULL, r);
1010                 }
1011
1012                 if (!dbus_message_iter_next(&iter) ||
1013                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_BOOLEAN)  {
1014                         strv_free(l);
1015                         return bus_send_error_reply(connection, message, NULL, -EINVAL);
1016                 }
1017
1018                 dbus_message_iter_get_basic(&iter, &interactive);
1019
1020                 zero(passed);
1021
1022                 /* Check whether a variable changed and if so valid */
1023                 STRV_FOREACH(i, l) {
1024                         bool valid = false;
1025
1026                         for (p = 0; p < _PROP_MAX; p++) {
1027                                 size_t k;
1028
1029                                 k = strlen(names[p]);
1030                                 if (startswith(*i, names[p]) && (*i)[k] == '=') {
1031                                         valid = true;
1032                                         passed[p] = true;
1033
1034                                         if (!streq_ptr(*i + k + 1, data[p]))
1035                                                 modified = true;
1036
1037                                         break;
1038                                 }
1039                         }
1040
1041                         if (!valid) {
1042                                 strv_free(l);
1043                                 return bus_send_error_reply(connection, message, NULL, -EINVAL);
1044                         }
1045                 }
1046
1047                 /* Check whether a variable is unset */
1048                 if (!modified)  {
1049                         for (p = 0; p < _PROP_MAX; p++)
1050                                 if (!isempty(data[p]) && !passed[p]) {
1051                                         modified = true;
1052                                         break;
1053                                 }
1054                 }
1055
1056                 if (modified) {
1057
1058                         r = verify_polkit(connection, message, "org.freedesktop.locale1.set-locale", interactive, &error);
1059                         if (r < 0) {
1060                                 strv_free(l);
1061                                 return bus_send_error_reply(connection, message, &error, r);
1062                         }
1063
1064                         STRV_FOREACH(i, l) {
1065                                 for (p = 0; p < _PROP_MAX; p++) {
1066                                         size_t k;
1067
1068                                         k = strlen(names[p]);
1069                                         if (startswith(*i, names[p]) && (*i)[k] == '=') {
1070                                                 char *t;
1071
1072                                                 t = strdup(*i + k + 1);
1073                                                 if (!t) {
1074                                                         strv_free(l);
1075                                                         goto oom;
1076                                                 }
1077
1078                                                 free(data[p]);
1079                                                 data[p] = t;
1080
1081                                                 break;
1082                                         }
1083                                 }
1084                         }
1085
1086                         strv_free(l);
1087
1088                         for (p = 0; p < _PROP_MAX; p++) {
1089                                 if (passed[p])
1090                                         continue;
1091
1092                                 free(data[p]);
1093                                 data[p] = NULL;
1094                         }
1095
1096                         simplify();
1097
1098                         r = write_data_locale();
1099                         if (r < 0) {
1100                                 log_error("Failed to set locale: %s", strerror(-r));
1101                                 return bus_send_error_reply(connection, message, NULL, r);
1102                         }
1103
1104                         push_data(connection);
1105
1106                         log_info("Changed locale information.");
1107
1108                         changed = bus_properties_changed_new(
1109                                         "/org/freedesktop/locale1",
1110                                         "org.freedesktop.locale1",
1111                                         "Locale\0");
1112                         if (!changed)
1113                                 goto oom;
1114                 }
1115         } else if (dbus_message_is_method_call(message, "org.freedesktop.locale1", "SetVConsoleKeyboard")) {
1116
1117                 const char *keymap, *keymap_toggle;
1118                 dbus_bool_t convert, interactive;
1119
1120                 if (!dbus_message_get_args(
1121                                     message,
1122                                     &error,
1123                                     DBUS_TYPE_STRING, &keymap,
1124                                     DBUS_TYPE_STRING, &keymap_toggle,
1125                                     DBUS_TYPE_BOOLEAN, &convert,
1126                                     DBUS_TYPE_BOOLEAN, &interactive,
1127                                     DBUS_TYPE_INVALID))
1128                         return bus_send_error_reply(connection, message, &error, -EINVAL);
1129
1130                 if (isempty(keymap))
1131                         keymap = NULL;
1132
1133                 if (isempty(keymap_toggle))
1134                         keymap_toggle = NULL;
1135
1136                 if (!streq_ptr(keymap, vc_keymap) ||
1137                     !streq_ptr(keymap_toggle, vc_keymap_toggle)) {
1138
1139                         r = verify_polkit(connection, message, "org.freedesktop.locale1.set-keyboard", interactive, &error);
1140                         if (r < 0)
1141                                 return bus_send_error_reply(connection, message, &error, r);
1142
1143                         if (free_and_set(&vc_keymap, keymap) < 0 ||
1144                             free_and_set(&vc_keymap_toggle, keymap_toggle) < 0)
1145                                 goto oom;
1146
1147                         r = write_data_vconsole();
1148                         if (r < 0) {
1149                                 log_error("Failed to set virtual console keymap: %s", strerror(-r));
1150                                 return bus_send_error_reply(connection, message, NULL, r);
1151                         }
1152
1153                         log_info("Changed virtual console keymap to '%s'", strempty(vc_keymap));
1154
1155                         r = load_vconsole_keymap(connection, NULL);
1156                         if (r < 0)
1157                                 log_error("Failed to request keymap reload: %s", strerror(-r));
1158
1159                         changed = bus_properties_changed_new(
1160                                         "/org/freedesktop/locale1",
1161                                         "org.freedesktop.locale1",
1162                                         "VConsoleKeymap\0"
1163                                         "VConsoleKeymapToggle\0");
1164                         if (!changed)
1165                                 goto oom;
1166
1167                         if (convert) {
1168                                 r = convert_vconsole_to_x11(connection);
1169
1170                                 if (r < 0)
1171                                         log_error("Failed to convert keymap data: %s", strerror(-r));
1172                         }
1173                 }
1174
1175         } else if (dbus_message_is_method_call(message, "org.freedesktop.locale1", "SetX11Keyboard")) {
1176
1177                 const char *layout, *model, *variant, *options;
1178                 dbus_bool_t convert, interactive;
1179
1180                 if (!dbus_message_get_args(
1181                                     message,
1182                                     &error,
1183                                     DBUS_TYPE_STRING, &layout,
1184                                     DBUS_TYPE_STRING, &model,
1185                                     DBUS_TYPE_STRING, &variant,
1186                                     DBUS_TYPE_STRING, &options,
1187                                     DBUS_TYPE_BOOLEAN, &convert,
1188                                     DBUS_TYPE_BOOLEAN, &interactive,
1189                                     DBUS_TYPE_INVALID))
1190                         return bus_send_error_reply(connection, message, &error, -EINVAL);
1191
1192                 if (isempty(layout))
1193                         layout = NULL;
1194
1195                 if (isempty(model))
1196                         model = NULL;
1197
1198                 if (isempty(variant))
1199                         variant = NULL;
1200
1201                 if (isempty(options))
1202                         options = NULL;
1203
1204                 if (!streq_ptr(layout, x11_layout) ||
1205                     !streq_ptr(model, x11_model) ||
1206                     !streq_ptr(variant, x11_variant) ||
1207                     !streq_ptr(options, x11_options)) {
1208
1209                         r = verify_polkit(connection, message, "org.freedesktop.locale1.set-keyboard", interactive, &error);
1210                         if (r < 0)
1211                                 return bus_send_error_reply(connection, message, &error, r);
1212
1213                         if (free_and_set(&x11_layout, layout) < 0 ||
1214                             free_and_set(&x11_model, model) < 0 ||
1215                             free_and_set(&x11_variant, variant) < 0 ||
1216                             free_and_set(&x11_options, options) < 0)
1217                                 goto oom;
1218
1219                         r = write_data_x11();
1220                         if (r < 0) {
1221                                 log_error("Failed to set X11 keyboard layout: %s", strerror(-r));
1222                                 return bus_send_error_reply(connection, message, NULL, r);
1223                         }
1224
1225                         log_info("Changed X11 keyboard layout to '%s'", strempty(x11_layout));
1226
1227                         changed = bus_properties_changed_new(
1228                                         "/org/freedesktop/locale1",
1229                                         "org.freedesktop.locale1",
1230                                         "X11Layout\0"
1231                                         "X11Model\0"
1232                                         "X11Variant\0"
1233                                         "X11Options\0");
1234                         if (!changed)
1235                                 goto oom;
1236
1237                         if (convert) {
1238                                 r = convert_x11_to_vconsole(connection);
1239
1240                                 if (r < 0)
1241                                         log_error("Failed to convert keymap data: %s", strerror(-r));
1242                         }
1243                 }
1244         } else
1245                 return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, properties);
1246
1247
1248         if (!(reply = dbus_message_new_method_return(message)))
1249                 goto oom;
1250
1251         if (!dbus_connection_send(connection, reply, NULL))
1252                 goto oom;
1253
1254         dbus_message_unref(reply);
1255         reply = NULL;
1256
1257         if (changed) {
1258
1259                 if (!dbus_connection_send(connection, changed, NULL))
1260                         goto oom;
1261
1262                 dbus_message_unref(changed);
1263         }
1264
1265         return DBUS_HANDLER_RESULT_HANDLED;
1266
1267 oom:
1268         if (reply)
1269                 dbus_message_unref(reply);
1270
1271         if (changed)
1272                 dbus_message_unref(changed);
1273
1274         dbus_error_free(&error);
1275
1276         return DBUS_HANDLER_RESULT_NEED_MEMORY;
1277 }
1278
1279 static int connect_bus(DBusConnection **_bus) {
1280         static const DBusObjectPathVTable locale_vtable = {
1281                 .message_function = locale_message_handler
1282         };
1283         DBusError error;
1284         DBusConnection *bus = NULL;
1285         int r;
1286
1287         assert(_bus);
1288
1289         dbus_error_init(&error);
1290
1291         bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
1292         if (!bus) {
1293                 log_error("Failed to get system D-Bus connection: %s", bus_error_message(&error));
1294                 r = -ECONNREFUSED;
1295                 goto fail;
1296         }
1297
1298         dbus_connection_set_exit_on_disconnect(bus, FALSE);
1299
1300         if (!dbus_connection_register_object_path(bus, "/org/freedesktop/locale1", &locale_vtable, NULL) ||
1301             !dbus_connection_add_filter(bus, bus_exit_idle_filter, &remain_until, NULL)) {
1302                 log_error("Not enough memory");
1303                 r = -ENOMEM;
1304                 goto fail;
1305         }
1306
1307         r = dbus_bus_request_name(bus, "org.freedesktop.locale1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
1308         if (dbus_error_is_set(&error)) {
1309                 log_error("Failed to register name on bus: %s", bus_error_message(&error));
1310                 r = -EEXIST;
1311                 goto fail;
1312         }
1313
1314         if (r != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
1315                 log_error("Failed to acquire name.");
1316                 r = -EEXIST;
1317                 goto fail;
1318         }
1319
1320         if (_bus)
1321                 *_bus = bus;
1322
1323         return 0;
1324
1325 fail:
1326         dbus_connection_close(bus);
1327         dbus_connection_unref(bus);
1328
1329         dbus_error_free(&error);
1330
1331         return r;
1332 }
1333
1334 int main(int argc, char *argv[]) {
1335         int r;
1336         DBusConnection *bus = NULL;
1337         bool exiting = false;
1338
1339         log_set_target(LOG_TARGET_AUTO);
1340         log_parse_environment();
1341         log_open();
1342
1343         umask(0022);
1344
1345         if (argc == 2 && streq(argv[1], "--introspect")) {
1346                 fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
1347                       "<node>\n", stdout);
1348                 fputs(locale_interface, stdout);
1349                 fputs("</node>\n", stdout);
1350                 return 0;
1351         }
1352
1353         if (argc != 1) {
1354                 log_error("This program takes no arguments.");
1355                 r = -EINVAL;
1356                 goto finish;
1357         }
1358
1359         r = read_data();
1360         if (r < 0) {
1361                 log_error("Failed to read locale data: %s", strerror(-r));
1362                 goto finish;
1363         }
1364
1365         r = connect_bus(&bus);
1366         if (r < 0)
1367                 goto finish;
1368
1369         remain_until = now(CLOCK_MONOTONIC) + DEFAULT_EXIT_USEC;
1370         for (;;) {
1371
1372                 if (!dbus_connection_read_write_dispatch(bus, exiting ? -1 : (int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC)))
1373                         break;
1374
1375                 if (!exiting && remain_until < now(CLOCK_MONOTONIC)) {
1376                         exiting = true;
1377                         bus_async_unregister_and_exit(bus, "org.freedesktop.locale1");
1378                 }
1379         }
1380
1381         r = 0;
1382
1383 finish:
1384         free_data();
1385
1386         if (bus) {
1387                 dbus_connection_flush(bus);
1388                 dbus_connection_close(bus);
1389                 dbus_connection_unref(bus);
1390         }
1391
1392         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1393 }