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