chiark / gitweb /
remove unused includes
[elogind.git] / src / locale / localectl.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2012 Lennart Poettering
7   Copyright 2013 Kay Sievers
8
9   systemd is free software; you can redistribute it and/or modify it
10   under the terms of the GNU Lesser General Public License as published by
11   the Free Software Foundation; either version 2.1 of the License, or
12   (at your option) any later version.
13
14   systemd is distributed in the hope that it will be useful, but
15   WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17   Lesser General Public License for more details.
18
19   You should have received a copy of the GNU Lesser General Public License
20   along with systemd; If not, see <http://www.gnu.org/licenses/>.
21 ***/
22
23 #include <locale.h>
24 #include <stdlib.h>
25 #include <stdbool.h>
26 #include <getopt.h>
27 #include <string.h>
28 #include <ftw.h>
29
30 #include "sd-bus.h"
31 #include "bus-util.h"
32 #include "bus-error.h"
33 #include "util.h"
34 #include "spawn-polkit-agent.h"
35 #include "build.h"
36 #include "strv.h"
37 #include "pager.h"
38 #include "set.h"
39 #include "def.h"
40 #include "virt.h"
41 #include "fileio.h"
42 #include "locale-util.h"
43
44 static bool arg_no_pager = false;
45 static bool arg_ask_password = true;
46 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
47 static char *arg_host = NULL;
48 static bool arg_convert = true;
49
50 static void pager_open_if_enabled(void) {
51
52         if (arg_no_pager)
53                 return;
54
55         pager_open(false);
56 }
57
58 static void polkit_agent_open_if_enabled(void) {
59
60         /* Open the polkit agent as a child process if necessary */
61         if (!arg_ask_password)
62                 return;
63
64         if (arg_transport != BUS_TRANSPORT_LOCAL)
65                 return;
66
67         polkit_agent_open();
68 }
69
70 typedef struct StatusInfo {
71         char **locale;
72         const char *vconsole_keymap;
73         const char *vconsole_keymap_toggle;
74         const char *x11_layout;
75         const char *x11_model;
76         const char *x11_variant;
77         const char *x11_options;
78 } StatusInfo;
79
80 static void print_overriden_variables(void) {
81         int r;
82         char *variables[_VARIABLE_LC_MAX] = {};
83         LocaleVariable j;
84         bool print_warning = true;
85
86         if (detect_container(NULL) > 0 || arg_host)
87                 return;
88
89         r = parse_env_file("/proc/cmdline", WHITESPACE,
90                            "locale.LANG",              &variables[VARIABLE_LANG],
91                            "locale.LANGUAGE",          &variables[VARIABLE_LANGUAGE],
92                            "locale.LC_CTYPE",          &variables[VARIABLE_LC_CTYPE],
93                            "locale.LC_NUMERIC",        &variables[VARIABLE_LC_NUMERIC],
94                            "locale.LC_TIME",           &variables[VARIABLE_LC_TIME],
95                            "locale.LC_COLLATE",        &variables[VARIABLE_LC_COLLATE],
96                            "locale.LC_MONETARY",       &variables[VARIABLE_LC_MONETARY],
97                            "locale.LC_MESSAGES",       &variables[VARIABLE_LC_MESSAGES],
98                            "locale.LC_PAPER",          &variables[VARIABLE_LC_PAPER],
99                            "locale.LC_NAME",           &variables[VARIABLE_LC_NAME],
100                            "locale.LC_ADDRESS",        &variables[VARIABLE_LC_ADDRESS],
101                            "locale.LC_TELEPHONE",      &variables[VARIABLE_LC_TELEPHONE],
102                            "locale.LC_MEASUREMENT",    &variables[VARIABLE_LC_MEASUREMENT],
103                            "locale.LC_IDENTIFICATION", &variables[VARIABLE_LC_IDENTIFICATION],
104                            NULL);
105
106         if (r < 0 && r != -ENOENT) {
107                 log_warning_errno(r, "Failed to read /proc/cmdline: %m");
108                 goto finish;
109         }
110
111         for (j = 0; j < _VARIABLE_LC_MAX; j++)
112                 if (variables[j]) {
113                         if (print_warning) {
114                                 log_warning("Warning: Settings on kernel command line override system locale settings in /etc/locale.conf.\n"
115                                             "  Command Line: %s=%s", locale_variable_to_string(j), variables[j]);
116
117                                 print_warning = false;
118                         } else
119                                 log_warning("                %s=%s", locale_variable_to_string(j), variables[j]);
120                 }
121  finish:
122         for (j = 0; j < _VARIABLE_LC_MAX; j++)
123                 free(variables[j]);
124 }
125
126 static void print_status_info(StatusInfo *i) {
127         assert(i);
128
129         if (strv_isempty(i->locale))
130                 puts("   System Locale: n/a\n");
131         else {
132                 char **j;
133
134                 printf("   System Locale: %s\n", i->locale[0]);
135                 STRV_FOREACH(j, i->locale + 1)
136                         printf("                  %s\n", *j);
137         }
138
139         printf("       VC Keymap: %s\n", strna(i->vconsole_keymap));
140         if (!isempty(i->vconsole_keymap_toggle))
141                 printf("VC Toggle Keymap: %s\n", i->vconsole_keymap_toggle);
142
143         printf("      X11 Layout: %s\n", strna(i->x11_layout));
144         if (!isempty(i->x11_model))
145                 printf("       X11 Model: %s\n", i->x11_model);
146         if (!isempty(i->x11_variant))
147                 printf("     X11 Variant: %s\n", i->x11_variant);
148         if (!isempty(i->x11_options))
149                 printf("     X11 Options: %s\n", i->x11_options);
150 }
151
152 static int show_status(sd_bus *bus, char **args, unsigned n) {
153         StatusInfo info = {};
154         static const struct bus_properties_map map[]  = {
155                 { "VConsoleKeymap",       "s",  NULL, offsetof(StatusInfo, vconsole_keymap) },
156                 { "VConsoleKeymap",       "s",  NULL, offsetof(StatusInfo, vconsole_keymap) },
157                 { "VConsoleKeymapToggle", "s",  NULL, offsetof(StatusInfo, vconsole_keymap_toggle) },
158                 { "X11Layout",            "s",  NULL, offsetof(StatusInfo, x11_layout) },
159                 { "X11Model",             "s",  NULL, offsetof(StatusInfo, x11_model) },
160                 { "X11Variant",           "s",  NULL, offsetof(StatusInfo, x11_variant) },
161                 { "X11Options",           "s",  NULL, offsetof(StatusInfo, x11_options) },
162                 { "Locale",               "as", NULL, offsetof(StatusInfo, locale) },
163                 {}
164         };
165         int r;
166
167         assert(bus);
168
169         r = bus_map_all_properties(bus,
170                                    "org.freedesktop.locale1",
171                                    "/org/freedesktop/locale1",
172                                    map,
173                                    &info);
174         if (r < 0) {
175                 log_error_errno(r, "Could not get properties: %m");
176                 goto fail;
177         }
178
179         print_overriden_variables();
180         print_status_info(&info);
181
182 fail:
183         strv_free(info.locale);
184         return r;
185 }
186
187 static int set_locale(sd_bus *bus, char **args, unsigned n) {
188         _cleanup_bus_message_unref_ sd_bus_message *m = NULL;
189         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
190         int r;
191
192         assert(bus);
193         assert(args);
194
195         polkit_agent_open_if_enabled();
196
197         r = sd_bus_message_new_method_call(
198                         bus,
199                         &m,
200                         "org.freedesktop.locale1",
201                         "/org/freedesktop/locale1",
202                         "org.freedesktop.locale1",
203                         "SetLocale");
204         if (r < 0)
205                 return bus_log_create_error(r);
206
207         r = sd_bus_message_append_strv(m, args + 1);
208         if (r < 0)
209                 return bus_log_create_error(r);
210
211         r = sd_bus_message_append(m, "b", arg_ask_password);
212         if (r < 0)
213                 return bus_log_create_error(r);
214
215         r = sd_bus_call(bus, m, 0, &error, NULL);
216         if (r < 0) {
217                 log_error("Failed to issue method call: %s", bus_error_message(&error, -r));
218                 return r;
219         }
220
221         return 0;
222 }
223
224 static int list_locales(sd_bus *bus, char **args, unsigned n) {
225         _cleanup_strv_free_ char **l = NULL;
226         int r;
227
228         assert(args);
229
230         r = get_locales(&l);
231         if (r < 0)
232                 return log_error_errno(r, "Failed to read list of locales: %m");
233
234         pager_open_if_enabled();
235         strv_print(l);
236
237         return 0;
238 }
239
240 static int set_vconsole_keymap(sd_bus *bus, char **args, unsigned n) {
241         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
242         const char *map, *toggle_map;
243         int r;
244
245         assert(bus);
246         assert(args);
247
248         if (n > 3) {
249                 log_error("Too many arguments.");
250                 return -EINVAL;
251         }
252
253         polkit_agent_open_if_enabled();
254
255         map = args[1];
256         toggle_map = n > 2 ? args[2] : "";
257
258         r = sd_bus_call_method(
259                         bus,
260                         "org.freedesktop.locale1",
261                         "/org/freedesktop/locale1",
262                         "org.freedesktop.locale1",
263                         "SetVConsoleKeyboard",
264                         &error,
265                         NULL,
266                         "ssbb", map, toggle_map, arg_convert, arg_ask_password);
267         if (r < 0)
268                 log_error("Failed to set keymap: %s", bus_error_message(&error, -r));
269
270         return r;
271 }
272
273 static Set *keymaps = NULL;
274
275 static int nftw_cb(
276                 const char *fpath,
277                 const struct stat *sb,
278                 int tflag,
279                 struct FTW *ftwbuf) {
280
281         char *p, *e;
282         int r;
283
284         if (tflag != FTW_F)
285                 return 0;
286
287         if (!endswith(fpath, ".map") &&
288             !endswith(fpath, ".map.gz"))
289                 return 0;
290
291         p = strdup(basename(fpath));
292         if (!p)
293                 return log_oom();
294
295         e = endswith(p, ".map");
296         if (e)
297                 *e = 0;
298
299         e = endswith(p, ".map.gz");
300         if (e)
301                 *e = 0;
302
303         r = set_consume(keymaps, p);
304         if (r < 0 && r != -EEXIST)
305                 return log_error_errno(r, "Can't add keymap: %m");
306
307         return 0;
308 }
309
310 static int list_vconsole_keymaps(sd_bus *bus, char **args, unsigned n) {
311         _cleanup_strv_free_ char **l = NULL;
312         const char *dir;
313
314         keymaps = set_new(&string_hash_ops);
315         if (!keymaps)
316                 return log_oom();
317
318         NULSTR_FOREACH(dir, KBD_KEYMAP_DIRS)
319                 nftw(dir, nftw_cb, 20, FTW_MOUNT|FTW_PHYS);
320
321         l = set_get_strv(keymaps);
322         if (!l) {
323                 set_free_free(keymaps);
324                 return log_oom();
325         }
326
327         set_free(keymaps);
328
329         if (strv_isempty(l)) {
330                 log_error("Couldn't find any console keymaps.");
331                 return -ENOENT;
332         }
333
334         strv_sort(l);
335
336         pager_open_if_enabled();
337
338         strv_print(l);
339
340         return 0;
341 }
342
343 static int set_x11_keymap(sd_bus *bus, char **args, unsigned n) {
344         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
345         const char *layout, *model, *variant, *options;
346         int r;
347
348         assert(bus);
349         assert(args);
350
351         if (n > 5) {
352                 log_error("Too many arguments.");
353                 return -EINVAL;
354         }
355
356         polkit_agent_open_if_enabled();
357
358         layout = args[1];
359         model = n > 2 ? args[2] : "";
360         variant = n > 3 ? args[3] : "";
361         options = n > 4 ? args[4] : "";
362
363         r = sd_bus_call_method(
364                         bus,
365                         "org.freedesktop.locale1",
366                         "/org/freedesktop/locale1",
367                         "org.freedesktop.locale1",
368                         "SetX11Keyboard",
369                         &error,
370                         NULL,
371                         "ssssbb", layout, model, variant, options,
372                                   arg_convert, arg_ask_password);
373         if (r < 0)
374                 log_error("Failed to set keymap: %s", bus_error_message(&error, -r));
375
376         return r;
377 }
378
379 static int list_x11_keymaps(sd_bus *bus, char **args, unsigned n) {
380         _cleanup_fclose_ FILE *f = NULL;
381         _cleanup_strv_free_ char **list = NULL;
382         char line[LINE_MAX];
383         enum {
384                 NONE,
385                 MODELS,
386                 LAYOUTS,
387                 VARIANTS,
388                 OPTIONS
389         } state = NONE, look_for;
390         int r;
391
392         if (n > 2) {
393                 log_error("Too many arguments.");
394                 return -EINVAL;
395         }
396
397         f = fopen("/usr/share/X11/xkb/rules/base.lst", "re");
398         if (!f)
399                 return log_error_errno(errno, "Failed to open keyboard mapping list. %m");
400
401         if (streq(args[0], "list-x11-keymap-models"))
402                 look_for = MODELS;
403         else if (streq(args[0], "list-x11-keymap-layouts"))
404                 look_for = LAYOUTS;
405         else if (streq(args[0], "list-x11-keymap-variants"))
406                 look_for = VARIANTS;
407         else if (streq(args[0], "list-x11-keymap-options"))
408                 look_for = OPTIONS;
409         else
410                 assert_not_reached("Wrong parameter");
411
412         FOREACH_LINE(line, f, break) {
413                 char *l, *w;
414
415                 l = strstrip(line);
416
417                 if (isempty(l))
418                         continue;
419
420                 if (l[0] == '!') {
421                         if (startswith(l, "! model"))
422                                 state = MODELS;
423                         else if (startswith(l, "! layout"))
424                                 state = LAYOUTS;
425                         else if (startswith(l, "! variant"))
426                                 state = VARIANTS;
427                         else if (startswith(l, "! option"))
428                                 state = OPTIONS;
429                         else
430                                 state = NONE;
431
432                         continue;
433                 }
434
435                 if (state != look_for)
436                         continue;
437
438                 w = l + strcspn(l, WHITESPACE);
439
440                 if (n > 1) {
441                         char *e;
442
443                         if (*w == 0)
444                                 continue;
445
446                         *w = 0;
447                         w++;
448                         w += strspn(w, WHITESPACE);
449
450                         e = strchr(w, ':');
451                         if (!e)
452                                 continue;
453
454                         *e = 0;
455
456                         if (!streq(w, args[1]))
457                                 continue;
458                 } else
459                         *w = 0;
460
461                  r = strv_extend(&list, l);
462                  if (r < 0)
463                          return log_oom();
464         }
465
466         if (strv_isempty(list)) {
467                 log_error("Couldn't find any entries.");
468                 return -ENOENT;
469         }
470
471         strv_sort(list);
472         strv_uniq(list);
473
474         pager_open_if_enabled();
475
476         strv_print(list);
477         return 0;
478 }
479
480 static void help(void) {
481         printf("%s [OPTIONS...] COMMAND ...\n\n"
482                "Query or change system locale and keyboard settings.\n\n"
483                "  -h --help                Show this help\n"
484                "     --version             Show package version\n"
485                "     --no-pager            Do not pipe output into a pager\n"
486                "     --no-ask-password     Do not prompt for password\n"
487                "  -H --host=[USER@]HOST    Operate on remote host\n"
488                "  -M --machine=CONTAINER   Operate on local container\n"
489                "     --no-convert          Don't convert keyboard mappings\n\n"
490                "Commands:\n"
491                "  status                   Show current locale settings\n"
492                "  set-locale LOCALE...     Set system locale\n"
493                "  list-locales             Show known locales\n"
494                "  set-keymap MAP [MAP]     Set console and X11 keyboard mappings\n"
495                "  list-keymaps             Show known virtual console keyboard mappings\n"
496                "  set-x11-keymap LAYOUT [MODEL [VARIANT [OPTIONS]]]\n"
497                "                           Set X11 and console keyboard mappings\n"
498                "  list-x11-keymap-models   Show known X11 keyboard mapping models\n"
499                "  list-x11-keymap-layouts  Show known X11 keyboard mapping layouts\n"
500                "  list-x11-keymap-variants [LAYOUT]\n"
501                "                           Show known X11 keyboard mapping variants\n"
502                "  list-x11-keymap-options  Show known X11 keyboard mapping options\n"
503                , program_invocation_short_name);
504 }
505
506 static int parse_argv(int argc, char *argv[]) {
507
508         enum {
509                 ARG_VERSION = 0x100,
510                 ARG_NO_PAGER,
511                 ARG_NO_CONVERT,
512                 ARG_NO_ASK_PASSWORD
513         };
514
515         static const struct option options[] = {
516                 { "help",            no_argument,       NULL, 'h'                 },
517                 { "version",         no_argument,       NULL, ARG_VERSION         },
518                 { "no-pager",        no_argument,       NULL, ARG_NO_PAGER        },
519                 { "host",            required_argument, NULL, 'H'                 },
520                 { "machine",         required_argument, NULL, 'M'                 },
521                 { "no-ask-password", no_argument,       NULL, ARG_NO_ASK_PASSWORD },
522                 { "no-convert",      no_argument,       NULL, ARG_NO_CONVERT      },
523                 {}
524         };
525
526         int c;
527
528         assert(argc >= 0);
529         assert(argv);
530
531         while ((c = getopt_long(argc, argv, "hH:M:", options, NULL)) >= 0)
532
533                 switch (c) {
534
535                 case 'h':
536                         help();
537                         return 0;
538
539                 case ARG_VERSION:
540                         puts(PACKAGE_STRING);
541                         puts(SYSTEMD_FEATURES);
542                         return 0;
543
544                 case ARG_NO_CONVERT:
545                         arg_convert = false;
546                         break;
547
548                 case ARG_NO_PAGER:
549                         arg_no_pager = true;
550                         break;
551
552                 case ARG_NO_ASK_PASSWORD:
553                         arg_ask_password = false;
554                         break;
555
556                 case 'H':
557                         arg_transport = BUS_TRANSPORT_REMOTE;
558                         arg_host = optarg;
559                         break;
560
561                 case 'M':
562                         arg_transport = BUS_TRANSPORT_MACHINE;
563                         arg_host = optarg;
564                         break;
565
566                 case '?':
567                         return -EINVAL;
568
569                 default:
570                         assert_not_reached("Unhandled option");
571                 }
572
573         return 1;
574 }
575
576 static int localectl_main(sd_bus *bus, int argc, char *argv[]) {
577
578         static const struct {
579                 const char* verb;
580                 const enum {
581                         MORE,
582                         LESS,
583                         EQUAL
584                 } argc_cmp;
585                 const int argc;
586                 int (* const dispatch)(sd_bus *bus, char **args, unsigned n);
587         } verbs[] = {
588                 { "status",                   LESS,   1, show_status           },
589                 { "set-locale",               MORE,   2, set_locale            },
590                 { "list-locales",             EQUAL,  1, list_locales          },
591                 { "set-keymap",               MORE,   2, set_vconsole_keymap   },
592                 { "list-keymaps",             EQUAL,  1, list_vconsole_keymaps },
593                 { "set-x11-keymap",           MORE,   2, set_x11_keymap        },
594                 { "list-x11-keymap-models",   EQUAL,  1, list_x11_keymaps      },
595                 { "list-x11-keymap-layouts",  EQUAL,  1, list_x11_keymaps      },
596                 { "list-x11-keymap-variants", LESS,   2, list_x11_keymaps      },
597                 { "list-x11-keymap-options",  EQUAL,  1, list_x11_keymaps      },
598         };
599
600         int left;
601         unsigned i;
602
603         assert(argc >= 0);
604         assert(argv);
605
606         left = argc - optind;
607
608         if (left <= 0)
609                 /* Special rule: no arguments means "status" */
610                 i = 0;
611         else {
612                 if (streq(argv[optind], "help")) {
613                         help();
614                         return 0;
615                 }
616
617                 for (i = 0; i < ELEMENTSOF(verbs); i++)
618                         if (streq(argv[optind], verbs[i].verb))
619                                 break;
620
621                 if (i >= ELEMENTSOF(verbs)) {
622                         log_error("Unknown operation %s", argv[optind]);
623                         return -EINVAL;
624                 }
625         }
626
627         switch (verbs[i].argc_cmp) {
628
629         case EQUAL:
630                 if (left != verbs[i].argc) {
631                         log_error("Invalid number of arguments.");
632                         return -EINVAL;
633                 }
634
635                 break;
636
637         case MORE:
638                 if (left < verbs[i].argc) {
639                         log_error("Too few arguments.");
640                         return -EINVAL;
641                 }
642
643                 break;
644
645         case LESS:
646                 if (left > verbs[i].argc) {
647                         log_error("Too many arguments.");
648                         return -EINVAL;
649                 }
650
651                 break;
652
653         default:
654                 assert_not_reached("Unknown comparison operator.");
655         }
656
657         return verbs[i].dispatch(bus, argv + optind, left);
658 }
659
660 int main(int argc, char*argv[]) {
661         _cleanup_bus_close_unref_ sd_bus *bus = NULL;
662         int r;
663
664         setlocale(LC_ALL, "");
665         log_parse_environment();
666         log_open();
667
668         r = parse_argv(argc, argv);
669         if (r <= 0)
670                 goto finish;
671
672         r = bus_open_transport(arg_transport, arg_host, false, &bus);
673         if (r < 0) {
674                 log_error_errno(r, "Failed to create bus connection: %m");
675                 goto finish;
676         }
677
678         r = localectl_main(bus, argc, argv);
679
680 finish:
681         pager_close();
682
683         return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
684 }