chiark / gitweb /
e627c3a716e4bd7baac16898cc1d7f536d0d0bc2
[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                                 /* If we got an exact match, this is best */
865                                 matching = 10;
866                         else {
867                                 size_t x;
868
869                                 x = strcspn(x11_layout, ",");
870
871                                 /* We have multiple X layouts, look
872                                  * for an entry that matches our key
873                                  * with the everything but the first
874                                  * layout stripped off. */
875                                 if (x > 0 &&
876                                     strlen(a[1]) == x &&
877                                     strncmp(x11_layout, a[1], x) == 0)
878                                         matching = 5;
879                                 else  {
880                                         size_t w;
881
882                                         /* If that didn't work, strip
883                                          * off the other layouts from
884                                          * the entry, too */
885
886                                         w = strcspn(a[1], ",");
887
888                                         if (x > 0 && x == w &&
889                                             memcmp(x11_layout, a[1], x) == 0)
890                                                 matching = 1;
891                                 }
892                         }
893
894                         if (matching > 0 &&
895                             streq_ptr(x11_model, a[2])) {
896                                 matching++;
897
898                                 if (streq_ptr(x11_variant, a[3])) {
899                                         matching++;
900
901                                         if (streq_ptr(x11_options, a[4]))
902                                                 matching++;
903                                 }
904                         }
905
906                         /* The best matching entry so far, then let's
907                          * save that */
908                         if (matching > best_matching) {
909                                 best_matching = matching;
910
911                                 free(new_keymap);
912                                 new_keymap = strdup(a[0]);
913
914                                 if (!new_keymap) {
915                                         strv_free(a);
916                                         fclose(f);
917                                         return -ENOMEM;
918                                 }
919                         }
920
921                         strv_free(a);
922                 }
923
924                 fclose(f);
925
926                 if (!streq_ptr(vc_keymap, new_keymap)) {
927                         free(vc_keymap);
928                         vc_keymap = new_keymap;
929
930                         free(vc_keymap_toggle);
931                         vc_keymap_toggle = NULL;
932
933                         modified = true;
934                 } else
935                         free(new_keymap);
936         }
937
938         if (modified) {
939                 dbus_bool_t b;
940                 DBusMessage *changed;
941                 int r;
942
943                 r = write_data_vconsole();
944                 if (r < 0)
945                         log_error("Failed to set virtual console keymap: %s", strerror(-r));
946
947                 changed = bus_properties_changed_new(
948                                 "/org/freedesktop/locale1",
949                                 "org.freedesktop.locale1",
950                                 "VConsoleKeymap\0"
951                                 "VConsoleKeymapToggle\0");
952
953                 if (!changed)
954                         return -ENOMEM;
955
956                 b = dbus_connection_send(connection, changed, NULL);
957                 dbus_message_unref(changed);
958
959                 if (!b)
960                         return -ENOMEM;
961
962                 return load_vconsole_keymap(connection, NULL);
963         }
964
965         return 0;
966 }
967
968 static int append_locale(DBusMessageIter *i, const char *property, void *userdata) {
969         int r, c = 0, p;
970         char **l;
971
972         l = new0(char*, _PROP_MAX+1);
973         if (!l)
974                 return -ENOMEM;
975
976         for (p = 0; p < _PROP_MAX; p++) {
977                 char *t;
978
979                 if (isempty(data[p]))
980                         continue;
981
982                 if (asprintf(&t, "%s=%s", names[p], data[p]) < 0) {
983                         strv_free(l);
984                         return -ENOMEM;
985                 }
986
987                 l[c++] = t;
988         }
989
990         r = bus_property_append_strv(i, property, (void*) l);
991         strv_free(l);
992
993         return r;
994 }
995
996 static DBusHandlerResult locale_message_handler(
997                 DBusConnection *connection,
998                 DBusMessage *message,
999                 void *userdata) {
1000
1001         const BusProperty properties[] = {
1002                 { "org.freedesktop.locale1", "Locale",               append_locale,              "as", NULL                   },
1003                 { "org.freedesktop.locale1", "X11Layout",            bus_property_append_string, "s",  x11_layout             },
1004                 { "org.freedesktop.locale1", "X11Model",             bus_property_append_string, "s",  x11_model              },
1005                 { "org.freedesktop.locale1", "X11Variant",           bus_property_append_string, "s",  x11_variant            },
1006                 { "org.freedesktop.locale1", "X11Options",           bus_property_append_string, "s",  x11_options            },
1007                 { "org.freedesktop.locale1", "VConsoleKeymap",       bus_property_append_string, "s",  vc_keymap              },
1008                 { "org.freedesktop.locale1", "VConsoleKeymapToggle", bus_property_append_string, "s",  vc_keymap_toggle       },
1009                 { NULL, NULL, NULL, NULL, NULL }
1010         };
1011
1012         DBusMessage *reply = NULL, *changed = NULL;
1013         DBusError error;
1014         int r;
1015
1016         assert(connection);
1017         assert(message);
1018
1019         dbus_error_init(&error);
1020
1021         if (dbus_message_is_method_call(message, "org.freedesktop.locale1", "SetLocale")) {
1022                 char **l = NULL, **i;
1023                 dbus_bool_t interactive;
1024                 DBusMessageIter iter;
1025                 bool modified = false;
1026                 bool passed[_PROP_MAX];
1027                 int p;
1028
1029                 if (!dbus_message_iter_init(message, &iter))
1030                         return bus_send_error_reply(connection, message, NULL, -EINVAL);
1031
1032                 r = bus_parse_strv_iter(&iter, &l);
1033                 if (r < 0) {
1034                         if (r == -ENOMEM)
1035                                 goto oom;
1036
1037                         return bus_send_error_reply(connection, message, NULL, r);
1038                 }
1039
1040                 if (!dbus_message_iter_next(&iter) ||
1041                     dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_BOOLEAN)  {
1042                         strv_free(l);
1043                         return bus_send_error_reply(connection, message, NULL, -EINVAL);
1044                 }
1045
1046                 dbus_message_iter_get_basic(&iter, &interactive);
1047
1048                 zero(passed);
1049
1050                 /* Check whether a variable changed and if so valid */
1051                 STRV_FOREACH(i, l) {
1052                         bool valid = false;
1053
1054                         for (p = 0; p < _PROP_MAX; p++) {
1055                                 size_t k;
1056
1057                                 k = strlen(names[p]);
1058                                 if (startswith(*i, names[p]) && (*i)[k] == '=') {
1059                                         valid = true;
1060                                         passed[p] = true;
1061
1062                                         if (!streq_ptr(*i + k + 1, data[p]))
1063                                                 modified = true;
1064
1065                                         break;
1066                                 }
1067                         }
1068
1069                         if (!valid) {
1070                                 strv_free(l);
1071                                 return bus_send_error_reply(connection, message, NULL, -EINVAL);
1072                         }
1073                 }
1074
1075                 /* Check whether a variable is unset */
1076                 if (!modified)  {
1077                         for (p = 0; p < _PROP_MAX; p++)
1078                                 if (!isempty(data[p]) && !passed[p]) {
1079                                         modified = true;
1080                                         break;
1081                                 }
1082                 }
1083
1084                 if (modified) {
1085
1086                         r = verify_polkit(connection, message, "org.freedesktop.locale1.set-locale", interactive, &error);
1087                         if (r < 0) {
1088                                 strv_free(l);
1089                                 return bus_send_error_reply(connection, message, &error, r);
1090                         }
1091
1092                         STRV_FOREACH(i, l) {
1093                                 for (p = 0; p < _PROP_MAX; p++) {
1094                                         size_t k;
1095
1096                                         k = strlen(names[p]);
1097                                         if (startswith(*i, names[p]) && (*i)[k] == '=') {
1098                                                 char *t;
1099
1100                                                 t = strdup(*i + k + 1);
1101                                                 if (!t) {
1102                                                         strv_free(l);
1103                                                         goto oom;
1104                                                 }
1105
1106                                                 free(data[p]);
1107                                                 data[p] = t;
1108
1109                                                 break;
1110                                         }
1111                                 }
1112                         }
1113
1114                         strv_free(l);
1115
1116                         for (p = 0; p < _PROP_MAX; p++) {
1117                                 if (passed[p])
1118                                         continue;
1119
1120                                 free(data[p]);
1121                                 data[p] = NULL;
1122                         }
1123
1124                         simplify();
1125
1126                         r = write_data_locale();
1127                         if (r < 0) {
1128                                 log_error("Failed to set locale: %s", strerror(-r));
1129                                 return bus_send_error_reply(connection, message, NULL, r);
1130                         }
1131
1132                         push_data(connection);
1133
1134                         log_info("Changed locale information.");
1135
1136                         changed = bus_properties_changed_new(
1137                                         "/org/freedesktop/locale1",
1138                                         "org.freedesktop.locale1",
1139                                         "Locale\0");
1140                         if (!changed)
1141                                 goto oom;
1142                 }
1143         } else if (dbus_message_is_method_call(message, "org.freedesktop.locale1", "SetVConsoleKeyboard")) {
1144
1145                 const char *keymap, *keymap_toggle;
1146                 dbus_bool_t convert, interactive;
1147
1148                 if (!dbus_message_get_args(
1149                                     message,
1150                                     &error,
1151                                     DBUS_TYPE_STRING, &keymap,
1152                                     DBUS_TYPE_STRING, &keymap_toggle,
1153                                     DBUS_TYPE_BOOLEAN, &convert,
1154                                     DBUS_TYPE_BOOLEAN, &interactive,
1155                                     DBUS_TYPE_INVALID))
1156                         return bus_send_error_reply(connection, message, &error, -EINVAL);
1157
1158                 if (isempty(keymap))
1159                         keymap = NULL;
1160
1161                 if (isempty(keymap_toggle))
1162                         keymap_toggle = NULL;
1163
1164                 if (!streq_ptr(keymap, vc_keymap) ||
1165                     !streq_ptr(keymap_toggle, vc_keymap_toggle)) {
1166
1167                         r = verify_polkit(connection, message, "org.freedesktop.locale1.set-keyboard", interactive, &error);
1168                         if (r < 0)
1169                                 return bus_send_error_reply(connection, message, &error, r);
1170
1171                         if (free_and_set(&vc_keymap, keymap) < 0 ||
1172                             free_and_set(&vc_keymap_toggle, keymap_toggle) < 0)
1173                                 goto oom;
1174
1175                         r = write_data_vconsole();
1176                         if (r < 0) {
1177                                 log_error("Failed to set virtual console keymap: %s", strerror(-r));
1178                                 return bus_send_error_reply(connection, message, NULL, r);
1179                         }
1180
1181                         log_info("Changed virtual console keymap to '%s'", strempty(vc_keymap));
1182
1183                         r = load_vconsole_keymap(connection, NULL);
1184                         if (r < 0)
1185                                 log_error("Failed to request keymap reload: %s", strerror(-r));
1186
1187                         changed = bus_properties_changed_new(
1188                                         "/org/freedesktop/locale1",
1189                                         "org.freedesktop.locale1",
1190                                         "VConsoleKeymap\0"
1191                                         "VConsoleKeymapToggle\0");
1192                         if (!changed)
1193                                 goto oom;
1194
1195                         if (convert) {
1196                                 r = convert_vconsole_to_x11(connection);
1197
1198                                 if (r < 0)
1199                                         log_error("Failed to convert keymap data: %s", strerror(-r));
1200                         }
1201                 }
1202
1203         } else if (dbus_message_is_method_call(message, "org.freedesktop.locale1", "SetX11Keyboard")) {
1204
1205                 const char *layout, *model, *variant, *options;
1206                 dbus_bool_t convert, interactive;
1207
1208                 if (!dbus_message_get_args(
1209                                     message,
1210                                     &error,
1211                                     DBUS_TYPE_STRING, &layout,
1212                                     DBUS_TYPE_STRING, &model,
1213                                     DBUS_TYPE_STRING, &variant,
1214                                     DBUS_TYPE_STRING, &options,
1215                                     DBUS_TYPE_BOOLEAN, &convert,
1216                                     DBUS_TYPE_BOOLEAN, &interactive,
1217                                     DBUS_TYPE_INVALID))
1218                         return bus_send_error_reply(connection, message, &error, -EINVAL);
1219
1220                 if (isempty(layout))
1221                         layout = NULL;
1222
1223                 if (isempty(model))
1224                         model = NULL;
1225
1226                 if (isempty(variant))
1227                         variant = NULL;
1228
1229                 if (isempty(options))
1230                         options = NULL;
1231
1232                 if (!streq_ptr(layout, x11_layout) ||
1233                     !streq_ptr(model, x11_model) ||
1234                     !streq_ptr(variant, x11_variant) ||
1235                     !streq_ptr(options, x11_options)) {
1236
1237                         r = verify_polkit(connection, message, "org.freedesktop.locale1.set-keyboard", interactive, &error);
1238                         if (r < 0)
1239                                 return bus_send_error_reply(connection, message, &error, r);
1240
1241                         if (free_and_set(&x11_layout, layout) < 0 ||
1242                             free_and_set(&x11_model, model) < 0 ||
1243                             free_and_set(&x11_variant, variant) < 0 ||
1244                             free_and_set(&x11_options, options) < 0)
1245                                 goto oom;
1246
1247                         r = write_data_x11();
1248                         if (r < 0) {
1249                                 log_error("Failed to set X11 keyboard layout: %s", strerror(-r));
1250                                 return bus_send_error_reply(connection, message, NULL, r);
1251                         }
1252
1253                         log_info("Changed X11 keyboard layout to '%s'", strempty(x11_layout));
1254
1255                         changed = bus_properties_changed_new(
1256                                         "/org/freedesktop/locale1",
1257                                         "org.freedesktop.locale1",
1258                                         "X11Layout\0"
1259                                         "X11Model\0"
1260                                         "X11Variant\0"
1261                                         "X11Options\0");
1262                         if (!changed)
1263                                 goto oom;
1264
1265                         if (convert) {
1266                                 r = convert_x11_to_vconsole(connection);
1267
1268                                 if (r < 0)
1269                                         log_error("Failed to convert keymap data: %s", strerror(-r));
1270                         }
1271                 }
1272         } else
1273                 return bus_default_message_handler(connection, message, INTROSPECTION, INTERFACES_LIST, properties);
1274
1275
1276         if (!(reply = dbus_message_new_method_return(message)))
1277                 goto oom;
1278
1279         if (!dbus_connection_send(connection, reply, NULL))
1280                 goto oom;
1281
1282         dbus_message_unref(reply);
1283         reply = NULL;
1284
1285         if (changed) {
1286
1287                 if (!dbus_connection_send(connection, changed, NULL))
1288                         goto oom;
1289
1290                 dbus_message_unref(changed);
1291         }
1292
1293         return DBUS_HANDLER_RESULT_HANDLED;
1294
1295 oom:
1296         if (reply)
1297                 dbus_message_unref(reply);
1298
1299         if (changed)
1300                 dbus_message_unref(changed);
1301
1302         dbus_error_free(&error);
1303
1304         return DBUS_HANDLER_RESULT_NEED_MEMORY;
1305 }
1306
1307 static int connect_bus(DBusConnection **_bus) {
1308         static const DBusObjectPathVTable locale_vtable = {
1309                 .message_function = locale_message_handler
1310         };
1311         DBusError error;
1312         DBusConnection *bus = NULL;
1313         int r;
1314
1315         assert(_bus);
1316
1317         dbus_error_init(&error);
1318
1319         bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
1320         if (!bus) {
1321                 log_error("Failed to get system D-Bus connection: %s", bus_error_message(&error));
1322                 r = -ECONNREFUSED;
1323                 goto fail;
1324         }
1325
1326         dbus_connection_set_exit_on_disconnect(bus, FALSE);
1327
1328         if (!dbus_connection_register_object_path(bus, "/org/freedesktop/locale1", &locale_vtable, NULL) ||
1329             !dbus_connection_add_filter(bus, bus_exit_idle_filter, &remain_until, NULL)) {
1330                 log_error("Not enough memory");
1331                 r = -ENOMEM;
1332                 goto fail;
1333         }
1334
1335         r = dbus_bus_request_name(bus, "org.freedesktop.locale1", DBUS_NAME_FLAG_DO_NOT_QUEUE, &error);
1336         if (dbus_error_is_set(&error)) {
1337                 log_error("Failed to register name on bus: %s", bus_error_message(&error));
1338                 r = -EEXIST;
1339                 goto fail;
1340         }
1341
1342         if (r != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER) {
1343                 log_error("Failed to acquire name.");
1344                 r = -EEXIST;
1345                 goto fail;
1346         }
1347
1348         if (_bus)
1349                 *_bus = bus;
1350
1351         return 0;
1352
1353 fail:
1354         dbus_connection_close(bus);
1355         dbus_connection_unref(bus);
1356
1357         dbus_error_free(&error);
1358
1359         return r;
1360 }
1361
1362 int main(int argc, char *argv[]) {
1363         int r;
1364         DBusConnection *bus = NULL;
1365         bool exiting = false;
1366
1367         log_set_target(LOG_TARGET_AUTO);
1368         log_parse_environment();
1369         log_open();
1370
1371         umask(0022);
1372
1373         if (argc == 2 && streq(argv[1], "--introspect")) {
1374                 fputs(DBUS_INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE
1375                       "<node>\n", stdout);
1376                 fputs(locale_interface, stdout);
1377                 fputs("</node>\n", stdout);
1378                 return 0;
1379         }
1380
1381         if (argc != 1) {
1382                 log_error("This program takes no arguments.");
1383                 r = -EINVAL;
1384                 goto finish;
1385         }
1386
1387         r = read_data();
1388         if (r < 0) {
1389                 log_error("Failed to read locale data: %s", strerror(-r));
1390                 goto finish;
1391         }
1392
1393         r = connect_bus(&bus);
1394         if (r < 0)
1395                 goto finish;
1396
1397         remain_until = now(CLOCK_MONOTONIC) + DEFAULT_EXIT_USEC;
1398         for (;;) {
1399
1400                 if (!dbus_connection_read_write_dispatch(bus, exiting ? -1 : (int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC)))
1401                         break;
1402
1403                 if (!exiting && remain_until < now(CLOCK_MONOTONIC)) {
1404                         exiting = true;
1405                         bus_async_unregister_and_exit(bus, "org.freedesktop.locale1");
1406                 }
1407         }
1408
1409         r = 0;
1410
1411 finish:
1412         free_data();
1413
1414         if (bus) {
1415                 dbus_connection_flush(bus);
1416                 dbus_connection_close(bus);
1417                 dbus_connection_unref(bus);
1418         }
1419
1420         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
1421 }